If Else in Python

If else in Python


 The general syntax of an if else statement in Python is 


if  condition:

    Statements if true

else:

    Statements if  false

Here is the simplest example

    This will check print if or else depending on the bool value given to the if else.

if True:
print("If")
else:
print("Else")

Output

IF

What happens if I change True to false?

if False:
print("If")
else:
print("Else")

Output
Else

The if and else are both optional. 

Thus I can write it this way

if True:
print("If")
Output
If

if False:
pass
else:
print("Else")
Output

Else




Example:

Program to find the max of 2 numbers


a=1
b=2
if a>=b:
    max=a
else:
    max=b

print(max)


Grouping in Python is by indent and not by curly braces {} as in languages derived from C. What are the "conditions"? Conditions are expressions that have True or False as their answer. What is True and False?
Read the previous post at bool class


Python has a  ternary operator as well. The syntax is

(value if true) if true else (value if false)

So, to find the maximum of 2 variables.




a=1
b=5
max=a if a>=b else b
print(max)


5

Ternary operators can be nested as well. Let us try an example where we find the maximum of three variables a,b and c.
The first step would be initializing the three variables.

a=3
b=2
a=1
Now, let us find the max between a and b. The condition to evaluate will be (a>=b).

In simple pseudo code.
If a>=b then max=a otherwise max=b

max=a if a>=b else b











Post a Comment

0 Comments