Python Control Flow
if…elif..else Statement
- We use if statement to run code if a certain condition is true.
- To add more conditions, we use
elifstatement. - We can add a default code with
elsestatement.
if condition:
# do thing1
elif condition2:
# do thing2
else:
# do thing3
For example
a = 50
b = 35
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Operations
Relational operators
We can create boolean expressions using relational operators:
- Equal: ==
- Not equal: !=
- Greater than: >
- Less than: <
- Greater than or equal to: >=
- Less than or equal to: <=
Boolean operators: and, or, and not.
- The
andoperator takes two arguments, and evaluates as True if both of its arguments are True. Otherwise, it evaluates to False. - The
oroperator also takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if both arguments are False. - not only takes one argument, and inverts it. The result of not True is False, and not False goes to True.
Try and Except Statements
We can use try and except statements to check for possible errors that a user might encounter.
try:
# some statement
except ErrorName:
# some statement
finally:
print("The 'try except' is finished")
- The try block lets you test a block of code for errors.
- The except block lets you handle the error.
- The finally block lets you execute code, regardless of the result of the try- and except blocks.
Explanation
First, the statement under try will be executed. If there’s an error such as NameError or a ValueError, and try statement will terminate and the except statement will execute.
def divides(a,b):
try:
result = a / b
print (result)
except ZeroDivisionError:
print ("Can't divide by zero!")