Py Section B Part 1
Py Section B Part 1
Control Statements
• Control Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true
or false. Conditional or Control statements are handled by IF
statements in Python.
Control Statements
•Python supports the following conditional statements:
•if statements
•if else statements
•elif statements
•nested if…elif…else statements
1. Simple If statement
• In order to write useful programs, we almost always need the ability to check conditions and change
the behavior of the program accordingly. Conditional statements give us this ability. The simplest
form is the if statement:
if x > 0 :
print('x is positive’)
• The boolean expression after the if statement is called the condition. We end the if statement with a
colon character (:) and the line(s) after the if statement are indented.
1. Simple If statement
1. Simple If statement
• If the logical condition is true, then the indented statement gets executed. If
the logical condition is false, the indented statement is skipped.
• The statement consists of a header line that ends with the colon character
(:) followed by an indented block. Statements like this are called compound
statements because they stretch across more than one line.
• There is no limit on the number of statements that can appear in the body,
but there must be at least one. Occasionally, it is useful to have a body
with no statements (usually as a place holder for code you haven’t written
yet). In that case, you can use the pass statement, which does nothing.
WAP to check whether a number is positive
x=8
if(x>0):
print("Number entered is positive",x)
Output:
Number entered is positive 8
WAP to check whether a number is positive
x=-10
if(x>0):
print("Number is Positive")
print("I will always execute")
Number is Positive
I will always execute
WAP to check whether a Letter is Vowel
vowels = ['A', 'E', 'I', 'O', 'U','a','e','i','o','u']
letter = input("Enter a vowel: ")
if letter in vowels:
print("Vowel")
Output:
Enter a vowel: e
Vowel
WAP to check the item in restaurant
stock=['pizza','hotdog','barbeque','hamburger']
order = input("Please enter your order: ")
if order in stock:
print("Thank you. Your order will be served in 5 minutes.")
Let us take an example of C++ code and Python Code on next page to
make it more clearer.
Multiple Statements in if.
Program to use multiple lines in an if statement
if test expression:
statement(s)
else:
statement(s)
2. If-else statement
WAP to check whether a number is positive or negative.
if(x>0):
print("Number is positive " , x)
else:
print("Number is negative" ,x )
Output:
Enter a number to check whether it is +ve or -ve -90
Number is negative -90
2. If-else statement
WAP to check whether a number is Even or Odd.
if(x%2==0):
print("Number is Even number " , x)
else:
print("Number is Odd one" ,x )
Output:
Enter a number to check whether it is Even or odd 66
Number is Even number 66
2. If-else statement
WAP to find greatest between 2 numbers
a = 200
b = 33
if (b > a):
print("b is greater than a")
else:
print("b is not greater than a")
2. If-else statement
• To illustrate, here’s a program which uses the ‘if..else’ structure:
stock=['pizza','hotdog','barbeque','hamburger']
order = input("Please enter your order: ")
if order in stock:
print("Thank you. Your order will be served in 5 minutes.")
else
print(“Item is not present in our stock")
3. if…elif…else statements
• An elif (else if) statement can be used when there is a need to
check or evaluate multiple expressions.
if expression:
if block
elif expression:
elif block
else:
else block
3. if…elif…else statements
•To illustrate, here is a simple program with an
if…elif..else structure:
if (x < y):
print('x is less than y')
elif (x > y):
print('x is greater than y')
else:
print('x and y are equal’)
• '''In this program, we check if the number is positive or negative or zero and display an appropriate
message'''
num = 3.4
if (num > 0):
print("Positive number")
elif (num == 0):
print("Zero")
else:
print("Negative number")
3. if…elif…else statements
• #WAP to check whether an angle is acute, obtuse, right angled or above 180.
print(“Yourname”)
print(“Yourname”)
print(“Yourname”)
print(“Yourname”)
print(“Yourname”)
So if you want to write the same thing 1000 times of times then it is not easy to copy paste again and again so for solving this
we have got loops. So we are having 2 types of loops in python.
1) while loop
2) for loop
While loop
while as you know will repeat something but you need to give a condition for
how many times the loop executes. So in case of while we will initialize a value
and put a condition with a while loop then some increment or decrement should
be taken in a loop .
while test_expression:
Body of while
While loop
In the while loop, test expression is checked first. The body of the
loop is entered only if the test_expression evaluates to True. After one
iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
i=1
while(i<=10):
print(i)
i=i+1
Now if you want the same output in a single line. Then put end= to the last of the print line shown below:
# WAP to print 1 to 10
i=1
while(i<=10):
print(i , end=" ")
i=i+1
# WAP to print 10 to 1
i=10
while(i>=1):
print(i , end=" ")
i=i-1
# Program to add natural numbers up to n
# sum = 1+2+3+...+n
n = int(input("Enter n: "))
sum = 0
i=1
rev=0;
while(num>0):
Enter a number you want to reverse
temp=num%10 213
rev=(rev*10)+temp
312
num=num//10
print(rev)
# WAP to check whether a number is Palindrome or not.
num=int(input("Enter a number you want to reverse"))
rev=0
n=num
while(num>0):
temp=num%10
rev=(rev*10)+temp
Enter a number you want to reverse
213
num=num//10
if(n==rev):
Not Palindrome
print("Number is Palindrome ")
else:
•In Python, there is not C like syntax for(i=0; i<n; i++) but you
use for in n.
for i in range(10):
Output:
0123456789
# printing first 20 whole number
for i in range(20):
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# printing first 20 whole number
for i in range(20):
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
2. range(start , stop) takes two argument
When user call range() with two arguments, user get to decide not only where the series of
numbers stops but also where it starts, so user don’t have to start at 0 all the time. User
can use range() to generate a series of numbers from X to Y using a range(X, Y). For
Example -arguments
Program 1
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Program 2
Output:
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
range(start, stop, step)
•When user call range() with three arguments, user can choose not only
where the series of numbers will start and stop but also how big the
difference will be between one number and the next. If user don’t
1.
range(start, stop, step)
# using range to print number divisible by 3
print()
Output :
0 3 6 9 12 15 18 21 24 27
Incrementing with range using positive step :
• If user want to increment, then user need step to be a positive number. For
example:
# incremented by 4 # incremented by 3
# incremented by 2
for i in range(2, 25, 2): for i in range(0, 30, 4): for i in range(15, 25, 3):
print(i, end =" ") print(i, end =" ") print(i, end =" ")
2 4 6 8 10 12 14 16 18 20 22 24 0 4 8 12 16 20 24 28 15 18 21 24
Decrementing with range using negative step :
• If user want to increment, then user need step to be a positive number. For
example:
# incremented by -2
# incremented by -4
for i in range(25, 2, -2): # incremented by -3
for i in range(30, 1, -4):
print(i, end =" ") for i in range(25, -6, -3):
print(i, end =" ")
print() print(i, end =" ")
print()
25 23 21 19 17 15 13 11 9 7 5 3 30 26 22 18 14 10 6 2 25 22 19 16 13 10 7 4 1 -2 -5
Using float Numbers in Python range() :
• Python range() function doesn’t support the float numbers. i.e. user
cannot use floating-point or non-integer number in any of its
argument. User can use only integer numbers.
for i in range(3.3):
print(i)
sum = 0
Output:
15
Program to Print all Numbers in a Range Divisible by a Given
Number
Case 1:
Enter lower range limit:1
Enter upper range limit:50 Case 2:
Enter the number to be divided by:5 Enter lower range limit:50
5 Enter upper range limit:100
10 Enter the number to be divided
15
by:7
20
56
25
30 63
35 70
40 77
45 84
50 91
98
Assignment
Syntax
while expression:
while expression:
statement(s)
statement(s)
How works nested while loop
• In the nested-while loop in Python, Two type of while statements are available:
• Outer while loop
• Inner while loop
• Initially, Outer loop test expression is evaluated only once.
• When its return true, the flow of control jumps to the inner while loop. the
inner while loop executes to completion. However, when the test
expression is false, the flow of control comes out of inner while loop and
executes again from the outer while loop only once. This flow of
control persists until test expression of the outer loop is false.
• Thereafter, if test expression of the outer loop is false, the flow of
control skips the execution and goes to rest.
Program 1
i=1
while (i<=3) :
print(i,"Outer loop is executed only once")
j=1
while (j<=3):
print(j,"Inner loop is executed until to completion")
j+=1
i+=1;
Program 1
Output:
(1, 'Outer loop is executed only once')
(1, 'Inner loop is executed until to completion')
(2, 'Inner loop is executed until to completion')
(3, 'Inner loop is executed until to completion')
(2, 'Outer loop is executed only once')
(1, 'Inner loop is executed until to completion')
(2, 'Inner loop is executed until to completion')
(3, 'Inner loop is executed until to completion')
(3, 'Outer loop is executed only once')
(1, 'Inner loop is executed until to completion')
(2, 'Inner loop is executed until to completion')
(3, 'Inner loop is executed until to completion')
Display multiplication table using nested
while in Python language
i=2
while i<=2:
j=1
while j<=10:
print(i*j)
j+=1
print ()
Display multiplication table using nested
while in Python language
Output:
2
4
6
8
10
12
14
16
18
20
Display multiplication table using nested
while in Python language
i=2
while i<=2:
j=1
while j<=10:
print (i,"*",j,'=',i*j)
j+=1
print ("\n")
Display multiplication table using nested
while in Python language
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
If in while loop
If can be used in while
i=1
while(i<=10):
if(i==5):
print("This has to be printed")
print(i)
i+=1
If in while loop
1
2
3
4
This has to be printed
5
6
7
8
9
10
While loop with else
• while loops can also have an optional else block.
• The else part is executed if the condition in the while loop evaluates to False.
• The while loop can be terminated with a break statement. In such cases, the
else part is ignored. Hence, a while loop's else part runs if no break occurs and
the condition is false.
While loop with else
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
While loop with else
Output:
Inside loop
Inside loop
Inside loop
Inside else
While loop with else
counter = 5
Inside else
While loop with else
n=5
while n > 0:
n=n-1
if n == 2:
break
print(n)
else:
print("Loop is finished")
While loop with else
Output:
4
3
While loop with else
n=5
while n > 0:
n=n-1
if n == 2:
continue
print(n)
else:
print("Loop is finished")
While loop with else
4
3
1
0
Loop is finished
One-Line while Loops
n=5
while n > 0: n -= 1; print(n)
Output:
4
3
2
1
0
WAP to print factorial of a number
n=int(input("Enter a number"))
fact=1
while(n>0):
fact=fact*n;
n-=1;
print(fact)
#Python program to generate
Fibonacci series until 'n' value
n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b
#Python program to generate
Fibonacci series until 'n' value
Output:
Enter the value of 'n': 5
Fibonacci Series: 0 1 1 2 3
Assignment
1. Count occurrence of a digit 5 in a given integer number
input by the user
• Break statement
• Continue statement
• Pass statement
Break statement
• General syntax
break
Break statement
• General syntax
break
Break statement
Break
for val in "string":
if val == "i":
break
print(val)
print("The end")
Break
s
t
r
The end
As the name suggests the continue statement forces the loop to continue
or execute the next iteration. When the continue statement is executed in
the loop, the code inside the loop following the continue statement will
be skipped and the next iteration of the loop will begin.
General Syntax is:
continue
Python continue statement
Program to show the use of continue
statement inside loops
print("The end")
Program to show the use of continue
statement inside loops
s
t
r
n
g
The end
This program is same as the above example except the break statement has been
replaced with continue.
We continue with the loop, if the string is i, not executing the rest of the block.
Hence, we see in our output that all the letters except i gets printed.
# WAP to print number not divisible by 3
and 5
num=50
i=1
while(i<num):
i+=1
if(i%3 == 0 or i%5 ==0):
continue
print(i,end=" ")
# WAP to print number not divisible by 3
and 5
Output:
2 4 7 8 11 13 14 16 17 19 22 23 26 28 29 31 32 34 37 38 41 43 44
46 47 49
The pass Statement:
• The pass statement in Python is used when a statement is required
syntactically but you do not want to execute it right now. In future you
might want to use it.
if(condition):
pass
else:
Statements
In above syntax if the condition of if is true then we don’t want to do anything so pass
has been written.
The pass Statement:
for letter in 'Python':
if letter == 'h':
pass
print("Good bye!")
The pass Statement:
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
The pass Statement:
# Program to print only odd number of values
for i in range(1,51):
if(i%2==0):
pass
else:
print(i,end=" ")
The pass Statement:
Output:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
The pass Statement:
The preceding code does not execute any statement or code if the value
of letter is 'h'. The pass statement is helpful when you have created a
code block but it is no longer required.
You can then remove the statements inside the block but let the block
remain with a pass statement so that it doesn't interfere with other parts
of the code.