1. Boolean Expressions:¶

These expressions evaluate to either True or False.¶

In [ ]:
x = 10
y = 5

print(x > y)  # True
print(x == y) # False
print(x < y)  # False
True
False
False

2. if Statement:¶

Executes a block of code only if a condition is True.¶

In [ ]:
x = 10
y = 5
if x > y:
  print("x is greater than y")
x is greater than y

3. else Statement:¶

Executes a block of code if the preceding if statement's condition is False.¶

In [ ]:
x = 10
y = 5
if x < y:
  print("x is less than y")
else:
  print("x is not less than y")
x is not less than y

4. elif Statement (else if):¶

Allows you to check multiple conditions sequentially.¶

In [ ]:
x = 10
y = 5
if x < y:
  print("x is less than y")
elif x == y:
  print("x is equal to y")
else:
  print("x is greater than y")
x is greater than y

5. Nested if Statements:¶

You can put if statements inside other if statements.¶

In [ ]:
if x > 5:
  if x < 15:
    print("x is between 5 and 15")
x is between 5 and 15

6. Logical Operators:¶

Combine multiple boolean expressions.¶

and: Both conditions must be True.¶

or: At least one condition must be True.¶

not: Inverts the truth value of a condition.¶

In [ ]:
x = 10
y = 5
if x > 5 and x < 15:
  print("x is between 5 and 15")

if x < 5 or x > 15:
  print("x is outside the range of 5 and 15")

if not (x == y):
  print("x is not equal to y")
x is between 5 and 15
x is not equal to y

Example: Checking if a number is even or odd¶

In [ ]:
number = 10

if number % 2 == 0:
  print(number, "is an even number")
else:
  print(number, "is an odd number")
10 is an even number

Python allows conditional checks on lists, tuples, strings, and other sequences.¶

In [ ]:
name = "Hello"
if "l" in name:
  print("The name contains 'l'")
The name contains 'l'

Iteration¶

For loop¶

In [ ]:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
apple
banana
cherry
In [ ]:
for i in range(5):
    print(i)
0
1
2
3
4

While loop¶

In [ ]:
count = 0
while count < 3:
  print(count)
  count += 1
0
1
2

Break¶

In [ ]:
for i in range(10):
  if i == 5:
      break
  print(i)
0
1
2
3
4
5
6
7
8
9

Continue¶

In [ ]:
for i in range(5):
    if i == 3:
        continue
    print(i)
0
1
2
4

for loop in another for loop¶

In [ ]:
for i in range(3):
  for j in range(2):
    print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

loop in dictionary¶

In [ ]:
person = {"name": "John",
      "age": 25,
      "city": "New York"}
for key, value in person.items():
  print(f"{key}: {value}")
name: John
age: 25
city: New York

One line for loop¶

In [ ]:
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)
[1, 4, 9, 16, 25]

same as above, but in many lines¶

In [ ]:
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
  square = n**2
  squares.append(square)

print(squares)
[1, 4, 9, 16, 25]

loop item and get index at the same time, (enumerate)¶

In [ ]:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
  print(index, fruit)
0 apple
1 banana
2 cherry

use two lists in a for loop. Zip it.¶

In [ ]:
names = ["John", "Jane", "Doe"]
ages = [25, 28, 22]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
John is 25 years old
Jane is 28 years old
Doe is 22 years old

Exercise¶

In [ ]:
students = [
    {"name": "John",  "scores": {"math": 90, "science": 85}},
    {"name": "Jane",  "scores": {"math": 78, "science": 92}},
    {"name": "Doe",  "scores": {"math": 85, "science": 89}},
]
print(students)
print(type(students))
[{'name': 'John', 'scores': {'math': 90, 'science': 85}}, {'name': 'Jane', 'scores': {'math': 78, 'science': 92}}, {'name': 'Doe', 'scores': {'math': 85, 'science': 89}}]
<class 'list'>
In [ ]:
# Calculate the average score for each student
for student in students:
  print(student)
  scores = student['scores'].values()
  print(scores)
  average_score = sum(scores) / len(scores)
  print(f"{student['name']}'s average score: {average_score:.2f}")
{'name': 'John', 'scores': {'math': 90, 'science': 85}}
dict_values([90, 85])
John's average score: 87.50
{'name': 'Jane', 'scores': {'math': 78, 'science': 92}}
dict_values([78, 92])
Jane's average score: 85.00
{'name': 'Doe', 'scores': {'math': 85, 'science': 89}}
dict_values([85, 89])
Doe's average score: 87.00
In [ ]: