0% found this document useful (0 votes)
78 views

Conditional Statements

This document discusses conditional statements and iteration in Python. It covers: 1. The if, if-else and if-elif-else conditional statements and provides examples of each. 2. Nested if statements with examples of if statements within the body of other if, elif, or else blocks. 3. Looping statements like the for and while loops for iterative execution. 4. Examples of programs using conditional logic like finding discounts, determining positive/negative numbers, and sorting numbers in ascending order.

Uploaded by

8D Audio Tune
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Conditional Statements

This document discusses conditional statements and iteration in Python. It covers: 1. The if, if-else and if-elif-else conditional statements and provides examples of each. 2. Nested if statements with examples of if statements within the body of other if, elif, or else blocks. 3. Looping statements like the for and while loops for iterative execution. 4. Examples of programs using conditional logic like finding discounts, determining positive/negative numbers, and sorting numbers in ascending order.

Uploaded by

8D Audio Tune
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Conditional Statements, Iteration

• Program to print the difference of two numbers.

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of",num1,"and",num2,"is",diff)
• Output:
• Enter first number 5
• Enter second number 7
• The difference of 5 and 7 is -2
Program to print the positive difference of two numbers.
Conditional Statements
The if statement is the conditional
statement in Python. There are 3
forms of if statement:
1. Simple if statement
2. The if..else statement
3. The If..elif..else statement
Simple if statement
• The if statement • Syntax The header of if
statement, colon
tests a condition & if <condition>: (:) at the end
in case the condition statement
is True, it carries out Body
[statements] of if
some instructions
and does nothing in • e.g.
case the condition is if amount>1000:
False. disc = amount * .10
Example of if statement
• Write a program to find discount (10%) if amount is more than
1000.
Program to find discount (10%) if amount is more than 1000.
Price = float(input("Enter Price of the item : "))
Qty = float(input("Enter the Qty : "))
Amt = Price* Qty
print("Amount :",Amt)
if Amt >1000: Body of if statement
disc=Amt*.10 (will be executed incase condition is true)
print("Discount is :",disc)
Output
Enter Price of the item : 500
Enter the Qty : 5
Amount : 2500.0
Discount is : 250.0
Enter Price of the item : 100
Enter the Qty ?2
Amount : 200.0
The if-else statement
• The if - else statement • Syntax
tests a condition and if <condition> :
in case the condition statement Block 1
[statements]
is True, it carries out else :
statements indented statement
below if and in case [statements] Block 2

the condition is False, • e.g.


it carries out if amount>1000:
statement below else. disc = amount * 0.10
else:
disc = amount * 0.05
Example of if-else statement
• Prog to find discount (10%) if amount is more than 1000,
otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000 :
disc = Amt * .10 block 1
print(“Discount :”, disc) (will be executed incase condition is true)

else :
disc = Amt * .05 block 2
print(“Discount :”, disc) (will be executed incase condition is False)
• Program to print the positive difference of
two numbers.
• num1 = int(input("Enter first number: "))
• num2 = int(input("Enter second number: "))
• if num1 > num2:
• diff = num1 - num2
• else:
• diff = num2 - num1
• print("The difference
of",num1,"and",num2,"is",diff)
• Output:
• Enter first number: 5
• Enter second number: 6
• The difference of 5 and 6 is 1
Write a program in Python to check
whether the given number is Odd
or Even by using if else statement
Answer
num=int(input(“Enter a Number”))
If(num%2==0):
print(“The Given number is Even”)
else:
print(“The Given Number is Odd”)
The if..elif statement
• The if - elif statement has • Syntax
multiple test conditions and if <condition1> :
statement
in case the condition1 is Block 1
[statements]
True, it executes statements elif <condition2> :
in block1, and in case the statement
condition1 is False, it moves [statements] Block 2
to condition2, and in case elif <condition3> :
the condition2 is True, statement
[statements] Block 3
executes statements in
:
block2, so on. In case none :
of the given conditions is else :
true, then it executes the statement
statements under else block [statements]
Example of if-elif statement
• Program to find discount (20%) if amount>3000, disc(10%) if
Amount <=3000 and >1000, otherwise (5%).
Price = float (input(“Enter Item Price : ” ))
Qty = float (input(“Enter the Quantity : ” ))
Amt = Price* Qty
print(“ The purchased Amount = ” , Amt)
if Amt >3000 :
disc = Amt * .20 block 1
print(“Discount :”, disc) (will be executed incase condition 1 is true)
elif Amt>1000 and Amt<= 3000:
disc = Amt * .10 block 2
print(“Discount :”, disc) (will be executed incase condition2 is True)
else :
block 3
disc = Amt * .05
(will be executed incase both the
print(“Discount :”, disc)
condition1 &conditon2 are False)
Write a program to create a simple
calculator performing only four basic
operations.
#Program to create a four function calculator
result = 0
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter any one of the operator (+,-,*,/): ")
if op == "+":
result = val1 + val2
elif op == "-":
if val1 > val2:
result = val1 - val2
else:
result = val2 - val1
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Error! Division by zero is not allowed. Program terminated")
else:
result = val1/val2
else:
print("Wrong input, program terminated")

print("The result is ",result)


Nested if statement
• A nested if is an if statement that has
another if statement in its if’s body or in
elif's body or in its else’s body.
Model:1 ( if inside if’s body)
If<conditional expression>:
If<conditional expression>:
statement(s)
else:
statement(s)
elif<conditional expression>:
statement(s)
else:
statement(s)
Model:2 ( if inside elif’s body)
If<conditional expression>:
statement(s)
elif<conditional expression>:
If<conditional expression>:
statement(s)
else:
statement(s)
else:
statement(s)
Model:3 ( if inside else’s body)
If<conditional expression>:
statement(s)
elif<conditional expression>:
statement(s)
else:
If<conditional expression>:
statement(s)
else:
statement(s)
Model:4 ( if inside if’s as well as else’s or elif’s body )
If<conditional expression>:
If<conditional expression>:
statement(s)
else:
statement(s)
elif<conditional expression>:
If<conditional expression>:
statement(s)
else:
statement(s)
else:
If<conditional expression>:
statement(s)
else:
statement(s)
Example of Nested if statement
• Program to find Largest of Three Numbers (X,Y,Z)
X = int(input("Enter Num1 : " ))
Y = int(input("Enter Num2 : " ))
Z = int(input("Enter Num3 : "))

if X > Y :
if X > Z: 10,4 , 9
Largest = X
else:
Largest = Z
else:
if Y > Z:
Largest = Y
else:
Largest = Z
print("Largest Number :",Largest)
Write Program that read three integer numbers and
print them in ascending order by using Nested if
statement.
else:
x=int(input(“Enter the first number”))
If x<y:
y=int(input(“Enter the first number”))
min,mid,max =z,x,y
z=int(input(“Enter the first number”))
min=mid=max=None else:
If x<y and x<z min,mid,max =z,y,x
if y<z: Print(“ The givern numbers in
min,mid,max =x,y,z Ascending Order”,
else: min,mid,max)
min,mid,max =x,z,y
elif y<x and y<z:
if x<z
min,mid,max =y,x,z
else
min,mid,max = y,z,x
Assignments
• WAP to input a Year and check whether it is a Leap year by using
if else statement.
• WAP to input a number check whether it is Positive or Negative
or ZERO by using elif statement.
• Write a Program to get 5 subject Marks of a students, and find
the grade as per following Percentage criterion: if Percentage
>=90 grade is “A” if Percentage between 75-89 grade is “B” if
Percentage between 60-74 grade is “C” and Below 60
Percentage grade is “D” by using if..elif statement.
What is leap year

• a year that is evenly divisible by 100 ,400 is a leap


year.
For this reason, the following years are not leap
years:
• 1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600
This is because they are evenly divisible by 100 but
not by 400.
The following years are leap years: 1600, 2000, 2400
• This is because they are evenly divisible by both
100 and 400.
# Check whether a number is positive, negative, or
zero.
number = int(input("Enter a number: "))
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
ITERATION /LOOPING
• The Iteration statements allow a set of instructions to be
performed repeatedly a certain condition is fulfilled. The
Iteration statements are called loops or looping
statements.
• Python provides two types of looping statement
a) for loop
b) while loop

• for loop is called counting loop


• while loop- is called conditional loop
For loop
The for Loop
List or a String
• Syntax : How many times
for <Var> in <Sequence> :
Statements to repeat
Program to print the characters in the string
“PYTHON” using for loop.

for letter in 'PYTHON':


print(letter)
Output:
P
Y
T
H
O
N
#Print the given sequence of numbers using for loop
count = [10,20,30,40,50]
for num in count:
print(num)
Output:
10
20
30
40
50
Program to print even numbers in a given sequence using for
loop.
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')
Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number
Range() Function

The range() is a built-in function in Python.


Syntax of range() function is:
range([start], stop[, step])

It is used to create a list containing a sequence


of integers from the given start value up to stop
value (excluding stop value), with a difference
of the given step value
The range() function
• range( 1 , n): 1) range( 1 , 7): will produce
will produce a list having 1, 2, 3, 4, 5, 6.
values starting from 1,2,3… 2) range( 1 , 9, 2): will produce
upto n-1. 1, 3, 5, 7.
The default step size is 1 3) range( 5, 1, -1): will produce
• range( 1 , n, 2): 5, 4, 3, 2.
will produce a list having 3) range(5): will produce
values starting from 1,3,5…
upto n-1. 0,1,2,3,4.
The step size is 2 default start value is 0
Example
#start and step not specified
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#default step value is 1
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
#step value is -1. Hence, decreasing
#sequence is generated
>>> list(range(0, -9, -1) )
[0, -1, -2, -3, -4, -5, -6, -7, -8]
Range function() with for Loop
Starting Ending Step
• Syntax : value value value

for <Var> in range (val1, val2, Val3):


Statements to be repeated
for loop implementation
Sum=0 Sum=0
for i in range(1, 11): For i in range(10, 1, -2):
print(i) print(i)
Sum=Sum + i Sum=Sum + i
print(“Sum of Series”, Sum) print(“Sum of Series”, Sum)
OUTPUT: OUTPUT:
1 10
2 8
: :
10 2
Sum of Series: 55 Sum of Series: 30
Write a program to check the given
number is PRIME or NOT by using
for loop:
Prime numbers

• In math, prime numbers are whole numbers greater


than 1, that have only two factors –> 1 and the
number itself.
• Prime numbers are divisible only by the number 1
or itself.

• For example, 2, 3, 5, 7 and 11 are the first few prime


numbers.
Prog to check the given number is PRIME or
NOT by using for loop:
num= int(input(“Enter Num?”))
for i in range(2, num//2+1):
if num%i == 0:
print(“It is Prime No.”)
break
else:
print(“It is Not a Prime No.”)

Note: the else clause of a loop will be


executed only when the loop
terminates normally (not when
break statement terminates the
loop)
// -- floor division
Nested for Loop
for i in range ( 1, 6 ):
print( )
for j in range (1, i + 1):
print(“@”, end=“ ”)

# end = “ ” appends space instead of newline.

Will produce following output


@
@@
@@@
@@@@
@@@@@
WHILE LOOP
• The while loop statement executes a block of code
repeatedly as long as the control condition of the
loop is true.
• When this condition becomes false, the statements
in the body of loop are not executed and the
control is transferred to the statement immediately
following the body of while loop.
• If the condition of the while loop is initially false,
the body is not executed even once.
The while Loop syntax
• It is a conditional loop, which repeats the statements with in itself as
long as condition is true.
• The general form of while loop is:
while <condition> :
Statement while loop body
[Statements] (these statements repeated until
condition becomes false)
Example 1
counter=1
while counter<=5:
print ("welcome")
counter=counter+1
Output
welcome
welcome
welcome
welcome
welcome
• #Print first 5 natural numbers using while loop

count = 1
while count <= 5:
print(count)
count += 1

Output:
1
2
3
4
5
Write a program to find the Sum of series by using
while loop
Example: OUTPUT
k = 1, sum=0 1
while k <= 4 : 2
print (k) 3
sum=sum + k 4
print(“Sum of series:”, sum) Sum of series: 10
Program to calculate the factorial of a number by using while loop

number=int(input("Enter a Number : ")) 5


fact=1
counter=1
while counter<=number:
fact=fact*counter
counter=counter+1
print("The factorial of ",number,"is",fact)
What is factorial
The factorial function (symbol: !) says to multiply all
whole numbers from our chosen number down to 1.
Examples:
4! = 4 × 3 × 2 × 1 = 24
So the rule is:
n! = n × (n−1)!
• Which says "the factorial of any number is that
number times the factorial of (that number minus
1)"
So
• 10! = 10 × 9!, ... and
• 125! = 125 × 124!, etc.
#Find the factors of a number using while loop

num = int(input("Enter a number to find its factor: "))


print (1, end=' ') #1 is a factor of every number
factor = 2
while factor <= num/2 :
if num % factor == 0:
#the optional parameter end of print function specifies the
delimeter
#blank space(' ') to print next value on same line
print(factor, end=' ')
factor += 1
print (num, end=' ') #every number is a factor of itself
Output:
Enter a number to find its factors : 6
1236

You might also like