= 10
x
if x > 0:
print("x is positive.")
print("The value of x is", x)
Control Structures
Conditional Branching
if
statement
The if
statement checks if a specific condition or expression evaluates to True
. If the condition is satisfied (True
), the block of code associated with the if
statement will be executed.
In this example, the condition x > 0
evaluates to True
, so the indented block of code following the if
statement is executed.
if-else
statement
The else
statement is used whenever you want to execute a different block of code if the condition in the if
statement is False
.
= -5
x
if x > 0:
print("x is positive.")
else:
print("x is not positive.")
In this example, the condition x > 0
evaluates to False
, so the block of code following the else
statement is executed.
if-elif-else
statement
Use the elif
statement to check multiple conditions. elif
(short for “else if”) is used in conjunction with if
and else
to create a series of conditions. The block of code associated with the first if/elif
condition that evaluates to True
will be executed. If no condition is satisfied, the code associated with the else
statement (if present) will be executed.
= 15
temperature
if temperature < 0:
print("It's freezing outside.")
elif temperature < 10:
print("It's cold outside.")
elif temperature < 20:
print("It's chilly outside.")
elif temperature < 30:
print("It's warm outside.")
else:
print("It's hot outside.")
In this example, the first two conditions (temperature < 0
and temperature < 10
) evaluate to False
, while the third condition (temperature < 20
) evaluates to True
. Thus, the block of code associated with this condition is executed, and “It’s chilly outside.” is printed as output.
Nested if
statements
Nested if
statements allow you to make more complex condition checks by placing an if
statement inside another if
statement.
= 5
x = -2
y
if x > 0:
if y > 0:
print("Both x and y are positive.")
else:
print("x is positive, but y is not.")
else:
if y > 0:
print("y is positive, but x is not.")
else:
print("Neither x nor y is positive.")
In this example, the condition x > 0
evaluates to True
, so the first nested if
statement is executed. Within the nested statement, the condition y > 0
evaluates to False
, executing the code associated with the else
statement. Thus, “x is positive, but y is not.” is the output.
One-liner if-else
expression
You can use a single line of code to execute simple if-else
statements. This is called the ternary conditional operator.
= 5
x = "x is positive" if x > 0 else "x is not positive"
str_result print(str_result)
In this example, the condition x > 0
is True
, so the variable str_result
will be assigned the value “x is positive”
Loops
for
loop
The for
loop in Python is used to iterate over a sequence, such as a list, tuple, or string. for
loops iterate over each element in the sequence, executing the associated block of code for each element.
# Example using a list
= [1, 2, 3, 4, 5]
numbers for num in numbers:
print(num)
In this example, the for
loop iterates over each element in the numbers
list. The loop variable num
takes on the value of each element in the list, and the print(num)
statement is executed.
# Example using a string
= "Python"
name for letter in name:
print(letter)
In this example, the for
loop iterates over each character in the name string.
for
loop with range()
The range()
function generates a sequence of numbers. It is commonly used in for
loops when you want to repeat a block of code a specific number of times.
# range(stop): Generates a sequence of numbers from 0 to stop - 1
for i in range(5):
print(i)
In this example, the range(5)
function generates the sequence [0, 1, 2, 3, 4]
, and the for
loop iterates over that sequence.
while
loop
The while
loop is used to repeatedly execute a block of code while a specified condition is True
. When the condition becomes False
, the loop terminates, and the program continues with the code following the while
loop.
# Example
= 0
counter while counter < 5:
print("counter:", counter)
= counter + 1 counter
In this example, the while
loop will continue to execute its block of code as long as the counter
variable is less than 5. After each iteration, the value of counter
is incremented by 1. When counter
reaches 5, the loop condition becomes False
, and the loop terminates.
List Comprehensions
List comprehensions are a concise and readable way to create lists in Python. They provide an alternative to creating lists using for
loops, offering more compact and readable code for specific scenarios. List comprehensions are especially useful when working with transformations or filters for lists.
The syntax for list comprehensions is as follows:
for item in iterable if condition] [expression
notes: if condition
is optional. This is the filter that will only include item
in the resulting list if the given condition is True
.
# Create a list of the squares of the numbers from 1 to 10:
= [x**2 for x in range(1, 11)]
squares
# Create a list of even numbers between 1 and 20:
= [x for x in range(1, 21) if x % 2 == 0] even_numbers
Exercise Control Structures
!pip install rggrader
# @title #### Student Identity
= "your student id" # @param {type:"string"}
student_id = "your name" # @param {type:"string"} name
# @title #### 00. Sum of Even Numbers
from rggrader import submit
# Write a program to compute the sum of all even numbers from 1 to 'n'.
# sum = 2 + 4 + ... + n
= 50
n
# TODO: compute the sum
# The sum of all even numbers from 1 to n:
sum = 0
# Put your code here:
# ---- End of your code ----
print(f"The sum of all even numbers from 1 to {n} is {sum}")
# Submit Method
= "01-control-structures"
assignment_id = "00_sum-of-even-numbers"
question_id str(sum), question_id)
submit(student_id, name, assignment_id,
# Expected Output for n=50: 650
# @title #### 01. Alternating Sum Even Odd
from rggrader import submit
# Write a program to calculate the sum of all even numbers subtracted by all odd numbers from 1 to 'n'.
# sum = -1 + 2 -3 + 4 + ... + n
= 50
n
# TODO: compute the sum
# Sum all even numbers and subtract all odd numbers from 1 to n:
sum = 0
# Put your code here:
# ---- End of your code ----
print(f"The sum of all even numbers subtracted by all odd numbers from 1 to {n} is {sum}")
# Submit Method
= "01-control-structures"
assignment_id = "01_alternating-sum-even-odd"
question_id str(sum), question_id)
submit(student_id, name, assignment_id,
# Expected Output for n=50: 0
# @title #### 02. Sum of Divisors
from rggrader import submit
# Write a program to compute the sum of all divisors of a given number 'n'.
# For example for n=12, the divisors are 1, 2, 3, 4, 6, 12 and the sum would be 28.
= 12
n
# TODO: compute the sum
# The sum of all divisors of n:
sum = 0
# Put your code here:
# ---- End of your code ----
print(f"The sum of all divisors of {n} is {sum}")
# Submit Method
= "01-control-structures"
assignment_id = "02_sum-of-divisors"
question_id str(sum), question_id)
submit(student_id, name, assignment_id,
# Expected Output for n=12: 28
# @title #### 03. Fibonacci Sequence
from rggrader import submit
# Write a program to print the first 'n' Fibonacci numbers.
# A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
# The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.
= 10
n
# TODO: print the first n Fibonacci numbers
# Put your code here:
# ---- End of your code ----
# Submit Method
= "01-control-structures"
assignment_id = "03_fibonacci-sequence"
question_id str(n), question_id)
submit(student_id, name, assignment_id,
# Expected Output for n=10: 0 1 1 2 3 5 8 13 21 34