In this post, i am giving my information about conditional control statements in python.
In python, there are two types of conditional control statements. They are:
1.if
2.match
Firstly if statement, there are four types of if statements.
1.sinple if
2.if..else
3.if..else ladder
4.nested if
Now, let us discuss about if statement
1.simple if:
If without else is called simple if.
Syntax:
if:
statement:1
statement:2
.
.
statement:n
statement
Example:
Bank Withdrawal form
balance=float(input(“Enter balance:”))
trans_amount=float(input(“Enter amount:”))
b=balance-trans_amount
if trans_amount>=50000
print(“Input PAN details:”)
print(“Balance”,b)
Output:
Enter balance:60000
Enter amount:55000
Input PAN details
Balance=5000
Output:
Enter balance:60000
Enter amount:30000
Balance:30000
2*.if..else:*
it contains two blocks
a.if block b.else block
Syntax:
if:
statement 1
.
.
statement n
else:
statement 2
.
statement n
statement
Example:
ch=input(“Enter a character:”)
if ch in “aeiouAEIOU”
print(“Vowel”)
else:
print(“Consonant”)
Output:
Enter a character: a
Vowel
Enter a character: A
Vowel
Enter a character: b
consonant
3.if..else ladder:
It is used for checking multiple conditions
Syntax:
if:
statement 1
elif:
statement 2
elif:
statement 3
.
.
else:
statement n
Example;
Write a program to print wishes with 24 time format
Good morning
Good Afternoon
Good Evening
Good Night
hours=int(input(“Enter hours in 24 time format:”))
if hours<=12:
print(“Good Morning”)
elif hours>12 and hours<4:
print(“Good Afternoon”)
elif hours>4 and hours<8:
print(“Good Evening”)
else:
print(“Good Night”)
**Output:**
Enter hours:7
Good Morning
Enter hours:2
Good Afternoon
Enter hours:5
Good Evening
Enter hours:10
Good Night
**4.Nested if:**
if within if is called nested if.
**_Syntax:_**
if:
if:
statement 1
else:
statement 2
elif:
if:
statement 3
else:
statement 4
else:
statement 5
Example:
Login Application
user=input(“Enter username:”)
psd=input(“Enter password:”)
if user==”naga”:
if psd==”naga1234″:
print(“Welcome”)
else:
print(“invalid password”)
else:
print(“invalid username”)
Output:
Enter username: naga
Enter password: naga1234
Welcome
Enter username:nara
Enter password:naga1234
invalid username
2.match():
match() statement contains case block and statements
Syntax:
match(value):
case:
statement 1
case:
statement 2
.
.
case_:
statement n
case_ is default in match
Example:
Simple Calculator
a=int(input(“Enter first number:”))
b=int(in[ut(“Enter second number:”))
operator=input(“Enter operator(+,-,,/)”)
match(operator):
case’+’:
print(f’ sum of {a} and {b} is {a+b])
case’-‘:
print(f’ difference of {a] and {b} is {a-b})
case’‘:
print(f’ product of {a} and {b} is {a*b})
case’/’:
print(f’ division of {a} and {b} is {a/b})
case_:
print(“invalid operator”)
Output:
Enter first number:5
Enter second number:9
operator=+
sum of 5+9=14
Enter first number:5
Enter second number:9
Operator=//
invalid operator