Conditional Statements in Python performs different computations or actions depending on conditions.
In python, the following are conditional statements
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the block level code. In Python, indentation is used to declare a block. If two statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All the statements of one block are intended at the same level indentation.
The if statement is used to test a specific condition. If the condition is true, a block of code (if-block) will be executed.
Syntax:if expression:
statement
a = 33
b = 200
if b > a:
print ("b is greater than a")
b is greater than a
The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if expression:
#block of statements
else:
#another block of statements
age = int (input("Enter your age : "))
if age >= 18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
Enter your age: 19
You are eligible to vote!!
The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them.
We can have any number of elif statements in our program depending upon our need. However, using elif is optional.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
marks = int(input("Enter the marks :"))
if marks > 85 and marks <= 100:
print("Congrats! you scored grade A..")
elif marks > 60 and marks <= 85:
print("You scored grade B + ..")
elif marks > 40 and marks <= 60:
print("You scored grade B ..")
elif (marks > 30 and marks <= 40):
print("You scored grade C ..")
else:
print("Sorry you are fail ?")
Enter the marks: 70
You scored grade B +..
a=int(input("Enter a value : "))
b=int(input("Enter b value : "))
c=int(input("Enter c value : "))
if (a>b) and (a>c):
print("Maximum value is :",a)
elif (b>c):
print("Maximum value is :",b)
else:
print("Maximum value is :",c)
Enter a value: 10
Enter b value: 14
Enter c value: 9
Maximum value is: 14