Simple if statement
There are circumstances when your program needs to execute some bit of the code just if a specific condition is valid. Such a bit of the code should be put inside the body of an if statement. The example is equivalent to in the English language: first comes the keyword if, at that point a condition, and afterward a list of statements to execute. The condition is consistently a Boolean expression, that is, its value equivalents either True or False. Here is one case of how the code with a conditional should resemble:
biscuits = 25 if biscuits >= 5: print("It's coffee time!")
Note that the condition closes with a colon and another line begins with a space. Typically, 4 spaces are utilized to assign each level of indentation. A bit of code wherein all lines are on a similar line of indentation is known as a block of code. In Python, just space is utilized to isolate various blocks of code, consequently, just space demonstrates which lines of code should be executed when the if statement is fulfilled, and which ones ought to be executed independently of the if statement. Look at the example:
if biscuits >= 5: print("It's coffee time!") print("What coffee do you prefer?") print("What about some chips?")
There is one pitfall, however. You ought not confuse the comparison operator for equality(==) with the assignment operator(=). Just the previous accommodates an appropriate condition. Attempt to stay away from this regular error in your code.
Nested if statement
Sometimes a condition happens to be excessively complicated for a simple if statement. For this situation, you can utilize nested if statements. The more if statements are nested, the more perplexing your code gets, which is typically not something worth it. In any case, this doesn’t imply that you have to maintain a strategic distance from nested if statements at any cost.
rainbow = "violet, indigo, blue, green, yellow, orange, red" colors = "red, yellow, orange" my_color = "orange" if my_color in rainbow: print("Congrats you selected a rainbow color!") if my_color in colors: print("Oh, by the way, it's a warm color.")
When it comes to nested if statements, proper indentation is crucial, so do not forget to indent each statement that starts with the if keyword.
Simple if-else statement
An if-else statement is another kind of conditional expressions in Python. It differs from an if statement by the presence of the extra keyword else. The block of code that else contains executes when the state of your if statement doesn’t hold (the Boolean worth is False). Since an else statement is an option for an if statement, just one block of code can be executed. Additionally, else doesn’t require any condition:
day = "Thursday" if(day == "Saturday"): print("Lucky you!") else: print("Weekend soon.")
Indentation applies here also.
As you may soon find out, developers do like a wide range of shortcuts. For conditional expressions there’s a trick too – you can compose an if-else expression in one line. This is known as a ternary operator and resembles this:
day = "Saturday" print("It’s a weekend!" if(day == "Saturday") else "It’s a weekday for sure!")
Nested if-else statement
It ought to be referenced, that if-else statements can be nested a similar way as if statements. An extra conditional statement may show up after the if statement as well as after the else statement. Also, remember to indent appropriately:
x = 500 if(x <= 500): print('Eligible') else: if(x == 500): print('x = 500') else: print('x > 1000') print('Not Eligible')
Elif statement is utilized when we need to determine a few conditions in our code. How can it vary from if-else statements? All things considered, it’s straightforward. Here we include the elif keyword for our extra conditions. It is generally utilized with both if and else operators and the syntax resembles like this:
if condition1: statement1 elif condition2: statement2 else: statement3
The condition is followed by a colon, just like with the if-else statements, then statements are placed within the elif body and don’t forget about an indentation, i.e., 4 spaces at the beginning of a new line.
Let’s have a look at an example:
characters = 10000 if characters > 5000: print("That's a too long article!") elif characters > 500: print("That's a too short article!") else: print("Perfect!")
Elif statements varies from else: it represents to another particular alternative while else fits all cases that don’t fall into the condition given in if statement. That is the reason now and then you may experience conditional statements without else:
pet = 'dog' if pet == 'cat': print('Oh, you are a cat lover. Meow!') elif pet == 'dog': print('Oh, you are a dog lover. Woof!')
There can be the as many of elif statements as you need, so your conditions can be exceptionally point by point. Regardless, what number of elif statements you have, the syntax is consistently the same. The main distinction is that we include more elifs:
if condition1: statement1 elif condition2: statement2 elif conditionN: statementN else: statemnetN1
The code inside the else block is executed only if all conditions before it are False. See the following example:
signal = "red" if signal == "green": print("You can go!") elif signal == "yellow": print("Get ready!") elif signal == "red": print("Just wait.") else: print("No such traffic light color!")
Nested elif statements
Elif statements can also be nested, just like if-else statements. We can rewrite our example of traffic lights with nested conditionals:
signal = "green, yellow, red" light = "purple" if light in signal: if light == "green": print("You can go!") elif light == "yellow": print("Get ready!") else: print("Just wait.") else: print("No such traffic light color!")
Let’s consider a complex example and understand once again
Ann watched a TV program about health and learned that it is recommended to sleep at least A hours per day. Oversleeping is also unhealthy and you should not sleep more than B hours. Now, Ann sleeps H hours per day.
Check if Ann’s sleep schedule complies with the requirements of that TV program.
The input format:
The input comprises three strings with variables in the following order: A, B, H.
A is always less than or equal to B.
The output format:
If Ann sleeps less than A hours, output “Deficiency”, if she sleeps more than B hours, output “Excess”.
If H lies between A and B, print “Normal”.
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
Sample Input 3:
Sample Output 3:
name_1 = "deficiency" name_2 = "excess" name_3 = "normal" A = int(input()) B = int(input()) H = int(input()) if H < A: print(name_1.capitalize()) elif H > B: print(name_2.capitalize()) elif A <= H <= B: print(name_3.capitalize())