py UNIT-I

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 140

UNIT-I

Introduction to Python

ECM Department
Unit-I Syllabus
Topics to be covered:
History, Features,
Modes of Execution,
Setting up path,
working with Python Basic Syntax,
Variable and Data Types, Operators.
Conditional Statements (If, If- else, Nested if-else)
Looping (for, While Nested loops)
Control Statements (Break, Continue, Pass).
Input-Output:
Printing on screen,
Reading data from keyboard,
ECM Department
Opening and closing file
Python is General purpose high-level programming language.
General purpose  multi purpose-Data science
application,machine learning,web application,Ai application,
Robotics etc.
High-level langugae:understand by machine and human
Low-level language: machine level language & Assembly lang
Developed by “Guido Ran Rassam”
In 1989 while working at National Research Institute(NRI) in
Netherlands.
In Feb 28 1991 python available to public.
Highly recommended programming-language.
Main advantage is easy to write like English like statements.
C & java are strictly or statically typed language.
Python is Dynamically Typed programming.
ECM Department
Why “PYTHON” name?
Monty “Python” Flying Circus.
Python Contains:
Functional Programming features from C
OOP features from C++.
Scripting features from Perl & Shell Scripting.
Modular programming features from Modula-3(Every thing
Module).
Syntax are borrowed from C & ABC Language.
PYTHON=Powerful programming + Powerful Scripting language

ECM Department
Where we can use PYTHON ?
Desktop application
Web application  Django—frame work to develop web
applications
Database application
Network application
Games
Data Analytics
Machine learning
AI
IOT

ECM Department
ECM Department
ECM Department
Features of Python programming language:

ECM Department
ECM Department
1. Readable: Python is a very readable language.
2. Easy to Learn: Learning python is easy as this is a expressive
and high level programming language, which means it is easy to
understand the language and thus easy to learn.
3. Cross platform: Python is available and can run on various
operating systems such as Mac, Windows, Linux, Unix etc. This
makes it a cross platform and portable language.
4. Open Source: Python is a open source programming language.
5. Large standard library: Python comes with a large standard
library that has some handy codes and functions which we can use
while writing code in Python.
6. Free: Python is free to download and use. This means you can
download it for free and use it in your application. See: Open
Source Python License. Python is an example of a FLOSS
(Free/Libre Open Source Software), which means you can freely
distribute copies of this software, read its source code and modify
ECM Department
it.
7. Supports exception handling: what is an exception?
An exception is an event that can occur during program
exception and can disrupt the normal flow of program.
Python supports exception handling which means we can write
less error prone code and can test various scenarios that can
cause an exception later on.
8. Advanced features: Supports generators and list
comprehensions.
9. Automatic memory management: Python supports
automatic memory management which means the memory is
cleared and freed automatically.
You do not have to bother clearing the memory.

ECM Department
What Can You Do with Python?
You may be wondering what all are the applications of Python.
There are so many applications of Python, here are some of the
them.
1. Web development – Web framework like Django and Flask are
based on Python.
They help you write server side code which helps you manage
database, write backend programming logic, mapping urls etc.
2. Machine learning – There are many machine learning
applications written in Python. Machine learning is a way to write a
logic so that a machine can learn and solve a particular problem on
its own.
 For example, products recommendation in websites like Amazon,
Flipkart, eBay etc. is a machine learning algorithm that recognizes
user’s interest.
Face recognition and Voice recognition in your phone is another
ECM Department
example of machine learning.
3. Data Analysis – Data analysis and data visualisation in form
of charts can also be developed using Python.
4. Scripting – Scripting is writing small programs to automate
simple tasks such as sending automated response emails etc.
Such type of applications can also be written in Python
programming language.
5. Game development – You can develop games using Python.
6. You can develop Embedded applications in Python.
7. Desktop applications – You can develop desktop application
in Python using library like TKinter or QT.

ECM Department
ECM Department
ECM Department
ECM Department
ECM Department
ECM Department
ECM Department
1.Modes of Execution:
1) Interactive Mode
For working in the interactive mode, we will start Python on
our computer.
We type Python expression / statement / command after the
prompt (>>>) and Python immediately responds with the
output of it.

ECM Department
2) Script Mode
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is finished.
When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script.
Python files have extension .py.
To create and run a Python script, we will use following steps
in IDLE, if the script mode is not made available by default
with IDLE environment.
1. File>New File (for creating a new script file) or Press
ctrl+N.
2. Write the Python code as function i.e. script.
3. Save it (^S).
4. Execute it in interactive mode- by using RUN option (^F5).
ECM Department
ECM Department
ECM Department
2.Setting up path
Working with Python Basic Syntax:

ECM Department
Python Line Structure
A Python program comprises logical lines. A NEWLINE token
follows each of those. The interpreter ignores blank lines.
The following line causes an error.
print("Hi
How are you?")
Python Multiline Statements
This one is an important Python Syntax
We saw that Python does not mandate semicolons. A new line means
a new statement.
But sometimes, you may want to split a statement over two or more
lines. It may be to aid readability. You can do so in the following
ways.
a. Use a backward slash
print("Hi\
ECM Department
how are you?")
b. Put the string in triple quotes

ECM Department
Python Comments:
 Python Syntax ‘Comments’ let you store tags at the right places in the
code. You can use them to explain complex sections of code.
 The interpreter ignores comments. Declare a comment using an
octothorpe (#).
#This is a comment
 Python does not support general multiline comments like Java or C++.
Python Docstrings:
 Python documentation strings (or docstrings) provide a convenient way
of associating documentation with Python modules, functions, classes,
and methods.
 Like a comment, this Python Syntax is used to explain code.
 But unlike comments, they are more specific. Also, they are retained at
runtime.
 This way, the programmer can inspect them at runtime.
 Delimit a docstring using three double quotes. You may put it as a
ECM Department
function’s first line to describe it.`1
Python Indentation
Since Python doesn’t use curly braces to delimit blocks of
code, this Python Syntax is mandatory.
You can indent code under a function, loop, or class.

You can indent using a number of tabs or spaces, or a


combination of those.
 But remember, indent statements under one block of code
with the same amount of tabs and spaces.
#This causes a
syntax error:
“unindent does not
match any outer
indentation level”
ECM Department
Python Multiple Statements in One Line
 You can also fit in more than one statement on one line. Do this by separating
them with a semicolon.

Python Quotations:
 Python supports the single quote and the double quote for string literals. But
if you begin a string with a single quote, you must end it with a single quote.
The same goes for double quotes.

ECM Department
Python Blank Lines:
If you leave a line with just whitespace, the interpreter will
ignore it.
Python Identifiers:
An identifier is a name of a program element, and it is user-
defined. This Python Syntax uniquely identifies the element.
There are some rules to follow while choosing an identifier:
An identifier may only begin with A-Z, a-z, or an
underscore(_).
This may be followed by letters, digits, and underscores- zero
or more.
Python is case-sensitive. Name and name are two different
identifiers.
A reserved keyword may not be used as an identifier.
ECM Department
The following is a list of keywords.

Apart from these rules, there are a few naming conventions that
you should follow while using this Python syntax:
Use uppercase initials for class names, lowercase for all others.
Name a private identifier with a leading underscore ( _username)
Name a strongly private identifier with two leading underscores
( __password)
Special identifiers by Python end with two leading underscores.
ECM Department
3.Python Variables:

 In Python, you don’t define the type of the variable. It is assumed on the
basis of the value it holds.
x=10
print(x)
x='Hello'
ECM Department
print(x)
A variable is a memory location where a programmer can store
a value. Example : roll_no, amount, name etc.
Value is either string, numeric etc. Example : "Sara", 120,
25.36
Variables are created when first assigned.
Variables must be assigned before being referenced.
The value stored in a variable can be accessed or updated later.
No declaration required
The type (string, int, float etc.) of the variable is determined by
Python
The interpreter allocates memory on the basis of the data type
of a variable.

ECM Department
Python Variable Name Rules:
Must begin with a letter (a - z, A - B) or underscore (_)
Other characters can be letters, numbers or _
Case Sensitive
Can be any (reasonable) length
There are some reserved words which you cannot use as a
variable name because Python uses them for other things.
Syntax:
<variable> = <expr>
Example Program
num1=10
num2=20
sum=num1+num2
print(sum)
ECM Department
Multiple Assignment:
The basic assignment statement works for a single variable and
a single expression.
You can also assign a single value to more than one variables
simultaneously.
Syntax:
var1=var2=var3...varn= = <expr>
Example:
x=y=z=1

ECM Department
Here is an another assignment statement where the variables
assign many values at the same time.
Syntax:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr> Example:
x, y, z = 1, 2, "abcd“
In the above example x, y and z simultaneously get the new
values 1, 2 and "abcd".
You can reuse variable names
by simply assigning a new value
to them :

ECM Department
Swap variables
Python swap values in a single line and this applies to all
objects in python.
Syntax:
var1, var2 = var2, var1

ECM Department
Deleting variables:
You can also delete python variables using the keyword ‘del’.

ECM Department
Triple quotes:
To define multi line string literals then use triple quotes.
’’’ hi hello
Hw ru’’’
Or
””” hie
heloo
Hru”””
‘hello iam from “SNIST” ‘
“hello iam from” snist’”
Both in one statement then use triple quotes
””” Hello iam from “SNIST “ ‘IT-C’ “””
To define Docstring
ECM Department
ECM Department
Variable Scope:
The scope of a variable in python is that part of the code
where it is visible.

ECM Department
Types of Python Variable Scope:

Local Scope
In the above code, we define a variable ‘d’ in a function ‘func’.
So, ‘d’ is local to ‘func’. Hence, we can read/write it in func,
but not outside it.
 When we try to do so, it raises a Name Error.

ECM Department
Enclosing Scope:
In this code, ‘b’ has local scope in Python function ‘blue’, and ‘a’
has nonlocal scope in ‘blue’. Of course, a python variable scope
that isn’t global or local is nonlocal. This is also called enclosing
scope.

Built-in Scope
The built-in scope has all the names that are loaded into python
variable scope when we start the interpreter. For example, we never
need to import any module to access functions like print() and id().
ECM Department
Global Scope
Variables that are defined inside a function body have a local
scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables
can be accessed throughout the program body by all functions.

ECM Department
Global Keyword in Python

ECM Department
Nonlocal Keyword
Like the ‘global’ keyword, you want to make a change to a
nonlocal variable, you must use the ‘nonlocal’ keyword.

As you can see, this did not change the value of ‘a’ outside
function ‘blue’. To be able to do that, we use ‘nonlocal’.
ECM Department
ECM Department
3.Data Types:

ECM Department
3.Data Types:
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instance (object) of these classes.
Data type represents the type of data stored into a variable or memory.
Type of Data type: -
1. Built-in Data type
2. User Defined Data type
Built-in Data type
These data types are provided by Python Language.
Following are the built-in data type: -
• None Type
• Numeric Types
• Sequences
• Sets
• Mappings
User Defined Data type
• Array
• Class
ECM Department
• Module
3.Data Types:
Data types are used to store data or information in a variable.
 Python data types are dynamic, because we don’t need to
mention type of the variable.
But in other languages we should mention the type of data.
Python Numbers:
There are four numeric Python data types.
1. int– int stands for integer.
This Python Data Type holds signed integers.
We can use the type() function to find which class it belongs
to.
2. float– This Python Data Type holds floating point real values.
An int can only store integer numbers, but float can store
decimals
ECM Department
complex- This Python Data Types holds a complex number.
 A complex number looks like this: a+bj Here, a and b are the real
parts of the number, and j is imaginary.
Strings
A string is a sequence of characters. Python does not have a char
data type, unlike C++ or Java.
You can delimit a string using single quotes or double quotes.
Displaying part of a string– You can display a character from a
string using its index in the string. Remember, indexing starts with 0.
>>> name=‘SNIST'
>>> name[0] o/p ”S’
You can also display a burst of characters in a string using the
slicing operator [ ].
>>> name[2:4] o/p ‘IS’
ThisECMprints the characters from 2 to 3.
Department
ECM Department
Slice Operator:
Syntax: s[begin:end]
Begin to end-1
Default value for begin is “0”.
If end is not specified it takes end has last index
Slices operator never raises any Index error.

ECM Department
Application:

ECM Department
+ operator:

ECM Department
* operator:
String reputation operator
‘*’ is applicable for string but one argument shuld be int

ECM Department
Booleans:
Boolean data types are of 2 types in Python.
They are True and False. These can be used to assign or
compare the boolean values.
In Python, logical expressions return the boolean values.
 In Python, True is equalled to 1 and False is equals to 0.
Python turns the boolean values into integers explicitly during
the arithmetic operations.

ECM Department
All fundamental data types are immutable.
Once we create an object we cannot change
If we try to perform any changes with that a new object will be
created

ECM Department
Collection Related Data types:
Fundamental data types can hold only One value
Group of values as a single entity then we use Collection
Related Data types.
List
Tuple
Set
Frozenset
Dict
Range
Bytes
Bytearray

ECM Department
Lists
A list is a collection of values.
List is an ordered sequence of items.
It is one of the most used datatype in Python and is very
flexible.
All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by
commas are enclosed within brackets [ ].
Example:
>>> days=['Monday','Tuesday',3,4,5,6,7]
>>> days
Output:
[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]
ECM Department
ECM Department
Order is preserved
Duplicates objects are allowed
[ ]  representation
Accepts heterogeneous or dissimilar objects
Indexing and slicing are applicable
L[ ]  creation of empty list
 to add an element to list use “append”
To remove use “remove”

ECM Department
1. Slicing a list – You can slice a list the way you’d slice a
string- with the slicing operator.
>>> days[1:3]
[‘Tuesday’, 3]
Indexing for a list begins with 0, like for a string. A Python
doesn’t have arrays.
Length of a list– Python supports an inbuilt function to
calculate the length of a list.
>>> len(days)
7
3. Reassigning elements of a list– A list is mutable.
This means that you can reassign elements later on.
>>> days[2]='Wednesday'
>>> days
ECM Department
[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]
4. Multidimensional lists– A list may have more than one
dimension.
>>> a=[[1,2,3],[4,5,6]]
>>> a
[[1, 2, 3], [4, 5, 6]]

ECM Department
Tuple:
Tuple is an ordered sequence of items same as list.
The only difference is that tuples are immutable.
Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than
list as it cannot change dynamically.
It is defined within parentheses () where items are separated by
commas.
We cannot add or remove values.
Read only version of list is tuple

ECM Department
ECM Department
The above example shows type is “int”
When we add a comma after value then it is consider as
“TUPLE”
Single value tuple end should end with “COMMA”
Without “comma” its type is int.
With comma
LIST its type is tuple TUPLE
1.Mutable 1.Immutable
2.[ ] 2.( )
3.More memory 3.To store tuple elements
python required very less
memory
4.Performance is less 4.Performance is more
ECM Department
5.application:contenet Ex:Account types
changing Savings and current bank
 Example:
>>> subjects=('Physics','Chemistry','Maths')
>>> subjects
(‘Physics’, ‘Chemistry’, ‘Maths’)
 Accessing and Slicing a Tuple– You access a tuple the same way as
you’d access a list. The same goes for slicing it.
>>> subjects[1]
‘Chemistry’
>>> subjects[0:2]
(‘Physics’, ‘Chemistry’)
 A tuple is immutable– However, it is immutable. Once declared, you
can’t change its size or elements.
>>> subjects[2]='Biology'
Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
ECM Department
TypeError: ‘tuple’ object does not support item assignment
Set:
A set is an unordered and unindexed collection of items.
This means when we print the elements of a set they will
appear in the random order and we cannot access the elements
of set based on indexes because it is unindexed.
In List & Tuple order is important and duplicates are allowed.
Tuple is immutable and List is Mutable
Duplicates are not allowed
Order is not required
Representation { }
Indexing and slicing are not applicable
Set is Mutable and Growable

ECM Department
ECM Department
append() add()
In list adding values at last In set adding values in any
position
S={10,20,30} S={10,20,30}
l.append(50) l.add(50)
print(s) print(s)
10,20,30,50 10,20,50,30

ECM Department
By default Curly Braces open and close type is “Dict” not
“set”
Frequently used data type is dict, more priority to “dict”

List Set
Order is important No order
Duplicate are allowed No duplicates
Represented by [ ] Represented by { }
ECM Department
Frozenset:
Frozen set same as Set
But Frozen set is immutable.
In frozen set we cannot add or remove values.
Order is not applicable
No duplication
Indexing and slicing are not applicable.

ECM Department
Dict:
If we want to represent a group of objects as “key value pair”
then use “dict”
Order is not important.
Dict is mutable.
Indexing & slicing are not applicable.
Syntax:
d={key:value}
{k1:v1,k2:v2,………..kn:vn}

ECM Department
Duplicate keys are not allowed .
Duplicate values are allowed
If we assign same “Key” if already assigned then old value is
replaced with new values. If we try to insert duplicate we wont
get any error or simply old is value is replaced with new value.

ECM Department
Range:
Representing a sequence of numbers then use range.
Indexing and slicing are applicable
Range object is immuatble

ECM Department
Different ways to create Range:
1.range(n):
Ex: r=range(10) #0 to 9
r=range(100) #0 to 99
2.range(begin,end):
Begin to end-1
r=range(1,10) #1 to 9
For x in r:
print(x)
r=range(1,11) #1 to 10 values
3.range(begin,end,increment/decrement):
r=range(1,21,1) # increment by1
r=range(1,21,2) # increment by2
ECM Department
r=range(1,21,-1) # decrement by -1
ECM Department
Byte:
Representing group of byte values
If we want to create byte use in-built byte function.

ECM Department
Byte values assign only from 0 to 255
Bytes are immutable

ECM Department
Bytearray:
Both are same.
Bytes are immutable
Bytearray is mutable
By using Bytearray function we can create bytearray

ECM Department
Type Conversion:
Python has five standard Data Types.
Sometimes it is necessary to convert values from one type to
another.
Python defines type conversion functions to directly convert
one data type to another.

ECM Department
ECM Department
Converting to Tuples and Lists:
A list is a mutable ordered sequence of elements that is
contained within square brackets [ ].
A tuple is an immutable ordered sequence of elements
contained within parentheses ( ).
You can use the methods list() and tuple() to convert the values
passed to them into the list and tuple data type respectively.

ECM Department
Value Error
While converting from string to int you may get ValueError
exception.
This exception occurs if the string you want to convert does
not represent any numbers.

ECM Department
 bool()
 It converts the value into a boolean. set()
>>> bool(3)
True
It converts the
>>> bool(0) value into a set.
False
>>> bool(True)
>>> set([1,2,2,3])
True {1, 2, 3}
>>> bool(0.1)
True
>>> set({1,2,2,3})
You can convert a list into a Boolean. {1, 2, 3}
>>> bool([1,2])
True
The function returns False for empty constructs.
>>> bool()
False
>>> bool([])
False
>>> bool({})
False
None is a keyword in Python that represents an absence of value.
>>> bool(None)
ECM Department
False
None data type:
None means Nothing or No value associated
If the value is not available, then to handle such type of cases
None is introduced.
It is something like null value in java.

Constants:
Constants are not applicable in Python.
But it is convention to use only uppercase characters if we
don’t want to change value.
It is just convention but we can change the value.
MAX_VALUE=16

ECM Department
list()
It converts the value into a list. tuple()
It converts the value into a
>>> del list
tuple.
>>> list("123") >>> tuple({1,2,2,3})
[‘1’, ‘2’, ‘3’] (1, 2, 3)
>>> list({1,2,2,3}) You can try your own
[1, 2, 3] combinations. Also try
>>> list({"a":1,"b":2}) composite functions.
>>> tuple(list(set([1,2])))
[‘a’, ‘b’] (1, 2)
However, the following raises an error.
>>> list({a:1,b:2})
Traceback (most recent call last):
File “<pyshell#173>”, line 1, in <module>;
list({a:1,b:2})
ECM Department
TypeError: unhashable type: ‘set’
4.Operators:
Operators are used to perform operations on values and
variables.
 Operators can manipulate individual items and returns a
result.
The data items are referred as operands or arguments.
Operators are either represented by keywords or special
characters.
Python Operator falls into 7 categories:
Arithmetic Operator
Relational Operator
Assignment Operator
Logical Operator
Membership
ECM DepartmentOperator

Python Arithmetic Operator:
These Python arithmetic operators include Python operators
for basic mathematical operations.

ECM Department
ECM Department
Python Relational Operator:
Relational operators are used to compare values. It either
returns True or False according to the condition.

ECM Department
ECM Department
Python Assignment Operator:
Assignment operators are used in Python to assign values to
variables.
a = 5 is a simple assignment operator that assigns the value 5
on the right to the variable a on the left. There are various
compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a = a + 5.

ECM Department
Python Logical Operator:
Logical operators are the and, or, not operators.

ECM Department
Python Bitwise Operator:
Bitwise operators act on operands as if they were string of
binary digits. It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4
(0000 0100 in binary)

It returns the one’s complement of a number’s binary. It flips


the bits. Binary for 2 is 00000010. Its one’s complement is
11111101. This is binary for -3. So, this results in -3. Similarly,
ECM Department
~1 results in -2.
ECM Department
Membership Python Operator:
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
 In a dictionary we can only test for presence of key, not the value.

ECM Department
Python Identity Operator:
is and is not are the identity operators in Python.
They are used to check if two values (or variables) are located
on the same part of the memory.
Two variables that are equal does not imply that they are
identical.

ECM Department
 Here, we see that x1 and y1 are integers of same values, so
they are equal as well as identical. Same is the case with x2
and y2 (strings).
 But x3 and y3 are list. They are equal but not identical. It is
because interpreter locates them separately in memory
although they are equal.

ECM Department
5.Conditional Statements :
Decision making statements in python, helps in controlling
your program accordingly.
There are the following decision making statements available
in Python:
if statement
if-else statement
nested if statement
Chained Conditionals (elif ladder)
Single Statement Condition

ECM Department
if statement:
The if statement is used to test a particular condition and if the
condition is true, it executes a block of code known as if-block.
 The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
syntax of the if-statement is given below.
if expression:
statement

ECM Department
if-else statement:
The if-else statement provides an else block combined with the
if statement which is executed in the false case of the
condition.
If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.
syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)

ECM Department
ECM Department
ECM Department
nested-if:
A nested if is an if statement that is the target of another if
statement.
 Nested if statements means an if statement inside another if
statement.
Yes, Python allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.
Syntax:
if condition:
if condition:
statements
else:
statements
else:
statements
ECM Department
ECM Department
Chained Conditionals (elif ladder):
The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the
true condition among them.
We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in
C.
It must be succeeded by an if statement.

ECM Department
syntax :
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

ECM Department
ECM Department
Single Statement Condition:
If you only need to write a single statement under if, you can
write it in the same line using single statement python decision
making constructs.

ECM Department
Iterative Statements:
Loops in Python are used to control your program.
Loops are basically used to execute a block of code several
number of times accordingly.

ECM Department
Advantages of loops
There are the following advantages of loops in Python.
It provides code re-usability.
Using loops, we do not need to write the same code again and
again.
Using loops, we can traverse over the elements of data
structures (array or linked lists).
4 types of Python Loop:
For Loop
While Loop
Python Loop Control Statements
Nested For Loop

ECM Department
For Loop:
Python for loop can iterate over a sequence of items. T
he structure of a for loop in Python is different than that in C+
+ or Java.
That is, for(int i=0;i<n;i++) won’t work here.
In Python, we use the ‘in’ keyword.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside
the sequence on each iteration.
Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code
using
ECMindentation.
Department
ECM Department
ECM Department
ECM Department
ECM Department
while loop:
The while loop is also known as a pre-tested loop.
In general, a while loop allows a part of the code to be
executed as long as the given condition is true.
It can be viewed as a repeating if statement.
The while loop is mostly used in the case where the number of
iterations is not known in advance.
syntax is given below:
while expression:
statements

ECM Department
ECM Department
6.Loop Control Statements:
break statement:
When you put a break statement in the body of a loop, the loop
stops executing, and control shifts to the first statement outside
it.
You can put it in a for or while loop.

ECM Department
ECM Department
continue statement:
The continue statement is used to skip the rest of the code
inside a loop for the current iteration only.
Loop does not terminate but continues on with the next
iteration.

ECM Department
ECM Department
pass statement:
 Pass is a keyword in python.
 In our programming syntactically if block is required which won’t
do anything then we can define that empty block with pass
keyword.
 It is an empty statement
 It is null statement
 It won’t do anything
Ex: Expecting true block
If True: Expected Indentation
else:
Print(“Hello”)

ECM Department
If the number is even we are doing nothing and if it is
odd then we are displaying the number.
ECM Department
7.Input-Output:
Input:
Reading dynamic input from the keyboard.
In python 2 we have 2 functions are available to read dynamic
input from the keyboard.
1.raw_input()
2.input()
1.raw_input():
This function always reads the data from the keyboard in the
form of String format.
We have to convert that string type to our required type by using
corresponding type casting methods.
Ex:
It always print str type only for any
a=raw_input(“enter a value”) input type
ECM Department
Print(type(a))
2.input():
input() function can be used to read data directly in our
required format.
Here we don’t require to perform type casting.
Ex:
x=input(“enter value”)
type(x)
6int
“SNIST”str
7.8float
Truebool

ECM Department
But in python 3 we have only input() method.
raw_input() method is not available
In Python 3 input() function behavior exactly same as
raw_input() method of Python 2
Raw_input() function of python 2 is renamed as input()
function in Python 3

ECM Department
ECM Department
split( ) function takes SPACE as
separator by default

ECM Department
eval():
eval function take a string evaluates to corresponding type.

ECM Department
ECM Department
7.Output statements:
We can use print() function to display output.
Format 1:
print() without any argument
Just it prints new line character.
Format 2:

ECM Department
Note:
If both arguments are String type then + operator acts as
Concatenation operator.
If one argument is string type and second id any other type like
int then we will get Error.
If both arguments are number type then + operator acts as
arithmetic addition operator.

Format 3:
print() with variable number of arguments:

ECM Department
By default output values are separated by space.
If we want separator we can specify by using ”sep” attribute.

Format 4:
Print() with end attribute.
If we want output in the same line with space
Default value for end
attribute is \n, which is
nothing but new line
character

ECM Department
Format 5:print(object) statement:
We can pass any object like list,tuple,set,etc as arguments to
print() statement.

Form 6:print(String, variable list):


We can use print() statement with String and any number of
arguments.

output:

ECM Department
Format 7:print(formatted string):
%iint
%dint
%ffloat
%sstring type
print(“fotmatted string”,%(variable list))

ECM Department
Format 8:print() with replacement operator{}
We can format the strings with variable values by using
replacement operator{} and format() method.

Output:

ECM Department
ECM Department

You might also like