Python Conditional Execution

if Statement:

When we write programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. The simplest form is the if statement. The boolean expression after the if statement is called the condition. We end the if statement with a colon character (:) and the line(s) after the if statement are indented. Check the following example.

x=10
if x > 0 : print('x is positive')

Alternative execution: if-else Statement

A second form of the if statement is alternative execution.,In this case there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

x=11
if x%2 == 0 :
    print('x is even')
else :
    print('x is odd')


Try it Yourself

Chained conditionals: if…elif…else

Sometimes there are more than two possibilities. Therefore you need more than two branches. One way to express a computation like that is a chained conditional like below:

a=10
b=20
if a < b:
    print('a is less than b')
elif a > b:
    print('a is greater than b')
else:
    print('a and b are equal')

There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

a=10
b=20
if a < b:
    print('a is less than b')
elif a > b:
    print('a is greater than b')
elif a==b:
    print('a and b are equal')
Try it Yourself

Nested conditionals:

One conditional can also be nested within another. You could have written the three-branch example like this:

a=20
b=10
if a == b: print('a and b are equal') else: if a < b: print('a is less than b') else: print('a is greater than b')
Try it Yourself

Catching exceptions using try and except:

There is a conditional execution structure built into Python to handle certain types of expected and unexpected errors called “try / except”. The idea of try and except is that you know that some sequence of instruction(s) may have a problem and you want to add some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error. Lets consider the following the example:

i=int(input("Enter a number\n"))
print(i)

For the above code if you don’t enter any number just hit enter without giving any input then you will get an error like this:

Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
i=int(input(“Enter a number\n”))
ValueError: invalid literal for int() with base 10: ”

Python starts by executing the sequence of statements in the try block. If all goes well, it skips the except block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block.

try:
    i=int(input("Enter a number\n"))    
    print(i) 
except: 
    print("Please enter a number")

Output:

>>> 
Enter a number

Please enter a number
>>>

Comments

Functions