Conditional statements allows you to make decisions on what part of your program would execute based on certain criteria.
The criteria is specified in form of an expression that evaluates to either True or False. So you write code that would execute depending on either the result is True or False.
The general form of Python conditional statement is given in Figure 1.0.
By default, non-zero values or non-null values in Python have a value of True while zero or null values have a value of False
The following three conditional statement construct can be implemented in Python
If Statements: This is a statement (condition) followed by a block of one or more statements which are executed if the condition evaluates to true. If the condition if false, the block is ignored and execution continues with statements after the block. Example of If statement is given in the code below.
a = 20 b = 40 if a == b: print("a is equal to b")
if … else Statement: This is like the if statement, but provides an optional else block which must be executed if the condition evaluates to false. This is shown in the code below
a = 20 b = 40 if a == b: print("a is equal to b") else: print("a is not equal to b")
elif Statement: This is a situation when more than one condition is to be evaluated. In this case, if the first condition evaluates to False, the elif provides a second condition to check. The structure of the elif statment is given below
a = 20 b = 40 if a == b: print("a is equal to b") elif a > b: print("a is greater than b") else: print("a is less than b")
Nested If Statements: This is a situation where a second condition have to be evaluated if the first condition is True. In this case, the second if statement is nested inside the first if statement. This is shown below
a = int(input("Please enter a number")) if a < 100: if > 50: print("a is less than 100 but greater than 50")
Try out the code below the is used to assign a grade A, B, C, D, E to a score. You can also watch the video below to see how it is explained and implemented in PyCharm
a = input("Enter a number") a = float(a) if a>= 70 and a <= 100: print("A") elif a >= 60 and a <=69: print("B") elif a >= 50 and a<=59: print("C") elif a > 45 and a < 59 print("D")
Watch the Video