In this article we will see how to use if else condition in python(python3). In python everything is indeneted esepcially conditions and loops with spaces or tabs. And these spaces and tabs are uniform accross the program. If the number of spaces/tabs is violated it is a syntax error.
So this is a simple example of if else block. Note the indentation and colon. Below you can see more examples.
If Elif Else:
Now if else statement with many examples:
You can find the all the above examples in the below code:
# this program is for indentation and if else
# here i am declaring two variables
a = 5
b = 6
print("Value of a is %d, b is %d" %(a, b))
#change the above variables with many possibulites and see what it will print
#now lets test if a is greater or b is greater
#example1
print("Example1")
if( a > b):
print("a is greater than b")
#here you can write as many statements as you want
else:
print("b is greater than a")
#here you can write as many statements as you want
#in the above code block if a is greater than b then if condition will be true and the statement underneath will execute
#else statemnets under else will be executed
#now what if there are many if conditions for ex: a>b, a<b, a==b etc
#example2
print("Example2")
if ( a > b):
print("a is greater than b")
#here you can write as many statements as you want
elif (a < b):
print("b is greater than a")
#here you can write as many statements as you want
else:
print(" both are equal")
#here you can write as many statements as you want
#example3
print("Example3")
if ( a > b):
print("a is greater than b")
#here you can write as many statements as you want
elif (a < b):
print("b is greater than a")
elif(a == b):
print("a and b are equal")
#here you can write as many statements as you want
else:
print("all the conditions failed")
#here you can write as many statements as you want
#example4 more complex if else statements
name = 'Manisha'
salary = 10000 #change this value and play with it
print("Example4")
if(salary > 50000):
print("Salary of %s is %d" %(name,salary))
print("So she will buy a car")
print("She will buy a house")
print("She will not give parties")
else:
print("Salary of %s is %d" %(name,salary))
print("She will try for new job")
print("She will not give parties")