“if” Statements
“if” statements set a certain condition which can be interpreted as either True or False. The statements following “if” are executed only when the condition is true. The basic form of “if” statements is:
if condition:
statement_1
statement_2
Let’s see an example (example 1).
# example 1x = 3
y = 5if x < y:
print('x is smaller than y')
As x and y are defined as 3 and 4 respectively, and 3 is smaller than 4 (3<4), the condition for “if” statement is True. Thus, the statement following the condition is executed — ‘x is smaller than y’ is printed.
“if, else” Statements
When the “if” condition is False, the statements following “if” are ignored. What if we need to set an alternative statement to be executed if the condition is false?
Answer: use “if, else” statements (see example 2)!
# example 2# set the value of "a".
a = int(input('Write a number: '))# determine the value of "a".
if a == 1:
print("That's right!")
else:
print("That's wrong. Try again!")
When building a program that can determine the value of “a”, you can provide an alternative statement that will be executed if the first condition is false.
“if, elif, else” Statements
You can also use the keyword “elif” when you have to set more than one alternative statement.
# if-elif-else statementsif condition_1:
statement_1
elif condition_2:
statement_2
elif condition_3:
statement_3
elif condition_4:
statement_4
else:
statement_5
Remember: “if” and “else” statements can be used only once, whereas “elif” can be used as many as you wish.
With “if, elif, else” statements, you can set various conditions for your program! Hope you practice these codes by yourselves.
I’ll come back with another Python grammar. See you soon!