0% found this document useful (0 votes)
4 views42 pages

Chapter - 3 Conditional and Iterative Statements

The document provides an overview of control statements in programming, specifically focusing on conditional and looping constructs. It details three types of control statements: decision-making statements, iteration statements (loops), and jump statements, along with their syntax and examples. Additionally, it includes practical programming exercises to reinforce the concepts discussed.

Uploaded by

nakul18209
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)
4 views42 pages

Chapter - 3 Conditional and Iterative Statements

The document provides an overview of control statements in programming, specifically focusing on conditional and looping constructs. It details three types of control statements: decision-making statements, iteration statements (loops), and jump statements, along with their syntax and examples. Additionally, it includes practical programming exercises to reinforce the concepts discussed.

Uploaded by

nakul18209
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/ 42

Conditional And Looping

Constructs

- Nirali Purohit
Control statements are used to control the flow of
execution depending upon the specified
condition/logic

There are three types of control statements.

1. Decision Making Statements


2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)
Decision making statement used to control
the flow of execution of program depending
upon condition.

There are three types of decision making


statement.
1. if statements
2. if-else statements
3. Nested if-else statement
1. if statements
An if statement is a programming conditional
statement that, if proved true, performs a
function or displays information.
1. if statements
Syntax:
if condition:
statement
[statements]
e.g.
noofbooks = 2
if noofbooks == 2:
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
Note:To indicate a block of code in Python, you must indent each line of
the block by the same amount. In above e.g. both print statements are
part of if condition because of both are at same level indented but not
the third print statement.
1. if statements
Using logical operator in if statement
x=1
y=2
if x==1 and y==2:
print(‘condition matching the criteria')

Output :-
condition matching the criteria
2. if-else Statements
If-else statement executes some code if the test
expression is true (nonzero) and some other code if
the test expression is false.
2. if-else Statements
Syntax:
if condition:
statements
else:
statements
e.g.
a=10
if a < 100:
print(‘less than 100')
else:
print(‘more than equal 100')

OUTPUT
less than 100

*Write a program in python to check that entered numer is even or odd


3. Nested if-else statement
The nested if...else statement allows you to check for
multiple test expressions and execute different codes
for more than two conditions.
3. Nested if-else statement
Syntax
if condition:
statements
if condition:
statements Nested if-else
elif condition: statement
statements
else:
statements
E.G.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number") else:
print("Negative number")
OUTPUT
Enter a number: 5 Positive number
* Write python program to find out largest of 3 numbers.
Iteration statements(loop) are used to execute a block
of statements as long as the condition is true.
Loops statements are used when we need to run same
code again and again.
Python Iteration (Loops) statements are of three type :-

1. While Loop

2. For Loop

3. Nested For Loops


1. While Loop
It is used to execute a block of statement as long as a given condition is
true. And when the condition become false, the control will come out of the loop.
The condition is checked every time at the beginning of the loop.
▶ Syntax

▶ while (condition):
▶ statement
[statement]
▶ e.g.

x=1 Output
while (x <= 4): 1
2
print(x) 3
x=x+1 4
while loop with else
e.g.

x=1
while x < 3:
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)

Output
inside while loop value of x is 1
inside while loop value of x is 2
inside else value of x is 3
while Loop: while Loop:
Infinite while Loop Infinite while Loop
e.g. e.g.
x=5 x=5
while x == 5: while True:
print(‘inside loop') print(‘inside loop')

Output Output
Inside loop Inside loop
Inside loop Inside loop
… …
… …
2. For Loop
Syntax
for val in range(<start>,end,<step>):
statements
e.g.
for i in range(3):
print (i, end=“ ”)
Output: 0 1 2
for i in range(1,11,2):
for i in range(3,5): print(I,end=“ ”)
print(i) Output: 1 3 5 7 9
Output
3
4
2. For Loop continue
for i in range(5,3,-1):
print(i)

Output
5
4

range() Function Parameters


start: (Optional) Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in
the sequence.
2. For Loop with sequence like list, tuple or string

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)): # executes 3 times
print ('Current fruit :', fruits[index])

OR

fruits = ['banana', 'apple', 'mango']


for I in fruits:
print ('Current fruit :', I)
2. For Loop continue
For Loop With Else
e.g.
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")

Output
1
2
3
No Break
2. For Loop continue
Nested For Loop
e.g.
for i in range(1,3):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
2. For Loop continue
Factorial of a number
factorial = int(input(‘enter a number’))

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
2. For Loop continue
Compound Interest calculation
n=int(input("Enter the principle amount:"))
rate=int(input("Enter the rate:"))
years=int(input("Enter the number of years:"))

for i in range(years):
n=n+((n*rate)/100)
print(n)
3. Jump Statements

Jump statements are used to transfer


the program's control from one location to another. Means
these are used to alter the flow of a loop like - to skip a
part of a loop or terminate a loop

There are three types of jump statements used in python.


1.break
2.continue
3.pass
1.break
it is used to terminate the loop.
e.g.
for val in "string":
if val == "i":
break
print(val)

print("The end")

Output
s
t
r
The end
2.continue
It is used to skip all the remaining statements
in the loop and move controls back to the top of
the loop.
e.g.
for val in "init":
if val == "i":
continue
print(val)
print("The end")

Output
n
t
The end
3. pass Statement
This statement does nothing. It can be used when a
statement is required syntactically but the program
requires no action.
Use in loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
In function
It makes a controller to pass by without executing any code.
e.g.
def myfun():
pass #if we don’t use pass here then error message will be shown
print(‘my program')

OUTPUT
My program
3. pass Statement
e.g.
for i in 'initial':
if i == 'i':
pass
else:
print(i)

OUTPUT
n
t
a
L
NOTE : continue forces the loop to start at the next iteration
while pass means "there is no code to execute here" and
will continue through the remainder or the loop body.
Find if the given number is prime no
(Hint: Modulo the number from 2 to the number-1, if
divisible it not prime)
Find if the given number is perfect no or not
(Perfect number is number which is equal to the sum of
its positive factors excluding the number itself )
Find factors of a number
(Hint: Modulo the number from 1 to the number+1, if
divisible print it)
Find largest of 3 numbers
Fibonacci up to 10 numbers using range function:
Other ways to print Fibonacci series
(Hint: Using while loop to give end value of series and
for loop for number of elements in the series)
Find factorial of a number
Find if the number is Armstrong number
(Hint: Modulo the number by 10, exponent the result by length of
the number, add to a variable, remove last digit of the number)
Find lcm of two numbers
(Hint: Find the bigger of two numbers, keep dividing both the
numbers with greater+1 till we reach a number that gets divided
successfully by both the numbers)
Find hcf of two numbers
(Hint: Find the smaller of two numbers, keep dividing both the
numbers from 2 till smaller+1 till we reach a number that divides
both the numbers successfully)
Do the following series:

Answer 1:
Answer 2:

Answer 3:
Answer 4:
Create a pattern as follows:

*
**
***
****
*****
Create a pattern as follows:

12345
1234
123
12
1
Create a pattern as follows:

A
AB
ABC
ABCD
ABCDE

You might also like