Python Loops




What is a Loop?

A loop is a sequence or order of instructions that are frequently repeated until a certain condition reached.

Types of loops in Python:

1.for loop

2.while loop

3.nested loop

for loop:

for( i =0;i<n;i++) —–> Which is not implemented in Python

>>> for i range(3)
>>>print(i)
Output: 
0
1
2
3
>>> for i in range(1,4)
>>>print(i)
1
2
3

Examples:

for_example_demo.py

1. To do the operation on each and every element of a list

a=[1,2,3,4,5]
b=0
for i in a;
b=b+i
print(b)

2.Return to list

a=[1,2,3,4,5]
for i in a;
print(i**2)
b=[(i**2)for i in a]
print(b)

for with if:

student_marks = [10,36,53,28,90]
for data in student_marks:
                if(data%2==0)
                       print(data, "is even number")
                else:
                       print(data,"is odd number")

for loop with else clause:

numbers = [10,20,30,40,50,60]
for i in numbers:
            print(i)
else:
           print("Loop completed ")

Looping control statement: A statement that converts the execution of loop from its designated cycle is called a loop control statement. The best example is the Break.

Break:

To break out the loop we can use a break function

syntax:

for variablie_name in sequence:

statement1

statement2

if(condition):

break




Example

>>>list = [10,20,30,40,50]
>>>for i in list:
            if(i==40)
                break
          print(i)

Continue statement:

Continue statement is used, Python to jump to the next iteration of a loop.

Example:
list = [10,20,30,40,50]
for i in list:
         if(i==40)
                continue
                 print(i)
          else:
             print("completed")

While Loop:

While loop is used to execute no.of statements till the condition passed in while loop once a condition is false, the control will come out the loop.

syntax:

while<expression>:

statement1

statement2

>>>while(i<n):
     print(i)

infinite loop

while else loop:

a =int(input("Enter integer less 100\n"))
print(a)

 


Summary: In Python programming language loops are very useful while using programs. In Loops will improve our logical thinking also. Python loops are very simple to learn and improve. Here only tell to for loop and while because these two are a major role in loops environment in Python Programming language

Python Data Types



Python Simple DataTypes:

A datatype represents the type of data stored into a variable or memory in Python also.

Basically, Python has inbuilt datatypes – Already available in python.

And User-defined datatypes – Datatypes created by programmers.

I). Built-in datatypes:

*None Type

*Numeric Types    – int, float, complex

*Sequences         – str, bytes, list, tuple, etc.

*Sets                       – set, frozenset

*Mapping             – dict

None :

‘None’ datatype represents an object that does not contain any value.

In Java – NULL

In Python – None

Numeric datatypes:

1.int:

It represents an integer number

It is number without the decimal part and fraction part.

Example:

 >>> x=100

>>>type(x)

<class 'int'>

2.float:

Float represents a floating number

A floating number contains decimal part

Example: 

>>>x=100.25

>>>type(x)

<class 'float>

3.Complex Data type:

The complex number is number that is written in the form of a+bJ or a+bj

a: real part

b: imaginary part

Example: 

>>>a=1+3j

>>>b=5+7j

>>>c=a+b

>>>print(c)

(4+10j)

Bool data  type:

The bool data type in Python represents boolean values.

>>>a=20

>>>b=10

>>>print(a>b)

True



Sequences in Python:

A sequence represents a group of elements or items.

Mainly 6 types of sequences in Python:

1.str

2.bytes

3.bytearray

4.list

5.tuple

6.range

Sets:

A set is an unordered collection of elements that is a set. Set does not accept duplicate elements.

Here two types of sets

1.Set datatype:

Set elements should be separated with a comma(,)

Set always print only unique elements.

Example :

>>>a={100,200,300,400,500,100,100}

>>>print(a)

{100,200,300,400,500}

2.frozenset datatype:

Frozenset datatype is a create frozenset bypassing set data

Cannot be modified(update and remove methods will not work)

Example:

>>>x={500,600,700,800}

>>>y=frozenset(x)

>>>type(y)

<class 'frozenset'>
>>>print(y)
frozenset({500,600,700,800})

Mapping Type:

A map represents a group of elements in the form of key-value pairs so that when a key is given will retrieve a value

The dict datatype is an example of a map. Dict represents a dictionary that contains a pair of elements first one is Key and second one is Value.

Example:

>>>d={10:"Vijay",20:"Murali"}

>>>print(d)

>>>d[10]

"Vijay"

>>>type(d)

<class 'dict'>



Python Variable



Python Variable:

Think of any number is a variable in Python. Let’s store it for later. When you think of that number, you are holding that value in your head.

It means that capable of being varied or changed.

A variable is a memory location where a programmer can store a value.

Example: Emp no, Emp name etc.

Value is either a string or numeric etc

Example: “Vijay”, 2456

Variables are created when first assigned.

The interpreter allocates memory on the basis of the data type of variable.

The type(string, int, float etc) of the variable is determined by Python.

Simple Rules for Python Variables:

1. Must begin with a letter (a-z, A-Z) or (_)

Examples:

>>>@@@EmpNumber =10134

SyntaxError: invalid syntax

>>>_EmpNumber =10134

>>>print(_EmpNumber)

10134

2.Must not contain any special characters like ! , @,#,$ etc.

Examples:

>>>Vijay@=48

SyntaxError: invalid syntax

>>>@@@=0

SyntaxError: invalid syntax

3.Case sensitive

Examples:

>>> product_name = “Phone”

>>>print(Product_name)

Traceback(most recent call last):

File “<pyshell#26>” line 1 in <module>

print(Product_name)

NameError: name ‘Product_name’ is not defined

>>>print(PRODUCT_NAME)

Traceback(most recent call last):

File “<pyshell#27>” line 1 in <module>

print(PRODUCT_NAME)

NameError: name ‘PRODUCT_NAME’ is not defined

4. There are some reserved keywords which you cannot use as a variable name because Python uses them for other things.

Examples:

>>>for = 100

SyntaxError: invalid syntax

Good Variable Name :

I) Choose a meaningful name instead of short names.

II) Maintain the length of a variable name

III) Begin a variable name with an underscore(_) character for a special case.

Multi Assignment:

a = 100

print (a)

Name = ‘Vijay’

Age = 27

a=b=c=1

print(a)

print(b)

print(c)

Swaping variable

Syntax:

var 1, var 2= var 2, var 1

>>>x=100

>>>y=200

>>>print(x)

100

>>>x,y=y,x

>>>print(x)

20

>>>print(y)

30

Input Function:

Examples:

>>>a=input()

100

>>>print(a)

100

>>>age = input(“Enter your age\n”)

Enter your age

27

>>>print(age)

27

Summary: Python Variables are very useful for Python learners and simple to learn for developers. In all programming languages variables are almost same the major difference is syntax only. Python is simple to learn for developers also. It is an easiest programming language.

 

 

 

 

 

 

 


Python



What is Python?

1. Python is an easy to learn, powerful programming language. The application development process much faster and easier.

2. The  Python was coined in the late 1980s and its development was started in December 1989 by Guido van Rossum at the Netherlands.

3. Python was named for the BBC TV show Monty Python’s Flying Circus.

Why Python?

1.Easy to understand

2.Beginners Language

3.Less Time Complexity

4.Portable

5.Simple to implement

6. Fully libraries support

Features of Python

1.Interpreted language

2.Easy to learn and use

3.Expressive language

4.Opensource and Free to install

5.Object-Oriented language

6.GUI programming(Tkinter)

Python Packages:

1.Web development – Django, Web2py, Flask frameworks etc.

2.Bigdata – PySpark, DASK etc.

3.Artificial Intelligence – Keras, Scikit, OpenCV

4.GUI – Tkinter

5.Desktop Applications – Jython, WxPython

6.Testing – Splitter Tool, Pytest framework

7.Game development – Pygame

Python Implementation alternatives.

1.CPython(standard implementation of Python)

2.Jython(Python for Java)

3.Stackless(Python for concurrency)

4.IronPython(Python for .Net)

5.PyPy(Python for Speed)

 


Best Frameworks in Python



Top Most Frameworks in Python:

At present in IT Python is most rated programming language because it is very simple to learn and use. And python has a wide range of applications.

Python:

Python is an interpreted, dynamically and high level language. It is based on Object oriented programming language(OOPS).  In development centers with Python will require framework to code. At the time we used Python frameworks.

Best Python Frameworks:

1. Django

Django is the one of the most popular open source Python web framework. It is very useful for freshers and experienced Python programmers. Django is completely with database engines while coming to real time applications like Instagram by Django. Finally it is kind of a website it contains JSON, XML, RSS.

Django helps developers to create complex code and applications in an easier way and time complexity also less . Some features like URL routing ORM, O-Auth, database schema migrations etc.


2.Flask:

Flask is a one of the powerful programming language we can use Python to develop standalone applications like apps. It has own template known as Jinja. Now a days Flask is considered more Python developers than Django because in common situations the equivalent Flask Web application is more explicit. Flask is also easy to get with boilerplate code.

Example :

from flask import Flask

app=Flask(_name_)

@app.route(‘/’)

def FirstProgram():

return “First Example of Flask”

if_name_ ==’_main_’:

app.run()

3. Sanic:

Sanic is an easy open source of Python 3.5+ . Sanic is similar to Flask function but here little bit difference is Faster compare with Flask. Sanic mainly HTTP responses with the help of asynchronous requests it means that can use the new shiny async /await syntax from Python and non-blocking.

Example :

from sanic import Sanic

app = Sanic()

@app.route(“/”)

async def demo(request);

return (“First Demo”)

if _name_ == “_main_”:

app.run(host = “0.0.0.0”, port = 8081)

4. CherryPy :

CherryPy is an open source of Python. It allows developers to build web application sometimes using object – oriented Python framework.It wll take less time complexity during developing source code and it has won multi threaded web server .CherryPy is a reliable, HTTP/1.1 complaint, Web Server Gateway Interface threaded pooled web server and it runs multiple HTTP servers at once.

Example:

from cherrypy import Cherrypy

class FirstDemo{

def index(self)

return “First Demo in CherryPy”

index.exposed= True

cherrypy.quickstart(FirstDemo())

5. Web2py :

Web2py is a opensource,fast, scalable, secure, full – stack and web – based application framework. Web2py is portable , code editor , debugger and deployment tool and it uses LDAP for authentication in Security. It is mainly used for built in components to handle HTTP request, responses, cookies and sessions. To ability to read multiple protocols. And it follow MVC (Model – View – Controller) pattern.

Example:

def FirstDemo();

response.view = ‘simple example

return dict(message= ( “First Demo”))


Conclusion:

Above Python frameworks are most preferable compare with other framework. Remaining also most versatile frameworks now a days.