In this session of flow control and looping in python we will learn about working of loop and controlling the flow of statements, there has always been a series of statements faithfully executed by Python in exact top-down order. What if you wanted to change the flow of how it works?
- For example, you want the program to take some decisions and do different things depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?
According to the above situation it can be categorized into three parts.
- Decision Making and branching (Conditional Statement)
- Looping or Iteration
- Jumping statements
Decision making is about deciding the order of execution of statements based on certain conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
There are three types of conditions in python:
- if statement
- if-else statement
- elif statement
if statement:
- It is a simple if statement. When condition is true, then code which is associated with if statement will execute.
Example:
a=40
b=20
if a>b:
print(“a is greater than b”)
2. if-else statement:
- When the condition is true, then code associated with if statement will execute, otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement:
- It is short form of else-if statement. If the previous conditions were not true, then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
No comments:
Write comments