Python Unit II Unit 3 COntrol Flow FINAL
Python Unit II Unit 3 COntrol Flow FINAL
PROGRAMMING
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus Division
Floor Division (It removes the digits after the
//
decimal point)
** Exponent
Operator Description
== Checks Equality
!= Not Equal
= Assigns Value
Operator Description
Operator Description
|| Logical OR
! Logical NOT
Operator Description
Returns TRUE if a variable is found in the
in Operator
specified sequence and FALSE otherwise.
Returns TRUE if a variable is not found in
not in
the specified sequence and FALSE
Operator
otherwise
Operator Description
Returns TRUE if the operands of both side
is Operator of the operator point to the same object and
FALSE otherwise.
Returns TRUE if the operands of both side
is not
of the operator does not point to the same
Operator
object and FALSE otherwise
Syntax:
if(condition):
statement(s)
if 12 > 3:
print(“Twelve is greater !")
Example:
x=10
if(x>0):
x=x+1
print(“x=”,x)
x=11
Syntax:
if(condition):
Statement Block 1
else:
Statement Block 2
while (condition):
statement(s)
In while loop, the condition is tested before any of the statements
in the statement block is executed.
If the condition is true then the statement block will executed
otherwise, the control will jump to statement Y
Output:
1
2
3
4
5
JanuaryProblem
4, 2025 Solving and Python Programming
while Loop
Output:
0 1 2 3 4 5 6 7 8 9 10 Completed
Sum= 55
Problem Solving and Python Programming
while Loop
Example: Sum and Average of first 10 Numbers
i=0
s=0
while(i<=10):
s=s+i
i=i+1
avg=float(s)/10
print(“The Sum of first 10 Numbers is:”,s)
print(“The average of first 10 Numbers is:”, avg)
Output:
The Sum of first 10 Numbers is: 55
The average of first 10 Numbers is: 5.5
i=2
while(i>0):
i=i-1 Options:
A. 2
B. 3
C. 1
D. 0
for loop also provides the mechanism to repeat a task until a particular
condition is True.
It is usually known as a definite loop because the programmer knows how
many times the loop will repeat.
In python, for…in is a statement used to iterate over the sequence of
statements.
Every iteration the loop must make the loop control variable closer to the
end of the range (i.e.) the loop control variable will be updated for every
iteration.
OUTPUT:
1
2
Sita
7
Ram
5
JanuaryProblem
4, 2025 Solving and Python Programming
For loop
OUTPUT:
1
2
Sita
7
Ram
5
JanuaryProblem
4, 2025 Solving and Python Programming
Loop Control Statements
JanuaryProblem
4, 2025 Solving and Python Programming
The break Statement
list=[1,2,’Sita’,7,’Ram’,5] OUTPUT:
for counter in list: 1
print(counter) 2
if counter == 7: Sita
break 7
It is used to terminate the execution of the nearest enclosing loop which
it appears.
It is widely used in for and while loop.
i=1
while i<=10:
print(i, end=“ “)
if(i==5):
break
i=i+1
print(“Completed”)
Output:
12345
Completed
OUTPUT:
list=[1,2,’Sita’,7,’Ram’,5] 1
for counter in list: 2
if counter == 7: Sita
continue Ram
print(counter) 5
Output:
1 2 3 4 6 7 8 9 10
COMPLETED
Output:
Produces Error - KeyboardInterrupt
Output:
Above statement will execute
if number is 2:
pass
else:
print ("Number: ", number)
display(2)
Output:
display(3)
???
JanuaryProblem
4, 2025 Solving and Python Programming
Iterative Statements - pass
if number is 2:
pass
else:
print ("Number: ", number)
display(2)
Output:
display(3)
Number: 3
JanuaryProblem
4, 2025 Solving and Python Programming
The pass Statement
In python programming, pass is a NULL statement.
Difference between pass & comment is that while the interpreter ignores
a comment entirely, but pass is not ignored.
comment statement will not get executed but the pass statement will be
executed but nothing happens.
JanuaryProblem
4, 2025 Solving and Python Programming
for Loop
range() function:
With single argument:
Example: range(10) is equal to range(0,10)
Output:
1
2
3
4
Output:
1234
Output:
1234
Example:
for i in range(1,10,2):
print(i, end=“ “)
Output:
13579
????
JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function
JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function
JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function
JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function
JanuaryProblem
4, 2025 Solving and Python Programming
for loop – range function
JanuaryProblem
4, 2025 Solving and Python Programming
Nested loop
a=["red","tasty"]
b=["apple","cherry"]
for x in a:
for y in b:
print(x,y) Output:
red apple
red cherry
tasty apple
tasty cherry
JanuaryProblem
4, 2025 Solving and Python Programming
Factorial of a given number using loop
Output:
Enter the number: 5
Factorial of 5 is: 120
Output: 28.27431
Output: 28.27431
print(absolute_value(-7))
def cube(x):
z=x*x*x
return(z)
num=10
result=cube(num)
print("Cube of",num,"=",result)
--------------------------------------
Output:
Cube of 10 = 1000
In python, we cannot access any variable from any part of the
program.
Existence of the variable depends on how the variable has been
declared.
Local Variable:
A variable which is defined within a function is local to that
function.
In this program, there are 3
def add(x,y): local variables – x,y and sum.
sum = x + y
return sum
z = 25
def func():
print(z)
func()
print(z)
Output:
25
25
z = 25 z = 25
def func(): def func():
print(z) z=10
print(z)
func()
print(z) func()
print(z)
Output: Output:
25 10
25 25
Problem Solving and Python Programming
Local & Global Variables
Global variables are those variables which are declared outside of the
function or in global scope. This means that a global variable can be
accessed inside or outside of the function.
z = 25 z = 25 z = 25
def func(): def func(): def func():
print(z) z=10 global z
print(z) z=10
func() print(z)
print(z) func()
print(z) func()
Output: Output: print(z) Output:
25 10 10
25 25 10
Problem Solving and Python Programming
Here is a Question
def func():
print(z)
z=36
print(z)
z=10
func()
print(z)
Output: ???
def func():
print(z)
z=36
print(z)
z=10
func()
print(z)
Output:
UnboundLocalError: local variable 'z'
referenced before assignment
Problem Solving and Python Programming
Here is a Question
Output: Output:
Local variable ‘str’ referenced Welcome to Python
before assignment Hello World
Output:
Enter the number: 5
Factorial of 5 is: 120
Logic:
Output:
Enter the number: 5
Factorial of 5 is: 120
Example:
>>> message = ‘hello‘
Example:
message=“Hello”
for i in message:
print(i)
Output:
H
e
l
l
o
Problem Solving and Python Programming
Strings Are Immutable
• Which means one can’t change an existing string.
>>> a='hello'
>>> a[0]=‘c‘
• TypeError: 'str' object does not support item assignment
>>> s+t
'helloworld‘
>>> message=“Hello"
Converts all character in the
lower() >>> print(message.lower())
string to lowercase
hello
>>> message=“Hello"
Converts all character in the
upper() >>> print(message.upper())
string to uppercase
HELLO
Problem Solving and Python Programming
Strings Functions & Methods
Function Description Example
Toggles the case of every character. >>> message="how ARE you?"
swapcase() (uppercase to lower case and vice >>> print(message.swapcase())
versa) HOW are YOU?
Returns TRUE if the string contains
>>> message=“ HELLO”
atleast 1 character and every
isupper() >>> print(message.isupper())
character is an upper case alphabet
True
and FALSE otherwise
>>> message="hello"
Returns TRUE if the string has >>> print(message.islower())
atleast 1 character and every True
islower()
character is a lowercase alphabet or >>> message="helloH"
otherwise. >>> print(message.islower())
False
>>> print(string.ascii_uppercase)
string.ascii_upper Refers to all Uppercase letters
ABCDEFGHIJKLMNOPQRSTU
case form A-Z
VWXYZ
>>> print(string.punctuation)
String of ASCII characters that are
string.punctuation !"#$%&'()*+,-./:;<=>?
considered to be punctuation
@[\]^_`{|}~
>>> print(string.printable)
0123456789abcdefghijklmnopqrst
Refers to a string of printable
uvwxyzABCDEFGHIJKLMNOP
characters which includes digits,
sring.printable QRSTUVWXYZ!"#$
letters, punctuation and
%&'()*+,-./:;<=>?@[\]^_`{|}~
whitespaces.
Example:
Example:
import array as arr import array as arr
a = arr.array('i', [2, 4, 6, 8]) a = arr.array(‘u', [‘a’, ‘b’, ‘c’])
print(a) print(a)
Output:
First Element: a
First Element: b
First Element: c
Example:
import array as arr
numbers = arr.array('i', [10, 11, 12, 12, 13])
numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
Output:
Enter Base Value:5
Enter Exponent Value6
Result: 15625
sum=0
for i in range (0,len(elements)):
sum=sum+elements[i]
print("Sum of Elements in an Array:",sum)
OUTPUT:
Enter Number of Elements in an Array:5
Enter the Number as:1
Enter the Number as:2
Enter the Number as:3
Enter the Number as:4
Enter the Number as:5
Your Array as: array('i', [1, 2, 3, 4, 5])
Sum of Elements in an Array: 15
Avarage of Elements in an Array: 3.0
OUTPUT:
Enter the Size of the List:8
Please Enter 8 Numbers
Enter Number:19
Enter Number:2
Enter Number:8
Enter Number:25
Enter Number:16
Enter Number:33
Enter Number:1
Enter Number:5
Your List: [19, 2, 8, 25, 16, 33, 1, 5]
Enter the item to be Search:16
Your item is found in the position: 4
Problem Solving and Python Programming
Illustrative Problems: Binary Search
def binarysearch(list,search):
list=[] first=0
size=int(input("Enter the Size of the List:")) last=len(list)-1