Mark As Completed Discussion

Control Flow

In Python, control flow refers to the order in which statements are executed in a program. It allows you to control the flow of execution based on conditions and loops.

If Statements

If statements are used to perform different actions based on different conditions. They allow you to specify certain conditions and execute certain code blocks if those conditions are met.

Here's an example of an if statement in Python:

PYTHON
1# Python code to demonstrate if statement
2
3# initializing a variable
4temperature = 25
5
6# checking the condition
7if temperature > 30:
8    print("It's hot outside")
9
10print("Enjoy your day")

In the above code, if the temperature is greater than 30, the program will print 'It's hot outside'. Otherwise, it will print 'Enjoy your day'.

Loops

Loops allow you to repeat a block of code multiple times. Python provides two types of loops: for loop and while loop.

Here's an example of a for loop that prints numbers from 1 to 10:

PYTHON
1# Python code to demonstrate for loop
2
3# iterating over a range of numbers
4for i in range(1, 11):
5    print(i)
6
7print("Loop is done")

In the above code, the for loop iterates over a range of numbers from 1 to 10 and prints each number. After the loop is finished, it prints 'Loop is done'.

Conditional Expressions

Conditional expressions, also known as ternary operators, allow you to write a shorter version of an if-else statement in a single line. It provides a way to make decisions based on a condition in a concise manner.

Here's an example of a conditional expression in Python:

PYTHON
1# Python code to demonstrate conditional expression
2
3# assigning a value based on a condition
4value = 10
5result = "Even" if value % 2 == 0 else "Odd"
6
7print(result)

In the above code, the value is checked for evenness using the condition value % 2 == 0. If the condition is true, the variable result is assigned the value 'Even', otherwise it is assigned the value 'Odd'. The result is then printed.

Understanding control flow is important as it allows you to make decisions, repeat code blocks, and perform different actions based on conditions in your program. Mastering control flow will make your code more flexible and powerful.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment