If Else In Python

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: 

 

if-else-flowchart


 Important to underline:

  • after "condition" there is colon i.e. ":" character 
  • "do something..." which follow after condition is right indented
  • what is after else, means "do something else..." is right intended
  • indentation is a must and it means all instructions with the same indentation will be executed as part of the condition accomplished or as part of else block


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:

  

if-else-example