[go: up one dir, main page]

0% found this document useful (0 votes)
71 views56 pages

PWP Chapter 2

The document discusses Python operators and control flow statements. It covers various types of operators like arithmetic, assignment, comparison etc and how they are used. It also discusses control flow statements like if/else conditional statements and for/while loops for flow control in programs.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views56 pages

PWP Chapter 2

The document discusses Python operators and control flow statements. It covers various types of operators like arithmetic, assignment, comparison etc and how they are used. It also discusses control flow statements like if/else conditional statements and for/while loops for flow control in programs.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit II: Python Operators & Control statements Programming with “Python” (22616)

Name of Staff: Mr. P. S. Bhandare


Name of Subject: Programming with Python
Subject code: 22616
Class: TYCO
Department: Computer Engineering

Unit No. 2
Python operator &
control flow statements
by
P. S. Bhandare

College of Engineering (Polytechnic),


Pandharpur

Hours: 6
Marks: 10

1|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Syllabus:
2.1 Basic Operators: Arithmetic, Comparison/ Relational, Assignment,
Logical, Bitwise, Membership, Identity operators, Python Operator
Precedence
2.2 Control Flow:
2.3 Conditional Statements (if, if ... else, nested if)
2.4 Looping in python (while loop, for loop, nested loops)
2.5 loop manipulation using continue, pass, break, else.

2|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

About Title of Chapter:


 The title of chapter Python operators & control statements” tells that
this chapter includes study of operator & control statements that can
be used in various expressions.
 Also, it includes study related to looping statement to solve the
different problems.
About Central Idea of Chapter:
 The central idea of chapter is that by studying this chapter student
will learn new programming concept with syntax and example to
write & execute python programs.
About Importance of Chapter:
 This is chapter is important because this will introduce basic syntax
and example to write python programs to solve real life problems like
control statements & looping statements.
Outcomes of Chapter:
 2a. Write simple Python program for the given arithmetic
expressions.
 2b. Use different types of operators for writing the the arithmetic
expressions.
 2c. Write a 'Python' program using decision making structure for
two-way branching to solve the given problem.
 2d. Write a 'Python' program using decision making structure for
multi-way branching to solve the given problem.

3|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Introduction:
Operator
An operator is a symbol that performs an operation. An operator acts on
some variables called operands. For example, if we write a + b the operator
'+' is acting on two operands 'a' and 'b'. If an operator acts on a single
variable, it is called unary operator. If an operator acts on two variables, it is
called binary operator. If an operator acts on three variables, then it is
called ternary operator. This is one type of classification. We can classify the
operators depending upon their nature, as shown below:
 Arithmetic operators
 Assignment operators
 Unary minus operator
 Relational operators
 Logical operators
 Boolean operators
 Bitwise operators
 Membership operators
 Identity operators

Arithmetic Operators
These operators are used to perform basic arithmetic operations like
addition, subtraction, division, etc.
There are seven arithmetic operators available in Python. Since these
operators act on two operands, they are called binary 'operators' also.
There are two types of division operators:
 Float division
 Floor division
Float division
The quotient returned by this operator is always a float number, no matter
if two numbers are integers. For example:
Example: The code performs division operations and prints the results. It
demonstrates that both integer and floating-point divisions return accurate
results. For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’

4|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)

Output:
1.0
5.0
-5.0
10.0
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being
passed. If any of the numbers is float, it returns output in float. It is also
known as Floor division because, if any number is negative, then the output
will be floored. For example:
Example: The code demonstrates integer (floor) division operations using
the ‘//’ operator. It provides results as follows: ’10//3′ equals ‘3’, ‘-
5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer
division returns the largest integer less than or equal to the division result.

print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)

Output:
3
-2
2.0
-2.0

Operator Meaning Description Example Output

5|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

+ Addition Adds the value of the left and right 1+4 5


operands
- Subtraction Subtracts the value of the right 10-5 5
operand from the value of the left
operand
* Multiplication Multiplies the value of the left and 5*2 10
right operand
/ Division Divides the value of the left 10/2 5.0
operand by the right operand
** Exponent Performs exponential calculation 2**3 8
% Modulus Returns the remainder after 15%4 3
dividing the left operand with the
right operand
// Floor Division of operands where the 17//5 3
Division solution is a quotient left after
removing decimal numbers

When there is an expression that contains several arithmetic operators, we


should know which operation is done first and which operation is done
next. In such cases, the following order of evaluation is used:
1. First parentheses are evaluated.
2. Exponentiation is done next.
3. Multiplication, division, modulus and floor divisions are at equal priority.
4. Addition and subtraction are done afterwards.
5. Finally, assignment operation is performed.
Let's take a sample expression: d= (x + y) * z* * a//b+c. Assume the values
of variables as: x=1; y=2; z=3; a=2; b=2; c=3. Then, the given expression d=
(1 + 2) ^ * 3^ * 2//2+3 will evaluate as:
1. First parentheses are evaluated. d=3 * 3 ** 2 //2+3.
2. Exponentiation is done next. d = 3*9//2+3.
3. Multiplication, division, modulus and floor divisions are at equal priority.
d 27// 2 + 3 and then d = 13 + 3
4. Addition and subtraction are done afterwards. d = 16

6|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

5. Finally, assignment is performed. The value 16 is now stored into 'd'.


Hence, the total value of the expression becomes 16 which is stored in the
variable 'd'.
Assignment Operators
These operators are useful to store the right-side value into a left side
variable. They can also be used to perform simple arithmetic operations
like addition, subtraction, etc., and then store the result into a variable.
These operators are shown in Table. x = 20, y = 10 and z =5:
Operator Example Meaning Result

= z = x+y Assignment operator. Stores right side value into Z =30


left side variable, i.e. x+y is stored into z.
+= z+=x Addition assignment operator. Adds right z = 25
operand to the left operand and stores the
result into left operand, i.e. z = z+x.
-= z-=x Subtraction assignment operator. Subtracts z =-15
right operand from left operand and stores the
result into left operand, i.e. z — z-x.
*= z*=x Multiplication assignment operator. Multiplies z = 100
right operand with left operand and stores the
result into left operand, i.e. z = z *x.
/= z/=x Division assignment operator. Divides left z =0.25
operand with right operand and stores the
result into left operand, i.e. z = z/x.
%= z%=x Modulus assignment operator. Divides left Z=5
operand with right operand and stores the
remainder into left operand, i.e. z = z%x.
**= Z**=x Exponentiation assignment operator. Performs Z=9765
power value and then stores the result into left 625
operand, i.e. Z=z**x
//= Z//=x Floor division assignment operator. Performs Z=0
floor division and then stores the result into left
operand, i.e. z = z/ / Y

7|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

It is possible to assign the same value to two variables in the same


statement as:
a=b=1
print(a, b) # will display 1 1
Another example is where we can assign different values to two variables
as:
a=1; b=2
print(a, b) # will display 1 2
The same can be done using the following statement:
a, b = 1 ,2
print(a, b) # will display 1 2
A word of caution: Python does not have increment operator (++) and
decrement operator (-) that are available in C and Java.

Unary Minus Operator


The unary minus operator is denoted by the symbol minus ( - ). When this
operator is used before a variable, its value is negated. That means if the
variable value is positive, it will be converted into negative and vice versa.
For example, consider the following statements:
e.g.
n = 10;
print(- n) # displays -10
num = - 10
num = - num
print(num) # displays 10

8|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Relational Operators
Relational operators are used to compare two quantities. We can
understand whether two values are same or which one is bigger or which
one is lesser, etc. using these operators. These operators will result in True
or False depending on the values compared, as shown in Table. In this
table, we are assuming a =1 and b = 2

Operator Example Meaning Result


Greater than operator. If the value of left operand is
> a>b greater than the value of right operand, it gives False
True else it gives False.
Greater than or equal operator. If the value of left
>= a>=b operand is greater or equal than that of right False
operand, it gives True else False.
Less than operator. If the value of left operand is
< a<b less than the value of right operand, it gives True True
else it gives False.
Less than or equal operator. If the value of left
<= a<=b operand is lesser or equal than that of right True
operand, it gives True else False.
Equals operator. If the value of left operand is
== a==b equal to the value of right operand, it gives True False
else False,
Not equals operator. If the value of the left
!= a!=b operand is not equal to the value of right True
operand, it returns True else it returns False.

Relational operators are generally used to construct conditions in if


statements. For example,
a=1; b=2
if (a>b):
print("Yes")
else:
print("No")
will display 'No'. Observe the expression (a>b) written after if. This is called
a 'condition'. When this condition becomes True, if statement will display
9|Page
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

'Yes' and if it becomes False, then it will display 'No'. In this case, (1>2) is
False and hence 'No' will be displayed.
Relational operators can be chained. It means, a single expression can hold
more than one relational operator. For example,
x=15
10<x<20 # displays True
Here, 10 is less than 15 is True, and then 15 is less than 20 is True. Since
both the conditions are evaluated to True, the result will be True.
10>=x<20 # displays False
Here, 10 is greater than or equal to 15 is False. But 15 is less than 20 is
True. Since we get False and True, the result will be False.
10<x>20 # displays False
Here, 10 is less than 15 is True. But 15 is greater than 20 is False. Since we
are getting True and False, the total result will be False. So, the point is this:
in the chain of relational operators, if we get all True, then only the final
result will be True. If any comparison yields False, then we get False as the
final result. Thus,
1<2<3<4 # will give True
1<2>3<4 # will give False
4>2>=2>1 # will give True

Logical Operators
Logical operators are useful to construct compound conditions. A
compound condition is a combination of more than one simple condition.
Each of the simple condition is evaluated to True or False and then the
decision is taken to know whether the total condition is True or False. We
should keep in mind that in case of logical operators, False indicates 0 and
True indicates any other number. There are 3 logical operators as shown in
Table 4.4. Let's take x = 1 and y = 2 in this table.

10 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Operator Example Meaning Result


And operator. If x is False, it returns x,
And x and y 2
otherwise it returns y.
Or operator. If x is False, it returns y,
Or x or y 1
otherwise it returns x.
Not operator. If x is False, it returns True,
Not not x False
otherwise False.

Let's take some statements to understand the effect of logical operators.


x = 100
y = 200
print(x and y) # will display 200
print(x or y) # will display 100
print (not x) # will display False
x=1; y=2; z=3
if(x<y and y<z): print('Yes')
else: print('No')'
In the above statement, observe the compound condition after if. That is x
<y and y<z. This is a combination of two simple conditions, x<y and y<z.
When 'and' is used, the total condition will become True only if both the
conditions are True. Since both the conditions became True, we will get
'Yes' as output. Observe another statement below:
if(x>y or y<z): print ('Yes')
else: print ('No')
Here, y is False but y<z is True. When using 'or' if any one condition is True,
it will take the total compound condition as 'True' and hence it will display
'Yes'.

11 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Boolean Operators
We know that there are two ‘bool' type literals. They are True and False.
Boolean operators act upon 'bool' type literals and they provide 'bool' type
output. It means the result provided by Boolean operators will be again
either True or False. There are three Boolean operators as mentioned in
Table.
Let's take x = True and y = False

Operator Example Meaning Result


and Boolean and operator. If both x and y are False
x and y
True, then it returns True, otherwise False.
or Boolean or operator. If either x or y is True, True
x or y then it returns True, else False.
not Boolean not operator. If x is True, it returns False
not x
False, else True.

Bitwise Operators
These operators act on individual bits (0 and 1) of the operands. We can
use bitwise operators directly on binary numbers or on integers also. When
we use these operators on integers, these numbers are converted into bits
(binary number system) and then bitwise operators act upon those bits.
The results given by these operators are always in the form of integers.

12 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

We use decimal number system in our daily life. This number system
consists of 10 digits from 0 to 9. We count all numbers using these 10 digits
only. But in case of binary number system that is used by computers
internally, there are only 2 digits, i.e. O and 1 which are called bits (binary
digits). All values are represented only using these two bits.

There are 6 types of bitwise operators as shown below:


 Bitwise Complement operator (~)
 Bitwise AND operator (&)
 Bitwise OR operator (1)
 Bitwise XOR operator (^)
 Bitwise Left shift operator (<<)
 Bitwise Right shift operator (>>)

Bitwise Complement Operator (~)


This operator gives the complement form of a given number. This operator
symbol is ~, which is pronounced as tilde. Complement form of a positive
number can be obtained by changing O's as 1's and vice versa. The
complement operation is performed by NOT gate circuit in electronics.
Truth table is a table that gives relationship between the inputs and the
output. The truth table is also given for NOT gate.

x 0 1 0 0 0 0 0

~x 1 0 1 1 1 1 1

e.g
x=10
~x
-11

13 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Bitwise AND Operator (&)


This operator performs AND operation on the individual bits of numbers.
The symbol for this operator is &, which is called ampersand.
Here we give an example of bitwise AND in Python.
x = 10 # Initialize the value of x by 10
y=4 # Initialize the value of y by 4
# Bitwise AND operation
print("x & y =", x & y)

Bitwise OR Operator (|)


This operator performs OR operation on the bits of the numbers. The
symbol of bitwise OR operator is ❘, which is called pipe symbol. The OR gate
circuit, which is present in the computer chip will perform the OR
operation.

14 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

x = 19 # Initialize the value of x by 19


y=2 # Initialize the value of y by 2
#Bitwise OR operation
print("x | y =", x | y)

Bitwise XOR Operator (^)


This operator performs exclusive or (XOR) operation on the bits of
numbers. The symbol is ^, which is called cap, carat, or circumflex symbol.
The XOR gate circuit of the computer chip will perform this operation.
When one of the bits is 1, another is 0, it returns true; otherwise, it returns
false.

x = 12 # Initialize the value of x by 12

15 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

y=6 # Initialize the value of y by 6


#Bitwise XOR operation
print("x ^ y =", x ^ y)

Bitwise Left Shift Operator (<<)


This operator shifts the bits of the number towards left a specified number
of positions. The symbol for this operator is <<<, read as double less than. If
we write x<<n, the meaning is to shift the bits of x towards left n positions.

If x = 10 , calculate x value if we write x<<2.


Shifting the value of x towards left 2 positions will make the leftmost 2 bits
to be lost. The value of x is 10 = 0000 1010. Now, x<<2 will be 0010 1000 =
40.

Bitwise Right Shift Operator (>>)


This operator shifts the bits of the number towards right a specified
number of positions. The symbol for this operator is >>, read as double
greater than. If we write x>>n, the meaning is to shift the bits of x towards
right n positions. >> shifts the bits towards right and also preserves the sign
bit, which is the leftmost bit. Sign bit represents the sign of the number.
Sign bit 0 represents a positive number and 1 represents a negative
number. So, after performing >> operation on a positive number, we get a
positive value in the result also. If right shifting is done on a negative
number, again we get a negative value only.
If x = 10, then calculate x>>2 value.
Shifting the value of x towards right 2 positions will make the rightmost 2
bits to be lost. x value is 10 = 0000 1010. Now x>>2 will be: 00000010 0 = 2
(in decimal).
x = int(input("Enter the value of x: ")) # Taking user input for x
y = int(input("Enter the value of y: ")) # Taking user input for y

16 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print("x & y =", x & y)


print("x | y =", x | y)
print("~y =", ~ y)
print("x ^ y =", x ^ y)
print("x >> 1 =", x >> 3)
print("y >> 1 =", y >> 3)
print("x << 1 =", x << 1)
print("y << 1 =", y << 1)
o/p:
Enter the value of x: 4
Enter the value of y: 5
x&y=4
x|y=5
~y = -6
x^y=1
x >> 1 = 0
y >> 1 = 0
x << 1 = 8
y << 1 = 10

Membership Operators
The membership operators are useful to test for membership in a sequence
such as strings, lists, tuples or dictionaries. For example, if an element is
found in the sequence or not can be asserted using these operators. There
are two membership operators as shown here:
 in
 not in

17 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

The in Operator
This operator returns True if an element is found in the specified sequence.
If the element is not found in the sequence, then it returns False.
The not in Operator
This works in reverse manner for 'in' operator. This operator returns True if
an element is not found in the sequence. If the element is found, then it
returns False.

Let's take a group of strings in a list. We want to display the members of the
list using a
for loop where the 'in' operator is used. The list of names is given below:
names = ["Poly", "Tech", "TYCO", "Ppur"]
Here the list name is 'names'. It contains a group of names. Suppose, we
want to retrieve all the names from this list, we can use a for loop as:
for name in names: print (name)
print(name)
o/p:
Poly
Tech
TYCO
Ppur

Identity Operators
These operators compare the memory locations of two objects. Hence, it is
possible to know whether the two objects are same or not. The memory
location of an object can be seen using the id() function. This function
returns an integer number, called the identity number that internally

18 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

represents the memory location of the object. For example, id(a) gives the
identity number of the object referred by the name 'a'. See the following
In the first statement, we are assigning the name (or identifier) 'a' to the
object 25. In the second statement, we are assigning another name 'b' to the
same object 25. In Python, everything is considered as an object. Here, 25 is
the object for which two names are given. If we display an identity number
of these two variables, we will get same numbers as they refer to the same
object.
statements:
a = 25
b = 25

id(a)
1670954952
id(b)
1670954952
There are two identity operators:
 is
 is not
The is Operator
The 'is' operator is useful to compare whether two objects are same or not.
It will internally compare the identity number of the objects. If the identity
numbers of the objects are same, it will return True; otherwise, it returns
False.
The is not Operator
This is not operator returns True, if the identity numbers of two objects
being compared are not same. If they are same, then it will return False.
The is' and 'is not' operators do not compare the values of the objects. They
compare the identity numbers or memory locations of the objects. If we

19 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

want to compare the value of the objects, we should use equality operator
(==)
a = 25
b = 25
if(a is b)
print("a and b have same identity")
else:
print("a and b do not have same identity")
Output:
a and b have same identity
As another example, we will take two lists with 4 elements each as:
one = [1, 2, 3, 4]
two = [1.2 * 0.3 * 0.4]
if(one is two):
print("one and two are same")
else:
print("one and two are not same")
Output:
one and two are not same
In the preceding example, the lists one and two are having same elements
or values. But the output is "one and two are not same". The reason is this:
'is' operator does not compare the values. It compares the identity numbers
of the lists. Let's see the identity numbers of these two lists by using the
id() function:
id (one)
51792432
id(two)

20 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

51 dot 6 071 dot 9 2


Since both the lists are created at different memory locations, we have their
identity numbers different. So, 'is' operator will take the lists 'one' and 'two'
as two different lists even though their values are same. It means, 'is' is not
comparing their values. We can use equality (==) operator to compare their
values as:
if(one ==two):
print("one and two are same")
else:
print("one and two are not same")
Output:
one and two are same
Operator Precedence

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division,
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, Comparisons, Identity, Membership
not in operators
not Logical NOT
and Logical AND

21 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

or Logical OR

Input & Output Statements


To provide input to a computer, Python provides some statements which
are called Input statements. Similarly, to display the output, there are
Output statements available in Python. We should use some logic to convert
the input into output. This logic is implemented in the form of several
topics in subsequent chapters. We will discuss the input and output
statements in this chapter, but in the following order:
 Output statements

 Input statements

Output statements
To display output or results, Python provides the print() function. This
function can be used in different formats which are discussed hereunder.
The print() Statement
When the print() function is called simply, it will throw the cursor to the
next line. It means that a blank line will be displayed.
The print("string") Statement
A string represents a group of characters. When a string is passed to the
print() function, the string is displayed as it is. See the example:
print("Hello")
Hello
Please remember that in case of strings, double quotes and single quotes
have the same meaning and hence can be used interchangeably.
print('Hello')
Hello

22 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

We can use escape sequence characters inside the print () function. An


escape sequence is a character that contains a special meaning. For
example, '\n' indicates new line. '\t' represents tab space.
print("This is the \n first line")
This is the
first line
print("This This is the \t first line")
This is the first line
To escape the effect of escape sequence, we should add one more '\'
(backslash before the escape sequence character. For example, \\n displays
'\n' and \\t displays backslash t'
print("this is the \\n first line")
this is the \n first line
We can use repetition operator (*) to repeat the strings in the output as:
print(3*'poly')
poly poly poly
The operator '+' when used on numbers will perform addition operation.
The same '+' will not do addition operation on strings as it is not possible to
perform arithmetic operations on strings. When we use '+' on strings, it will
join one string with another string. Hence '+' is called concatenation
(joining) operator when used on strings.
print("City name="+"Hyderabad")
City name=Hyderabad
The ‘+’ operator in the preceding statement joined the two strings without
any space in between. We can also write the preceding statement by
separating the strings using ‘ , ‘ as:
print("City name=", "Hyderabad") City name Hyderabad
In this case, a space is used by the print() function after each string. In the
output, observe the single space after the string 'City name =’ . When the

23 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print() function sees a comma, it will assume that the values are different
and hence a space should be used between them for clarity.

The print(variables list) Statement


We can also display the values of variables using the print() function. A list
of variables can be supplied to the print() function as:
a, b = 2, 4
print(a)
2
print(a, b)
24
Observe that the values in the output are separated by a space by default.
To separate the output with a comma, we should use 'sep' attribute as
shown below. 'sep' represents separator. The format is sep="characters"
which are used to separate the values in the output.
print(a, b, sep=",")
2,4
print(a, b, sep =’:’ )
2:4
print(a, b, sep='----')
2---4
When several print() functions are used to display output, each print()
function will display the output in a separate line as shown below:
print("Hello")
print("Dear")
print('How are u?')
Output:
Hello
24 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Dear
How are U?
Each print() function throws the cursor into the next line after displaying
the output. This is the reason we got the output in 3 lines. We can ask the
print() function not to throw the cursor into the next line but display the
output in the same line. This is done using 'end' attribute. The way one can
use it is end="characters" which indicates the ending characters for the
line. Suppose, we write end=", then the ending character for each line will
be ‘ ‘ (nothing) and hence it will display the next output in the same line.
See the
print("Hello", end=' ‘ )
print("Dear", end=’ ' )
print('How are u?', end=' ' )
HelloDearHow are U?
If we use end='\t' then the output will be displayed in the same line but tab
space will separate them as:
print ("Dear",end=’\t’)
print('How are u?', end='\t')
Output:
Hello
example:
Output:
Dear How are U?
If we use end='\n' then the output is displayed in a separate line. So, '\n' is
the default value for 'end' attribute.

The print(object) Statement


We can pass objects like lists, tuples or dictionaries to the print() function
to display the elements of those objects. For example,

25 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

list = [10, 'A', 'Hai']


print(1st)
[10, 'A', 'Hai']
d = {'Idly':30.00, 'Roti':45.00, 'Chappati':55.50]
print(d)
{'Idly': 30.0, 'Roti': 45.0, 'Chappati': 55.5}

The print("string", variables list) Statement


The most common use of the print() function is to use strings along with
variables inside the print() function.
a=2
print(a, "is even number")
2 is even number
print('You typed', a, 'as input')
You typed 2 as input

The print(formatted string) Statement


The output displayed by the print () function can be formatted as we like.
The special operator %' (percent) can be used for this purpose. It joins a
string with a variable or value in the following format:
print("formatted string" % (variables list))
In the "formatted string", we can use %i or %d to represent decimal integer
numbers. We can use %f to represent float values. Similarly, we can use %s
to represent strings. See the example below:
x=10
print('value=%i' % x)
 value= 10

26 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

As seen above, to display a single variable (i.e. x) we need not wrap it inside
parentheses. When more than one variable is to be displayed, then
parentheses are needed as:
x , y = 10 , 20
print(‘x=%i y=%d’, %(x,y))
 x=10 y=20
To display a string, we can use %s in the formatted string. When we use
%20s, it will allot 20 spaces and the string is displayed right aligned in
those spaces. To align the string towards left side in the spaces, we can use
%-20s. Consider the following examples:
name=’Poly’
print(‘name %s’, %name )
 name Poly

name=’Poly’
print(‘name (%20s)’, %name )
 name ( Poly)
name=’Poly’
print(‘name (%-20s)’, %name )
 name (Poly )

We can use %c to display a single character as shown below:


name='Poly'
print('Name %c, %c’,% (name[0], name[1]))
 Name P, o
The above example displayed 0 and 1 characters from name variable. We
can use slicing operator on a string to display required characters from the
string. For example, name [0:2] gives 0th to 1 character from name as:

27 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

name='Poly'
print ('Name %c, %c’, % (name [0:2]))
 Name PO
To display floating point values, we can use %f in the formatted string. If we
use %8.2f, then the float value is displayed in 8 spaces and within these
spaces, a decimal point and next 2 fraction digits.
When we use %.3f, then the float value is displayed with 3 fraction digits
after the decimal point. However, the digits before decimal point will be
displayed as they are. Consider the following examples:
num-123.456789
print('The value is: %f' % num)
 The value is: 123.456789
print('The value is: %8.2f' %num)
 The value is: 123.46 #observe 2 spaces before the value
print('The value is: %.2f' %num)
 The value is: 123.46
Inside the formatted string, we can use replacement field which is denoted
by a pair of curly braces { }. We can mention names or indexes in these
replacement fields. These names or indexes represent the order of the
values. After the formatted string, we should write member operator and
then format() method where we should mention the values to be displayed.
Consider the general format given below:
print('format string with replacement fields' .format(values))
To display a single value using index in the replacement field, we can write
as:
n1, n2, n3=1,2,3
print (‘number1={0}’ .format(nl))
 number1=1

28 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

In the above statement, observe (0) which was replaced by the value of n1.
To display all the three numbers, we can use:
print('number1={0},number2={1},number3={2}'.format(n1,n2,n3))
 number1=1, number2=2, number3=3
In the above statement, {0},{1},{2} represent the values of n1, n2 and n3,
respectively. Hence, if we change the order of these fields, we will have
order of the values to be changed in the output as:
print('number1={1},number2={0},number3={2}'.format(n1, n2, n3))
 number1=2, number2=1, number3=3
As an alternate, we can also use names in the replacement fields. But the
values for these names should be provided in the format() method.
Consider the following example:
print('number1={two}, number2={one}, number3={three}’. format
(one=n1. Two=n2, three=n3))
 number1-2, number2-1, number3=3
We can also use the curly braces without mentioning indexes or names. In
this case, those braces will assume the sequence of values as they are given.
Consider the following
print('number1={}, number2={}, number3={}'. format(n1, n2, n3))
 number1=1, number2=2, number3=3
All format given in below program.
nm,sal='poly', 1200.453
print('name={0},salary={1}'.format(nm,sal))
print('name={n},salary={n}'.format(n=nm,s=sal))
print('name={:s},salary={:.2f}'.format(nm,sal))
print('name=%s,salary=%.2f'%(nm,sal))
"""
o/p:

29 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

name=poly,salary=1200.453
name=poly,salary=poly
name=poly,salary=1200.45
name=poly,salary=1200.45
"""
Input Statements
To accept input from keyboard, Python provides the input() function. This
function takes a value from the keyboard and returns it as a string. For
example,
str = input() #this will wait till we enter a string
Poly tech # enter this string
print(str)
Poly tech
It is a better idea to display a message to the user so that the user
understands what to enter. This can be done by writing a message inside
the input() function as:
str= input('Enter your name: ')
Enter your name: Poly tech
print(str)
Poly tech
Once the value comes into the variable 'str', it can be converted into 'int' or
'float' etc. This is useful to accept numbers as:
str = input('Enter a number: ')
Enter a number: 125
x = int(str) # str is converted into int
print(x)
125

30 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

We can use the int() function before the input() function to accept an
integer from the keyboard as:
x = int (input('Enter a number: '))
Enter a number: 125
print(x)
125
Similarly, to accept a float value from the keyboard, we can use the float()
function along with the input() function as:
x = float(input('Enter a number: '))
Enter a number: 12.345
print(x)
12.345
We will understand these concepts with the help of a Python program. Let's
write a program to accept a string and display it, as shown in Program .

A Python program to accept a string from keyboard and display it.


#accepting a string from keyboard
str = input("Enter a string: ")
print('U entered: ' str) #display entire string
Output:
Enter a string: Hello
U entered: Hello
The way we accept a character from the keyboard is also same as accepting
a string.
A Python program to accept a character as a string.
Accepting single character or string from keyboard
Ch= input("Enter char:”)

31 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print("u entered: "+ch)


Output:
Enter a char: A
U entered: A
From the output of the above program, we can understand that the input()
function is accepting the character as a string only. If we need only a
character, then we should use the index, as: ch[0]. Here Oth character is
taken from the string.
Now, let's plan a program to accept an integer number from the keyboard.
Since, the input() function accepts only a string, it will accept the integer
number also as a string. Hence, we should convert that string into integer
number using the int() function. This is shown in Program 4.
Program 4: A Python program to accept an integer number from keyboard.
#accepting integer from keyboard
str = input('Enter a number: ')
x = int(str) #convert string into int
print('u entered: ', x); #display the int number
Output:
Enter a number: 1122
U entered: 1122
The same program can be rewritten by combining the first two statements.
x = int(input('Enter a number: '))"
print('U entered: ', x); #display the int number
Output:
Enter a number: 123456
U entered: 123456

32 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

The same procedure can be adopted to accept a floating point number from
the keyboard. While the input() function accepts a float value as a string, it
should be converted into float number using the float() function.
#accepting float number from keyboard
X = float(input('Enter a number: '))
print('U entered: ', x); #display the float number
Output:
Enter a number: 12. 54621345789
U entered: 12.54621345789
From the above output, we can understand that the float values are
displayed to an accuracy of 15 digits after decimal point. In the next
program, we will accept two integer numbers and display them.
A Python program to accept two integer numbers from keyboard.
#accepting two numbers from keyboard
x=int( input (print(‘Enter first number: '))
y=int( input (print(‘Enter Second number: '))
print('u entered: ', x, y) #display both the numbers separating with a
space
 Enter first number: 45
Enter Second number:54
u entered: 45 54

The eval() function takes a string and evaluates the result of the string by
taking it as a Python expression. For example, let's take a string - a + b -4^ -
where a = 5 and b = 10 If we pass the string to the eval() function, it will
evaluate the string and returns the result Consider the following example:
a, b = 5,10
result = eval("a+b-4")

33 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print(result)
 11
We can use the eval() function along with input() function. Since the input()
function accepts a value in the form of a string, the eval() function receives
that string and evaluates it. In Program 14, we can enter an expression that
is evaluated by the eval() function and result is displayed.
Evaluating an expression entered from keyboard.
# using eval() along with input function
x=eval( input (‘Enter an expression: "))
print(‘Result=%d’%x)
Enter an expression: 10 + 5 - 4
Result= 11
We can use the combination of eval( ) and input() functions to accept
objects like lists or tuples. When the user types the list using square braces
[ ], eval() will understand that it is a list.
A Python program to accept a list and display it.

#accepting a list from keyboard


list= eval(input("Enter a list: "))
print("List", list)
Output:
Enter a list: ["Ajay", "Preethi", "Sashank", "vishnu"]
list=[ ‘Aja y' , 'Preethi', "Sashank', 'Vishnu']
Entera list: [10, 20, 30]
List [10, 20, 30]
Similarly, when the user types a tuple using parentheses (), eval() will
understand that it is a tuple.
A Python program to accept a tuple and display it.
34 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

#accepting a tuple from keyboard


tpl= eval(input("Enter a tuple: "))
print("Tuple", tpl)
Output:
Enter a tuple: (10, 20, 30, 40)
Tuple (10, 20, 30, 40)

Command Line Arguments


We can design our programs in such a way that we can pass inputs to the
program when we give run command. For example, we write a program by
the name 'add.py' that takes two numbers and adds them. We can supply
the two numbers as input to the program at the time of running the
program at command prompt as:
C:\>python add.py 10 22
Sum - 32
Here, add.py is our Python program name. While running this program, we
are passing two arguments 10 and 22 to the program, which are called
command line arguments. So, command line arguments are the values
passed to a Python program at command prompt (or system prompt).
Command line arguments are passed to the program from outside the
program. All the arguments should be entered from the keyboard
separating them by a space. These arguments are stored by default in the
form of strings in a list with the name 'argv' which is available in sys
module. Since argv is a list that contains all the values passed to the
program, argv[0] represents the name of the program, argv[1] represents
the first value, argv[2] represents the second value and so on. If we want to
find no of command line argument we can use len() function as: len(argv).
import sys
n=len(sys.argv)
a=sys.argv[1]

35 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

b=sys.argv[2]
c=int(a)+int(b)
print("C= ",c)
print("\n No of ARGV:- ", n)

"""
o/p:
python commandline.py 10 20
C= 30
No of ARGV:- 3
"""
Control Statements
When we write a program, the statements in the program are normally
executed We by and one by one. This type of execution is called 'sequential
execution’.
To develop critical programs, the programmer should be able to change the
flow of execution as needed by him. For example, the programmer may
wish to repeat a group of statements several times or he may want to
directly jump from one statement to another statement in the program. For
this purpose, we need control statements.
Conditional Statements
Conditional statements are statements which control or change the flow of
execution. The following are the control statements available in Python:
 if statement
 if... else statement
 if... elif... else statement
 while loop
 for loop
 else suite
 break statement

36 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

 continue statement
 pass statement
 assert statement
 return statement
Please note that the switch statement found in many languages like C and
Java is not available in Python.

The if Statement
This statement is used to execute one or more statement depending on
whether a condition is True or not. The syntax or correct format of if
statement is given below:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements
given after colon (:) are executed. We can write one or more statements
after colon (:). If the condition is False, then the statements mentioned after
colon are not executed.

To understand the simple if statement, let's write a Python program to


display a digit in words.
A Python program to express a digit in a word.
#understanding if statement
if num==1:
print("One")
o/p: One
We can also write a group of statements after colon. The group of
statements in Python is called a suite. While writing a group of statements,
we should write them all with proper indentation. Indentation represents
the spaces left before the statements. The default indentation used in

37 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Python is 4 spaces. Let's write a program to display a group of messages


using if statement.
A Python program to display a group of messages when the condition is
true.
# understanding if statement
str = 'Yes'
if str == 'Yes':
print("Yes")
print("This is what you said")
print("Your response is good")
O/p:
This is what you said
Your response is good
Observe that every print() function mentioned after colon is starting after 4
spaces only. When we write the statements with same indentation, then
those statements are considered as a suite (or belonging to same group). In
Program , the three print statements written after the colon form a suite.

A Word on Indentation
Understanding indentation is very important in Python. Indentation refers
to spaces that are used in the beginning of a statement. The statements
with same indentation belong to same group called a suite. By default,
Python uses 4 spaces but it can be increased or decreased by the
programmers. Consider the statements given below
f x ==1
print('a')
print('b')
if y ==2
print('c')
38 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print (‘d’ )
print (‘end’ )
if x=1:
print('end')
belong to same group as they do not have any spaces before them. So, after
executing the if statement, Python interpreter goes to the next statement,
i.e. print('end'). Even if the statement if x== 1' is not executed, interpreter
will execute print('end') statement as it is the next executable statement in
our program.
In the next level, the following statements are typed with 4 spaces before
them and hence they are at the same level (same suite).
print('a')
print('b')
if y = 2
These statements are inside if x== 1 statement. Hence if the condition is
True (i.e. x ==1 is satisfied), then the above 3 statements are executed.
Thus, the third statement if y== 2 is executed only if x ==1 is True. At the
next level, we can find the following statements:
print (‘ c’ )
print('d')
These two statements are typed with 8 spaces before them and hence they
belong to the same group (or suite). Since they are inside if y = 2 statement,
they are executed only if condition y ==2 is True.

The if ... else Statement


The if ... else statement executes a group of statements when a condition is
True: otherwise, it will execute another group of statements. The syntax of
if ... else statement is given below:
if condition:

39 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

statements1
else:
statements2
If the condition is True, then it will execute statements1 and if the condition
is False, then it will execute statements2. It is advised to use 4 spaces as
indentation before statements1 and statements2. In following Program, we
are trying to display whether a given number is even or odd. The logic is
simple. If the number is divisible by 2, then it is an even number; otherwise,
it is an odd number. To know whether a number is divisible by 2 or not, we
can use modulus operator (%). This operator gives remainder of division. If
the remainder is 0, then the number is divisible, otherwise not.
A Python program to test whether a number is even or odd.
# to know if a given number is even or odd
x = 10
if x%2==0:
print (x,” is even number")
else:
print ( x ," is odd number")
Output:
10 is even number
The same program can be rewritten to accept input from keyboard. In
Program 5, we are accepting an integer number from keyboard and testing
whether it is even or odd.
A Python program to accept a number from the keyboard and test whether
it is even or odd.
# to know if a given number is even or odd
x=int (input) "Enter a number: "))
if x%2 ==0:
print(x, is even number")

40 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

else:
print(x, " is odd number")
Output:
Enter a number: 11
11 is odd number

We will write another program where we accept a number from the user
and test whether that number is in between 1 and 10 (inclusive) or not. If
the entered number is x, then the condition x >= 1 and x <= 10 checks
whether the number is in between 1 and 10.
A Python program to test whether a given number is in between 1 and 10.
# using 'and' in if else statement .
x = int(input('Enter a number: '))
if x >= 1 and x <= 10:
print("You typed", x, "which is between 1 and 10”)
else:
print("You typed", x, "which is below 1 or above 10 “)
Output:
Enter a number: 9
You typed 9 which is between 1 and 10
Observe the condition after 'if'. We used 'and' to combine two conditions x
>= 1 and x <= 10. Such a condition is called compound condition.

The if ... elif ... else Statement


Sometimes, the programmer has to test multiple conditions and execute
statements depending on those conditions. if …elif… else statement is
useful in such situations. Consider the following syntax of if ... elif ... else
statement:

41 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

if conditionl:
statementsl
elif condition2:
statements2
elif condition3:
statements3
else:
statements4
When condition1 is True, the statements1 will be executed. If condition1 is
False, then condition2 is evaluated. When condition2 is True, the
statements2 will be executed. When condition2 is False, the condition3 is
tested. If condition3 is True, then statements3 will be executed. When
condition3 is False, the statements4 will be executed. It means statements4
will be executed only if none of the conditions are True.
Observe colon (:) after each condition. The statements1, statements2,
represent one statement or a suite. The final 'else' part is not compulsory. It
means, it is possible to write if…elif statement, without 'else' and
statements4. Let's write a program to understand the usage of if…elif…else
statement. In below program we are checking whether a number is positive
or negative. A number becomes positive when it is greater than 0. A number
becomes negative when it is lesser than 0. Apart from positive and negative,
a number can also become zero (neither +ve nor -ve). All these 3
combinations are checked in the program.
A Python program to know if a given number is zero, positive or negative.
# to know if a given number is zero or +ve or -ve
num=-5
if num==0:
print(num, "is zero")
elif num>0:
print(num, "is positive")

42 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

else:
print(num, "is negative")
Output:
-5 is negative
observe the indentation. There are 4 spaces before every statement after
colon. Now, we write another program that accepts a numeric digit from
keyboard and prints it in words. In this program, we will use several elif
conditions. After colon, we are leaving only one space before every print()
statement. While this is not recommended way of using indentation, this
program will run properly since every statement has equal number of
spaces (1 space) as indentation.
A program to accept a numeric digit from keyboard and display in words.
# to display a numeric digit in words
x = int(input('Enter a digit: '))
if x ==0: print("ZERO")
elif x ==1: print("ONE")
elif x ==2: print("TWO"),
elif x ==3: print("THREE")
elif x ==4: print(“FOUR")
elif x ==5: print ("FTVE” )
elif x ==6: print("SIX")
elif x ==7: print("SEVEN")
elif x ==8: print("EIGHT")
elif x ==9: print ("NINE”) # else part not compulsory
Output:
Enter a digit: 5
FIVE

43 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

In the above program, if we enter a digit '15', then the program does not
display any output. On the other hand, if we want to display a message like
'Please enter digit between 0 and 9', we can add 'else' statement at the end
of the program, as:
else: print('Please enter digit between 0 and 9')

The while Loop


A statement is executed only once from top to bottom. For example, if is a
statement that is executed by Python interpreter only once. But a loop is
useful to execute repeatedly. For example, while and for are loops in Python.
They are useful to execute a group of statements repeatedly several times.
The while loop is useful to execute a group of statements several times
repeatedly depending on whether a condition is True or False. The syntax
or format of while loop is:
while condition:
statements
Here, 'statements' represents one statement or a suite of statements.
Python interpreter first checks the condition. If the condition is True, then
it will execute the statements written after colon (:) After executing the
statements, it will go back and check the condition again. If the condition is
again found to be True, then it will again execute the statements. Then it
will go back to check the condition once again. In this way, as long as the
condition is True, Python interpreter executes the statements again and
again. Once the condition is found to be False, then it will come out of the
while loop.
In Program, we are using while loop to display numbers from 1 to 10. Since,
we should start from 1, we will store ‘ 1' into a variable ‘x' Then we will
write a while loop as:
while x <= 10
Observe the condition. It means, as long as x value is less than or equal to
10, continue the while loop. Since we want to display 1,2,3, ... up to 10, we
need this condition. To display x value, we can use:

44 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print(x)
Once this is done, we have to increment x value by 1, by writing x +=1 or x =
x + 1 . Now, consider Program in which while loop is used to display
numbers.
x=1
while x<=10:
print(x)
x+=1
print("End")
1
2
3
4
5
6
7
8
9
10
End
For loop
A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string). This is less like the for keyword in other
programming languages, and works more like an iterator method as found
in other object-orientated programming languages. With the for loop, we
can execute a set of statements, once for each item in a list, tuple, set etc.
The for loop is useful to iterate over the elements of a sequence. It means,
the for loop can be used to execute a group of statements repeatedly
depending upon the number of elements in the sequence. The for loop can

45 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

work with sequence like string, list, tuple, range etc. The syntax of the for
loop is given below:
for var in sequence:
statements
The first element of the sequence is assigned to the variable written after
'for' and then the statements are executed. Next, the second element of the
sequence is assigned to the variable and then the statements are executed
second time. In this way, for each element of the sequence, the statements
are executed once. So, the for loop is executed as many times as there are
number of elements in the sequence.
A Python program to display characters of a string using for loop.
# to display each character from a string
str='Hello'
For ch in str :
print(ch)
H
e
l
l
o
Display odd numbers between 1 and 10:
for i in range(1, 10, 2):
print(i)

Display numbers in descending order:


for x in range (10, 0, - 1 ) :
print(x)

A program to display the elements of a list using for loop.


list = [10,20.5,'A', 'America'] # take a list of elements
# display each element from the list

46 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

for element in list:


print(element)

A Python program to display and find the sum of a list of numbers using for
loop.
# to find sum of list of numbers using for.
list = [10,20,30,40,50] # take a list of numbers
sum=0 #initially sum is zero
for i in list:
print(i) #display the element from list
sum+=i #add each element to sum
print('Sum=', sum)
# to find sum of list of numbers using while.
list=[10,22,33,44,55,66]
sum=0
i=0
while i < len(list):
print(list[i])
sum+=list[i]
i+=1
print("sum=",sum)

 o/p:
10
22
33
44
55
66

47 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

sum= 230

Infinite Loops
i=1
while i<=10:
print(i)

It will display the value 1 forever. To stop the program, we have press
Control+C at system prompt. Another way of creating an infinite loop is to
write 'True' in the condition part of the while loop so that the Python
interpreter thinks that the condition is True always and hence executes it
forever. See the example:
while(True)
print("Hai")
This loop will always display 'Hai' without stopping since the condition is
read as 'True' always. Infinite loops are drawbacks in a program because
when the user is caught in an infinite loop, he cannot understand how to
come out of the loop. So, it is always recommended to avoid infinite loops in
any program.

Nested Loops
It is possible to write one loop inside another loop. For example, we can
write a for loop inside a while loop or a for loop inside another for loop.
Such loops are called 'nested loops'. Take the following for loops:

for i in range(3): # i values are from 0 to 2


for j in range(4): # j values are from 0 to 3
print('i=', i, '\t', 'j=',j) # display i and į values
The outer for loop repeats for 3 times by changing i values from 0 to 2. The
inner for loop repeats for 4 times by changing į values from 0 to 3. Observe
the indentation (4 spaces) before the inner for loop. The indentation
represents that the inner for loop is inside the
outer for loop. Similarly, print() function is inside the inner for loop.
48 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

When outer for loop is executed once, the inner for loop is executed for 4
times. It means, when i value is 0, j values will change from 0 to 3. So,
print() function will display the following output:
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
Once the inner for loop execution is completed (j reached 3), then Python
interpreter will go back to outer for loop to repeat the execution for second
time. This time, i value will be 1& again loop is executed for 4 times.
i=1 j=0
i=1 j=1
i=1 j=2
i=1 j=3
This time, i value will be 2 & again loop is executed for 4 times.
i=2 j=0
i=2 j=1
i=2 j=2
i=2 j=3

A Python program that displays stars in right angled triangular form using
nested loops.
# to display stars in right angled triangular form
for i in range(1, 11): # to display 10 rows
for j in range(1, i+1): # no. of stars = row number
print('*’ , end=' ')
print()

49 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

Ans 2:
for i in range(1,11):
print('*'*(i))
o/p:
*
**
***
****
*****
******
*******
********
*********
**********
A Python program to display the stars in an equilateral triangular form
using a single for loop.
# to display stars in equilateral triangular form
n=40
for i in range(1, 11):
print(‘ ‘*n, end='') # repeat space for n times
print ('* '*(i)) # repeat star for i times
n-=1
A Python program to display numbers from 1 to 100 in a proper format. #
Displaying nur numbers from 1 to 100 in 10 rows and 10 cols. for

for x in range(1, 11):


for y in range(1, 11):
print('{:8}'. format (x * y) , end='') # each column size is 8
print()
o/p:
1 2 3 4 5 6 7 8 9 10

50 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The else Suite
In Python, it is possible to use 'else' statement along with for loop or while
loop in the form
for with else
for(var in sequence):
statements
else:
statements
while with else
while(condition):
statements
else:
statements

The statements written after 'else' are called suite. The else suite will be
always executed irrespective of the statements in the loop are executed or
not. For example,
for i in range (5):
print (“ Yes” )
else:

51 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print (“N0”)
this will display the following output:
Yes
Yes
Yes
Yes
Yes
No

It means, the for loop statement is executed and also the else suite is
executed. Suppose, we write:
for i in range(0):
print (“ Yes”)
else:
print("No")
This will display the following output:
No
Here, the statement in the for loop is not even executed once, but the else
suite is executed as usual. So, the point is this: the else suite is always
executed. But then where is this else suite useful?
Sometimes, we write programs where searching for an element is done in
the sequence When the element is not found, we can indicate that in the
else suite easily. In this case, else with for loop or while loop - is very
convenient. Let's now write a program where we take a list of elements and
using for loop we will search for a particular element in the list. If the
element is found in the list, we will display that is found in the group; else
we will display a message that the element is not found in the list. This is
displayed using else suite.
list=[10,20,30,50,60,40,70]
search=int(input(“Enter The no to search:- ”))
for ele in list:
if ele==search

52 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

print(“Element found”)
brea;
else:
print(“Element not found in list”)
The break Statement
The break statement can be used inside a for loop or while loop to come out
of the loop. When break' is executed, the Python interpreter jumps out of
the loop to process the next statement in the program.
We have already used break inside for loop in search Program. When the
element is found, it would break the for loop and comes out. We can also
use break inside a while loop.
i=10
while i>=1:
print(i)
i-=1
if i==5:
break;
print("out of loop")
o/p:
10
9
8
7
6
out of loop

The continue Statement

The continue statement is used in a loop to go back to the beginning of the


loop. It means, when continue is executed, the next repetition will start.
When continue is executed, the subsequent statements in the loop are not
executed.
for i in range(1,20):
if i%2!=0:

53 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

continue
print(i)

o/p:
2
4
6
8
10
12
14
16
18

The pass Statement

The pass statement does not do anything. It is used with if statement or


inside a loop to represent no operation. We use pass statement when we
need a statement syntactically but we do not want to do any operation.
e.g.
list=[-11,10,-22,20,-33,-44,-55]
for i in list:
if i>0:
pass
else
print(i)
print (“end of pass”)
o/p: -11
-22
-33
-44
-55
end of pass
The assert Statement

The assert statement is useful to check if a particular condition is fulfilled


or not. The syntax is as follows:
assert expression, message
In the above syntax, the 'message' is not compulsory. Let's take an example.
If we want to assure that the user should enter only a number greater than
0, we can use assert statement as:
assert x>0, "wrong input entered"
54 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

In this case, the Python interpreter checks if x>0 is True or not. If it is True,
then the next statements will execute, else it will display AssertionError
along with the message "Wrong input entered".
e.g.
x=int(input("Enter no greater than 0: "))
assert x>0, "Wrong input entered"
print("No -",x)

o/p:
Enter no greater than 0: 5
No – 5

Enter no greater than 0: -2


Traceback (most recent call last):
File
"C:/Users/COHOD/AppData/Local/Programs/Python/Python312/asser
tdemo.py", line 2, in <module>
assert x>0, "Wrong input entered"
AssertionError: Wrong input entered

Questions
Summer-22
1. List identity operators in python. (2M)
2. Write a program to print following : (4M)
1
1 2
1 2 3
1 2 3 4
55 | P a g e
Prashant S. Bhandare
Unit II: Python Operators & Control statements Programming with “Python” (22616)

3. Explain membership and assignment operators with example. (4M)


4. Explain decision making statements If - else, if - elif - else with
example. (4M)
Winter-22
1. List comparison operators in Python. (2M)
2. Describe bitwise operators in Python with example. (4M)
3. Write python program to illustrate if else ladder. (4M)
4. Write Python code for finding greatest among four numbers. (4M)
5. What is command line argument? Write python code to add two
numbers given as input from command line arguments and print its
sum. (4M)

56 | P a g e
Prashant S. Bhandare

You might also like