Conditional Statements¶
age = 18
if age >= 18:
print("Adult")
elif age < 5:
print("child")
else:
print("Minor")Adult
def my_adder(a, b, c):
"""
Calculate the sum of three numbers
author
date
"""
# Check for erroneous input
if not (
isinstance(a, (int, float))
or isinstance(b, (int, float))
or isinstance(c, (int, float))
):
raise TypeError("Inputs must be numbers.")
# Return output
return a + b + c# Testing the my_adder function
result = my_adder(1, 2, 3)
print(f"Result: {result}") # Returns 6Result: 6
# Testing error handling (uncomment to test)
# try:
# result = my_adder(1, '2', 3)
# print(result)
# except TypeError as e:
# print(f"Error: {e}") # Raises TypeError: Inputs must be numbers.Ternary Operator¶
Basic syntax for a ternary operator in Python:
value_if_true if condition else value_if_falseis_student = True
person = 'student' if is_student else 'not student'
print(person)student
Loops¶
# For loop
fruits = [1, 2, "apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)1
2
apple
banana
cherry
# While loop
count = 0
while count < 3:
print(count)
count += 10
1
2
# List
print("Looping through a list:")
for item in fruits:
print(item)Looping through a list:
1
2
apple
banana
cherry
# Tuple
my_tuple = (10, 20, 30)
print("Looping through a tuple:")
for item in my_tuple:
print(item)Looping through a tuple:
10
20
30
# Dictionary (keys)
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print("Looping through a dictionary (keys):")
for key in my_dict:
print(key, ":", my_dict[key])Looping through a dictionary (keys):
name : Alice
age : 25
city : New York
# Dictionary (items)
print("Looping through a dictionary (items):")
for key, value in my_dict.items():
print(key, ":", value)Looping through a dictionary (items):
name : Alice
age : 25
city : New York
# range() generates a sequence of numbers.
# Syntax: range(start, stop, step)
# - start: The first number (default is 0)
# - stop: The sequence ends before this number (required)
# - step: Difference between each number (default is 1)
# Example 1: range(5) -> [0, 1, 2, 3, 4]
print("Example 1: range(5)")
for i in range(5):
print(i)Example 1: range(5)
0
1
2
3
4
# Example 2: range(2, 7) -> [2, 3, 4, 5, 6]
print("Example 2: range(2, 7)")
for i in range(2, 7):
print(i)Example 2: range(2, 7)
2
3
4
5
6
# Example 3: range(1, 10, 2) -> [1, 3, 5, 7, 9]
print("Example 3: range(1, 10, 2)")
for i in range(1, 10, 2):
print(i)Example 3: range(1, 10, 2)
1
3
5
7
9
# Converting range to a list
numbers = list(range(5)) # [0, 1, 2, 3, 4]
print("Converting range to list:")
print(numbers)Converting range to list:
[0, 1, 2, 3, 4]
List Comprehensions¶
Efficient way to create lists - very useful for data processing.
# Basic list comprehension
squares = [x**2 for x in range(5)]
print("Basic list comprehension:")
print(squares)Basic list comprehension:
[0, 1, 4, 9, 16]
# List comprehension with condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print("List comprehension with condition:")
print(even_squares)List comprehension with condition:
[0, 4, 16, 36, 64]
# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
print("Dictionary comprehension:")
print(square_dict)Dictionary comprehension:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Dictionary comprehension from a list of tuples
tuples = [('a', 1), ('b', 2), ('c', 3)]
tuple_dict = {key: value for key, value in tuples}
print("Dictionary comprehension from tuples:")
print(tuple_dict)Dictionary comprehension from tuples:
{'a': 1, 'b': 2, 'c': 3}
# Set comprehension
unique_squares = {x**2 for x in range(-3, 4)}
print("Set comprehension:")
print(unique_squares)Set comprehension:
{0, 9, 4, 1}
Iterators and Generators¶
Memory-efficient ways to work with large datasets.
# Generator function
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b# Using generator
fib = fibonacci_generator(10)
print("Using generator:")
print(list(fib))Using generator:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Generator expression
squares_gen = (x**2 for x in range(5))
print("Generator expression:")
print(list(squares_gen))Generator expression:
[0, 1, 4, 9, 16]
# Using range (which is an iterator)
print("Using range as iterator:")
for i in range(3):
print(i)Using range as iterator:
0
1
2
# enumerate - useful for getting index and value
fruits = ["apple", "banana", "cherry"]
print("Using enumerate:")
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")Using enumerate:
0: apple
1: banana
2: cherry
# zip - combining multiple iterables
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
print("Using zip:")
for name, age in zip(names, ages):
print(f"{name} is {age} years old")Using zip:
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old