Python Tutorial - Conditional Statement
In this blog, we are digging into condition statements in python. The condition statement in python is not as complex as it is in other languages. Before entering into the topic, let us see some key points,
- Equals: a==b
- Not Equals: a!=b
- Less than: a<b
- Less than or equal to a<=b
- Greater than: a>b
- Greater than or equal to a>=b
if statement:
Syntax:
a = 3
b = 5
c = a+b
print(c)
if c>4:
print("Gaming")
else:
print("Bug")
Output:
8
Gaming
Explanation:
We are storing values in two variables a and b. In line 3, we are adding a and b to get c. Inline 4, we are printing the c. Now coming to the if statement, we are making a condition that if c>4, it should print "Gaming" or else it should print "Bug". The result is 8 and it printed "Gaming".
Note: ':' should be added next to if or any condition statement.
elif:
This is used if we have more than one condition.
Syntax:
a = 3
b = 5
c = a+b
print(c)
if c>8:
print("Gaming")
elif c==8:
print("Gaming Bug")
else:
print("Bug")
Output:
8
Gaming Bug
Explanation:
Same as if statement. The change is we are having more than one condition. So we added one more statement known as elif.
Nested if:
If we have an if condition inside an if condition, then it is known as Nested if statement.
Syntax:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Explanation:
This is defined as if the value satisfies two, it will print them both. For example x=41, it satisfies both if condition, hence both are printed. Nested if it is used in these conditions.
And:
We can use and operator to combine two conditions.
Syntax:
a = 3
b = 5
c = a+b
print(c)
if c>5 and c<7:
print("Gaming")
else:
print("Bug")
Output:
8
Bug
Explanation:
In this, if condition, it should satisfy two conditions to print the if conditional statement. Else it will print the else statement.
Or:
a = 5
b = 5
c = 5
if a>b or a>c:
print("Gaming")
else:
print("Gaming Bug")
Output:
Gaming Bug
Explanation:
In this program, in if conditional statement should satisfy either one of the statements to print or it will print the else conditional statement.
Indentation is very important in python. So space should be correctly given. If you do not understand what is indentation is, kindly google it. It will be better if you learn that on your own.
To get updates kindly subscribe to our blog. Share this to the maximum.
Comments
Post a Comment