Very often in life something is happening depending by a condition and as programs solve something from life, in programs we need to use conditional statement.
Basic python conditional statement is if/else and general syntax is:
if condition:
do something i.e. execute it when condition is true
else:
do something else i.e. execut when condition is false
Let’s see a simple example:
price=12
if price >= 10:
discount=0.2
else:
discount=0.15
print(f"My discount is {discount}")
To understand more any if/else can be represented in a diagram or a logic flow chart, for our case:
Important to underline:
Further about our example:
price=12
if price >= 10:
discount=0.2
print("discount is higher")
else:
discount=0.15
print("discount is smaller")
print(f"My discount is {discount}")
After if condition we can have one or many instructions, also after else we can have one or many instructions, and in both cases those need to be identical indented, which means for python that those will be executed together
And the code executed is: