Python Programming with Jupyter and Anaconda
In Python programming, control flow statements are used to control the order in which statements are executed in a program. The two most commonly used control flow statements are if/else statements and loops.
If/else statements: An if/else statement is used to execute a block of code if a particular condition is true or false. The basic syntax of an if/else statement is:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
For example, if we want to check whether a variable x
is greater than 10 or not, we can use the following code:
if x > 10:
print('x is greater than 10')
else:
print('x is less than or equal to 10')
Loops: A loop is used to execute a block of code repeatedly until a particular condition is met. There are two types of loops in Python: for
loops and while
loops.
A for
loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each element in the sequence. The basic syntax of a for
loop is:
for element in sequence:
# code to execute for each element
For example, if we want to print each element in a list my_list
, we can use the following code:
my_list = [1, 2, 3]
for element in my_list:
print(element)
A while
loop is used to execute a block of code repeatedly as long as a particular condition is true. The basic syntax of a while
loop is:
while condition:
# code to execute as long as condition is true
For example, if we want to print the first 5 even numbers, we can use the following code:
i = 0
while i < 10:
if i % 2 == 0:
print(i)
i += 1
Further Reading:
Python Control Flow Statements
Python if...else Statement
Python for Loop
Python while Loop
All courses were automatically generated using OpenAI's GPT-3. Your feedback helps us improve as we cannot manually review every course. Thank you!