ISBN Validator
Skill 1: Variable Assignment
Easier Exercise:
Task: Assign your name to a variable called my_name
.
Your Code:
Click here to write code in a Python learning environment
Example:
my_name = "Alice"
Practice Exercise 2 (More Complex):
Task: Assign your age to a variable called my_age
, and then assign a new variable next_year_age
that is one more than your age.
Your Code:
Click here to write code in a Python learning environment
Example:
my_age = 12
next_year_age = my_age + 1
Skill 2: Data Types
Practice Exercise 1 (Basic):
Task: Create a variable called is_sunny
and set it to a Boolean value that means "yes".
Your Code:
Click here to write code in a Python learning environment
Example:
is_sunny = True
Practice Exercise 2 (More Complex):
Task: Create three variables: first_name
, last_name
, and age
. Then create a variable called intro
that contains a full sentence introducing yourself using those variables.
Your Code:
Click here to write code in a Python learning environment
Example:
first_name = "Sam"
last_name = "Lee"
age = 13
intro = "My name is " + first_name + " " + last_name + " and I am " + str(age) + " years old."
Skill 3: Print Statements
Practice Exercise 1 (Basic):
Task: Print the phrase:
Hello, world!
Your Code:
Click here to write code in a Python learning environment
Example:
print("Hello, world!")
Practice Exercise 2 (More Complex):
Task: Create a variable called pet_name
and assign it the name of a pet. Print a sentence that says:
My pet's name is ___
using the variable.
Your Code:
Click here to write code in a Python learning environment
Example:
pet_name = "Buddy"
print("My pet's name is " + pet_name)
Skill 4: Defining Functions
Practice Exercise 1 (Basic):
Task: Define a function called greet
that prints the message "Hello there!"
. Then call the function.
Your Code:
Click here to write code in a Python learning environment
Example:
def greet():
print("Hello there!")
greet()
Practice Exercise 2 (More Complex):
Task: Define a function called introduce
that prints a sentence with your name and favorite color inside it. Call the function after defining it.
Your Code:
Click here to write code in a Python learning environment
Example:
def introduce():
name = "Lara"
color = "green"
print("Hi, my name is " + name + " and my favorite color is " + color + ".")
introduce()
Skill 5: using parameters in functions
Practice Exercise 1 (Basic):
Task: Define a function called say_hello
that takes one parameter name
. The function should print a greeting like: Hello, [name]!
. Call the function using your own name.
Your Code:
Click here to write code in a Python learning environment
Example:
def say_hello(name):
print("Hello, " + name + "!")
say_hello("Maya")
Practice Exercise 2 (More Complex):
Task: Define a function called describe_pet
that takes two parameters: animal_type
and pet_name
. Print a sentence using both values in the format: I have a [animal_type] named [pet_name].
Your Code:
Click here to write code in a Python learning environment
Example:
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type + " named " + pet_name + ".")
describe_pet("dog", "Max")
Skill 6: Returning Values from Functions
Practice Exercise 1 (Basic):
Task: Define a function called add_two_numbers
that takes two numbers as parameters and returns their sum. Store the result in a variable and print it.
Your Code:
Click here to write code in a Python learning environment
Example:
def add_two_numbers(a, b):
return a + b
total = add_two_numbers(3, 5)
print(total)
Practice Exercise 2 (More Complex):
Task: Write a function called make_greeting
that takes a name as a parameter and returns a greeting message. Store the result and then print it.
Your Code:
Click here to write code in a Python learning environment
Example:
def make_greeting(name):
return "Hello, " + name + "! Welcome."
message = make_greeting("Ava")
print(message)
Skill 7: Calling Functions
Practice Exercise 1 (Basic):
Task: Define a function called good_morning
that prints "Good morning!"
. Then call the function below it.
Your Code:
Click here to write code in a Python learning environment
Example:
def good_morning():
print("Good morning!")
good_morning()
Practice Exercise 2 (More Complex):
Task: Define two functions:
say_name()
that prints your namemorning_message()
that callssay_name()
and then prints"Have a great day!"
Callmorning_message()
at the end.
Your Code:
Click here to write code in a Python learning environment
Example:
def say_name():
print("My name is Leo.")
def morning_message():
say_name()
print("Have a great day!")
morning_message()
Skill 8: String Methods
Practice Exercise 1 (Basic):
Task: Create a string word = "hello"
. Print the uppercase version of the string using a string method.
Your Code:
Click here to write code in a Python learning environment
Example
word = "hello"
print(word.upper())
Practice Exercise 2 (More Complex):
Task: Create a list of single characters: ['H', 'i', '!']
. Use the ''.join()
method to combine them into one string. Then print the string and its length using len()
.
Your Code:
Click here to write code in a Python learning environment
Example:
chars = ['H', 'i', '!']
message = ''.join(chars)
print(message)
print(len(message))
Skill 9: Lists
Practice Exercise 1 (Basic):
Task: Create a list called colors
with three colors inside it. Then print the list.
Your Code:
Click here to write code in a Python learning environment
Example:
colors = ["red", "blue", "green"]
print(colors)
Practice Exercise 2 (More Complex):
Task: Create a list of your three favorite foods. Then print the first item in the list using indexing.
Your Code:
Click here to write code in a Python learning environment
Example:
favorite_foods = ["pizza", "sushi", "ice cream"]
print(favorite_foods[0])
Skill 10: For Loops
Practice Exercise 1 (Basic):
Task: Use a for loop to print the numbers 0 to 4.
Your Code:
Click here to write code in a Python learning environment
Example:
for i in range(5):
print(i)
Practice Exercise 2 (More Complex):
Task: Create a list called names
with three names. Use a for loop to print: "Hello, [name]!"
for each.
Your Code:
Click here to write code in a Python learning environment
Example:
names = ["Liam", "Ava", "Noah"]
for name in names:
print("Hello, " + name + "!")
Skill 11: Iterating through lists
Practice Exercise 1 (Basic):
Task: Create a list called fruits
with three fruit names. Use a for loop to print each fruit name.
Your Code:
Click here to write code in a Python learning environment
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Practice Exercise 2 (More Complex):
Task: Create a list called numbers
with the values 10, 20, 30, 40
. Use a for loop to print each number multiplied by 2.
Your Code:
Click here to write code in a Python learning environment
Example:
numbers = [10, 20, 30, 40]
for number in numbers:
print(number * 2)
Skill 12: Creating a For Loop That Repeats a Certain Amount of Time Using range()
Practice Exercise 1 (Basic):
Task: Use a for loop with range()
to print the numbers 0 to 4.
Your Code:
Click here to write code in a Python learning environment
Example:
for i in range(5):
print(i)
Practice Exercise 2 (More Complex):
Task: Use a for loop with range()
to print "Good job!"
three times.
Your Code:
Click here to write code in a Python learning environment
Example:
for i in range(3):
print("Good job!")
Skill 13: Conditional Statements
Practice Exercise 1 (Basic):
Task: Create a variable age
and set it to 16. Use an if statement to print "You are old enough to drive."
if the age is 16 or more.
Your Code:
Click here to write code in a Python learning environment
Example:
age = 16
if age >= 16:
print("You are old enough to drive.")
Practice Exercise 2 (More Complex):
Task: Create a variable score
and set it to 85. Use an if-else statement to print "You passed!"
if the score is 60 or more, otherwise print "You did not pass."
Your Code:
Click here to write code in a Python learning environment
Example:
score = 85
if score >= 60:
print("You passed!")
else:
print("You did not pass.")
Skill 14: Logic Operators (e.g., ==
and !=
in If Statements)
Practice Exercise 1 (Basic):
Task: Create a variable color
and set it to "blue"
. Use an if statement to check if the color is "blue"
and print "Blue is cool!"
if true.
Your Code:
Click here to write code in a Python learning environment
Example:
color = "blue"
if color == "blue":
print("Blue is cool!")
Practice Exercise 2 (More Complex):
Task: Create a variable day
and set it to "Saturday"
. Use an if statement to check if the day is not "Monday"
, and if so, print "It's not Monday!"
Your Code:
Click here to write code in a Python learning environment
Example:
day = "Saturday"
if day != "Monday":
print("It's not Monday!")
Skill 15: if not
Statements
Practice Exercise 1 (Basic):
Task: Create a variable is_raining
set to False
. Use an if not
statement to print "You donāt need an umbrella."
Your Code:
Click here to write code in a Python learning environment
Example:
is_raining = False
if not is_raining:
print("You donāt need an umbrella.")
Practice Exercise 2 (More Complex):
Task: Create a variable homework_done
and set it to False
. Use an if not
statement to print "Please finish your homework!"
if homework is not done.
Your Code:
Click here to write code in a Python learning environment
Example:
homework_done = False
if not homework_done:
print("Please finish your homework!")
Skill 16: Using and
, or
, not
Practice Exercise 1 (Basic):
Task: Create two variables: is_weekend = True
and is_sunny = False
. Use an or
statement to print "You can go out!"
if itās either the weekend or sunny.
Your Code:
Click here to write code in a Python learning environment
Example:
is_weekend = True
is_sunny = False
if is_weekend or is_sunny:
print("You can go out!")
Practice Exercise 2 (More Complex):
Task: Create two variables: has_ticket = True
, age = 12
. Use an and
statement to check if the person has a ticket and is at least 10 years old. If both are true, print "You can enter!"
Your Code:
Click here to write code in a Python learning environment
Example:
has_ticket = True
age = 12
if has_ticket and age >= 10:
print("You can enter!")
Skill 17: Using +=
Practice Exercise 1 (Basic):
Task: Create a variable points = 0
. Use +=
to add 10 points, then print the total.
Your Code:
Click here to write code in a Python learning environment
Example:
points = 0
points += 10
print(points)
Practice Exercise 2 (More Complex):
Task: Create a variable total = 0
. Then use a for loop with range(5)
to add 2 to total
on each loop. Print the total after the loop ends.
Your Code:
Click here to write code in a Python learning environment
Example:
total = 0
for i in range(5):
total += 2
print(total)
Skill 18: Arithmetic Operators
Practice Exercise 1 (Basic):
Task: Create two variables a = 10
and b = 3
. Print the result of a % b
.
Your Code:
Click here to write code in a Python learning environment
Example:
a = 10
b = 3
print(a % b)
Practice Exercise 2 (More Complex):
Task: Ask the question: "Is a number even?"
Create a variable num = 7
. Use %
to check if the number is even (hint: even numbers have no remainder when divided by 2). If it is even, print "Even number"
, otherwise print "Odd number"
.
Your Code:
Click here to write code in a Python learning environment
Example:
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Skill 19: Python Methods
Practice Exercise 1 (Basic):
Task: Create a string variable number_str = "5"
. Convert it to an integer using int()
and add 2 to it. Print the result.
Your Code:
Click here to write code in a Python learning environment
Example:
number_str = "5"
number = int(number_str)
print(number + 2)
Practice Exercise 2 (More Complex):
Task: Create a list of numbers: [4, 5, 6]
. Use sum()
to add all the numbers together and print the total.
Your Code:
Click here to write code in a Python learning environment
Example:
numbers = [4, 5, 6]
total = sum(numbers)
print(total)
Skill 20: Python Value Error Exception Handling
Practice Exercise 1 (Basic):
Task: Write a function called check_number
that takes a number as a parameter. If the number is less than 0, raise a ValueError
with the message "Number cannot be negative"
. Test it by calling the function with a negative number.
Your Code:
Click here to write code in a Python learning environment
Example:
def check_number(number):
if number < 0:
raise ValueError("Number cannot be negative")
check_number(-5)
Practice Exercise 2 (More Complex):
Task: Write a function called check_age
that takes an age as a parameter. If the age is less than 18, raise a ValueError
with the message "You must be at least 18 years old"
. Test it by calling the function with an age below 18.
Your Code:
Click here to write code in a Python learning environment
Example:
def check_age(age):
if age < 18:
raise ValueError("You must be at least 18 years old")
check_age(16)
Skill 21: Concatenating String (+ f
Statements)
Practice Exercise 1 (Basic):
Task: Create two string variables first_name = "John"
and last_name = "Doe"
. Concatenate them using the +
operator to create a full name, and print it.
Your Code:
Click here to write code in a Python learning environment
Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Practice Exercise 2 (More Complex):
Task: Create two variables: age = 25
and city = "New York"
. Use an f-string to create a sentence that says: "I am 25 years old and I live in New York."
and print the sentence.
Your Code:
Click here to write code in a Python learning environment
Example:
age = 25
city = "New York"
sentence = f"I am {age} years old and I live in {city}."
print(sentence)
Skill 22: New Line Syntax (\n
)
Practice Exercise 1 (Basic):
Task: Create a string variable message = "Hello"
and append a new line (\n
) to it. Add "World!"
after the new line. Print the message.
Your Code:
Click here to write code in a Python learning environment
Example:
message = "Hello\nWorld!"
print(message)
Practice Exercise 2 (More Complex):
Task: Create a variable address
with the following string: "123 Main St"
. Use \n
to add a new line after the street address and then add "City, Country"
. Print the address in the correct format.
Your Code:
Click here to write code in a Python learning environment
Example:
address = "123 Main St\nCity, Country"
print(address)
Task Priority Manager
1. Defining a List
Easier Exercise: Create a List of Favorite Colors
Task: Define a list called
colors
that contains your 3 favorite colors. Print the list.Your Code:
Example:
colors = ["blue", "green", "red"]
print(colors)
More Complex Exercise: List of Numbers and Sum
Task: Define a list of 5 numbers and calculate the sum of the numbers in the list. Print the sum.
Your Code:
Example:
numbers = [2, 5, 8, 10, 3]
total = sum(numbers)
print(total)
2. Allowing for User Input (input() Method)
Easier Exercise: Collect Your Name
Task: Ask the user to input their name and print a greeting message using their name.
Your Code:
Example:
name = input("What is your name? ")
print(f"Hello, {name}!")
More Complex Exercise: Collect and Add Two Numbers
Task: Ask the user to input two numbers and then print their sum.
Your Code:
Example:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
sum_result = num1 + num2
print(f"The sum is: {sum_result}")
3. Defining a Procedure (Difference Between Procedure and Function)
Easier Exercise: Simple Function to Greet
Task: Define a simple function that prints "Hello, world!". Call this function.
Your Code:
Example:
def greet():
print("Hello, world!")
greet()
More Complex Exercise: Function to Calculate Square of a Number
Task: Define a function that takes a number as input and returns the square of that number. Call the function and print the result.
Your Code:
Example:
def square(number):
return number ** 2
result = square(4)
print(result)
4. Passing Parameters into Procedures and Using Them Throughout the Procedure
Easier Exercise: Greet with a Name
Task: Define a function that takes a name as a parameter and prints a greeting using that name.
Your Code:
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
More Complex Exercise: Calculate the Area of a Rectangle
Task: Define a function that takes the length and width of a rectangle as parameters and returns the area.
Your Code:
Example:
def area_of_rectangle(length, width):
return length * width area = area_of_rectangle(5, 3)
print(area)
5. Calling Procedures
Easier Exercise: Call a Function to Print a Message
Task: Define a function that prints "I am learning Python!" and call it.
Your Code:
Example:
def learning_message():
print("I am learning Python!")
learning_message()
More Complex Exercise: Call a Function to Add Two Numbers
Task: Define a function that adds two numbers and call the function with different values.
Your Code:
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
6. Using if..break
Easier Exercise: Break the Loop when User Types "stop"
Task: Write a loop that keeps asking the user to input a word. If the user types "stop", the loop should end.
Your Code:
while True:
user_input = input("Enter a word: ")
if user_input.lower() == "stop":
break
print("You typed:", user_input)
More Complex Exercise: Stop Loop if Number is Even
Task: Write a loop that keeps asking the user for numbers. If an even number is entered, break the loop.
Your Code:
Example:
while True:
number = int(input("Enter a number: "))
if number % 2 == 0:
break
print("You entered an odd number:", number)
7. Using .append() Method for Lists
Easier Exercise: Add an Item to a List
Task: Create a list of numbers and add one more number to it using the
.append()
method. Print the updated list.Your Code:
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
More Complex Exercise: Append User Input to a List
Task: Create an empty list and ask the user to enter 3 items. Append each item to the list and print the final list.
Your Code:
Example:
items = []
for _ in range(3):
item = input("Enter an item: ")
items.append(item)
print(items)
8. Using While True
Easier Exercise: Infinite Loop with Break
Task: Write a loop that repeatedly asks the user for their name until they type "quit".
Your Code:
Example:
while True:
name = input("Enter your name (type 'quit' to stop): ")
if name.lower() == "quit":
break
print(f"Hello, {name}!")
More Complex Exercise: Sum Numbers Until User Types "done"
Task: Use a
while True
loop to keep asking the user for numbers to sum. If the user types "done", print the total sum.Your Code:
Example:
total = 0
while True:
user_input = input("Enter a number (or 'done' to stop): ")
if user_input.lower() == "done":
break total += float(user_input)
print(f"The total sum is: {total}")
9. Using List()
Easier Exercise: Convert a Tuple to a List
Task: Convert a tuple of 3 items to a list and print the result.
Your Code:
Example:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)
More Complex Exercise: Convert Input Values to List
Task: Ask the user for 3 numbers, convert the inputs into a list of numbers, and print the list.
Your Code:
Example:
user_input = input("Enter 3 numbers separated by space: ")
numbers = list(map(int, user_input.split()))
print(numbers)
10. Using Filter()
Easier Exercise: Filter Even Numbers
Task: Filter out the even numbers from a list of numbers and print the result.
Your Code:
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
More Complex Exercise: Filter Numbers Greater Than 10
Task: Filter all numbers greater than 10 from a list of integers.
Your Code:
Example:
numbers = [5, 12, 18, 3, 7, 20]
greater_than_ten = filter(lambda x: x > 10, numbers)
print(list(greater_than_ten))
11. Lambda Functions
Easier Exercise: Simple Lambda Function
Task: Create a lambda function that adds 5 to a number and use it to add 5 to a given number.
Your Code:
Example
add_five = lambda x: x + 5
result = add_five(10)
print(result)
More Complex Exercise: Lambda Function to Calculate Square
Task: Create a lambda function that calculates the square of a number and apply it to a list of numbers.
Your Code:
Example:
numbers = [2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
12. Using Sorted()
Easier Exercise: Sort Numbers in Ascending Order
Task: Sort a list of numbers in ascending order and print the result.
Your Code:
Example:
numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
More Complex Exercise: Sort Strings by Length
Task: Sort a list of strings by the length of each string.
Your Code:
Example:
words = ["apple", "banana", "kiwi", "grape"]
sorted_words = sorted(words, key=len)
print(sorted_words)
13. Using Min()
Easier Exercise: Find the Minimum Number in a List
Task: Use the
min()
function to find the smallest number in a list and print it.Your Code:
Example:
numbers = [5, 2, 9, 1, 7]
minimum_value = min(numbers)
print(minimum_value)
More Complex Exercise: Find the Shortest String
Task: Use
min()
to find the shortest string in a list of strings based on length.Your Code:
Example:
words = ["apple", "banana", "kiwi", "grape"]
shortest_word = min(words, key=len)
print(shortest_word)
14. Accessing Items from a List Using Indexes
Easier Exercise: Access the First Item of a List
Task: Print the first item in a list using its index.
Your Code:
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
More Complex Exercise: Access the Last Item of a List
Task: Access and print the last item from a list using negative indexing.
Your Code:
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
15. Recap in Catching Return Values from Functions
Easier Exercise: Catch the Return Value from a Simple Function
Task: Write a function that returns a greeting message, and capture the return value in a variable. Print the variable to display the greeting.
Your Code:
Example:
def greet():
return "Hello, welcome to Python!"
greeting_message = greet() # Catch the return value print(greeting_message)
More Complex Exercise: Function to Calculate and Catch the Sum of Two Numbers
Task: Write a function that takes two numbers as input, adds them together, and returns the result. Call the function, catch the return value, and print the sum.
Your Code:
Example:
def add_numbers(a, b):
return a + b
sum_result = add_numbers(5, 7) # Catch the return value of the function
print(f"The sum of the numbers is: {sum_result}")
Vowel Remover Program
1. string method .lower and .upper
Practice Exercise 1: (Easier) Convert a string to lowercase and uppercase
Task: Write a Python program that asks the user to input a string and then outputs the string in both lowercase and uppercase.
Your code:
Click here to write code in a Python learning environment.
Example:
user_input = input("Enter a string: ")
lowercase_string = user_input.lower()
uppercase_string = user_input.upper()
print(f"Lowercase: {lowercase_string}")
print(f"Uppercase: {uppercase_string}")
Practice Exercise 2: (More Complex) Format a sentence in both lowercase and uppercase
Task: Write a Python program that accepts a sentence from the user, converts the entire sentence to lowercase, and then prints out the uppercase version of the sentence with each word starting with a capital letter.
Your code:
Click here to write code in a Python learning environment.
Example:
sentence = input("Enter a sentence: ")
# Convert to lowercase first
lowercase_sentence = sentence.lower()
# Capitalize each word in the lowercase sentence
capitalized_sentence = lowercase_sentence.title()
print(f"Lowercase: {lowercase_sentence}")
print(f"Capitalized: {capitalized_sentence}")
2. recap on string method .join
Practice Exercise 1: (Easier) Join a list of words into a single sentence
Task: Write a Python program that takes a list of words and joins them together to form a sentence using spaces.
Your code:
Click here to write code in a Python learning environment.
Example:
words = ["Python", "is", "fun", "to", "learn"] # Join words into a sentence
sentence = " ".join(words)
print("Sentence:", sentence)
Practice Exercise 2: (More Complex) Join a list of words into a sentence with a custom separator
Task: Write a Python program that asks the user to input a list of words separated by spaces and joins them into a sentence. Additionally, the program should ask the user to input a separator (like a comma or dash), which should be used to join the words.
Your code:
Click here to write code in a Python learning environment.
Example:
words = input("Enter words separated by space: ").split()
separator = input("Enter a separator: ")
# Join words with the given separator
sentence = separator.join(words)
print("Joined Sentence:", sentence)
3. for loop recap
Practice Exercise 1: (Easier) Loop through a list and print each item
Task: Write a Python program that loops through a list of numbers and prints each number one by one.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5]
# Loop through each number and print it
for number in numbers:
print(number)
Practice Exercise 2: (More Complex) Calculate the sum of all even numbers in a list
Task: Write a Python program that loops through a list of numbers, identifies the even numbers, and calculates the sum of all even numbers in the list.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Initialize the sum of even numbers
sum_of_even_numbers = 0
# Loop through each number and add to sum if it's even
for number in numbers:
if number % 2 == 0:
sum_of_even_numbers += number
print(f"Sum of even numbers: {sum_of_even_numbers}")
4. list comprehension
Practice Exercise 1: (Easier) Square each number in a list using list comprehension
Task: Write a Python program that uses list comprehension to square each number in a list of numbers.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5]
# Use list comprehension to square each number
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers)
Practice Exercise 2: (More Complex) Extract only the even numbers from a list using list comprehension
Task: Write a Python program that uses list comprehension to filter out only the even numbers from a list of numbers.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Use list comprehension to extract only even numbers
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Finding Square Root of Pi
Arithmetic Operators Recap
Practice Exercise 1 (Basic)
Task:
Write a program that adds, subtracts, multiplies, and divides two numbers (you can input the numbers). Also, raise one of the numbers to the power of 3.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Input two numbers
num1 = 5
num2 = 3
# Perform arithmetic operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
exponentiation = num1 ** 3 # Display the results
print(f"{num1} + {num2} = {addition}")
print(f"{num1} - {num2} = {subtraction}")
print(f"{num1} * {num2} = {multiplication}")
print(f"{num1} / {num2} = {division}")
print(f"{num1} raised to the power of 3 is {exponentiation}")
Example Output:
5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 3 = 1.6666666666666667
5 raised to the power of 3 is 125
Practice Exercise 2 (Complex)
Task:
Write a program that accepts two numbers from the user, calculates their sum, difference, product, quotient, and the first number raised to the power of the second number. Handle division by zero errors gracefully.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform arithmetic operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
# Handle division by zero
if num2 != 0:
division = num1 / num2
else:
division = "Cannot divide by zero"
# Perform exponentiation
exponentiation = num1 ** num2
# Display the results
print(f"{num1} + {num2} = {addition}")
print(f"{num1} - {num2} = {subtraction}")
print(f"{num1} * {num2} = {multiplication}")
print(f"{num1} / {num2} = {division}")
print(f"{num1} raised to the power of {num2} is {exponentiation}")
Example Output:
Enter the first number: 4
Enter the second number: 2
4 + 2 = 6.0
4 - 2 = 2.0
4 * 2 = 8.0
4 / 2 = 2.0
4 raised to the power of 2.0 is 16.0
2. Using max()
Function
Practice Exercise 1 (Basic)
Task:
Write a program that uses the max()
function to find the larger of two numbers entered by the user.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Use max() to find the larger number
larger_number = max(num1, num2)
# Display the result
print(f"The larger number is: {larger_number}")
Example Output:
Enter the first number: 5
Enter the second number: 8
The larger number is: 8.0
Practice Exercise 2 (Complex)
Task:
Write a program that takes three numbers as input and uses max()
to find the largest number. Also, display the smallest number using the min()
function.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Input three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Use max() to find the largest number and min() for the smallest
largest = max(num1, num2, num3)
smallest = min(num1, num2, num3)
# Display the results
print(f"The largest number is: {largest}")
print(f"The smallest number is: {smallest}")
Example Output:
Enter the first number: 3
Enter the second number: 7
Enter the third number: 5
The largest number is: 7.0
The smallest number is: 3.0
3. Setting a Variable to None
Practice Exercise 1 (Basic)
Task:
Create a variable my_var
and set it to None
. Then, check if it is None
and print a message.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Set the variable to None
my_var = None # Check if the variable is None
if my_var is None:
print("The variable is set to None.")
else:
print("The variable has a value.")
Example Output:
The variable is set to None.
Practice Exercise 2 (Complex)
Task:
Write a program that assigns None
to a variable result
. If a certain condition is met (for example, if two numbers are equal), set result
to the sum of the numbers. Print the result only if it is not None
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Assign None to result
result = None
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# If the numbers are equal, assign the sum to result
if num1 == num2:
result = num1 + num2
# Display the result if it's not None
if result is not None:
print(f"The sum of the two numbers is: {result}")
else:
print("The numbers are not equal, so no sum is displayed.")
Example Output:
Enter the first number: 4
Enter the second number: 4
The sum of the two numbers is: 8.0
4. Importing Libraries in Python (Math Library)
Practice Exercise 1 (Basic)
Task:
Write a program that imports the math
library and prints the value of pi.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Import the math library
import math
# Print the value of pi
print(f"The value of pi is: {math.pi}")
Example Output:
The value of pi is: 3.141592653589793
Practice Exercise 2 (Complex)
Task:
Write a program that uses the math
library to calculate the square root of a number (use the math.sqrt()
function).
Your Code:
Click here to write code in a Python learning environment.
Example:
# Import the math library
import math
# Input a number
num = float(input("Enter a number: "))
# Calculate the square root using math.sqrt()
square_root = math.sqrt(num)
# Display the result
print(f"The square root of {num} is: {square_root}")
Example Output:
Enter a number: 16
The square root of 16.0 is: 4.0
5. Recap on if...break
in the Context of a Loop
Practice Exercise 1 (Basic)
Task:
Write a loop that prints numbers from 1 to 10, but stops when the number 6 is reached using if...break
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Loop through numbers from 1 to 10
for num in range(1, 11):
if num == 6:
print("Breaking the loop at number:", num)
break
print(num)
Example Output:
1
2
3
4
5
Breaking the loop at number: 6
Practice Exercise 2 (Complex)
Task:
Write a program that keeps asking the user to guess a number between 1 and 100. The loop should break once the correct number is guessed.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Set the correct number
correct_number = 42
# Keep asking for guesses until the correct number is guessed
while True: guess = int(input("Guess the number (between 1 and 100): "))
if guess == correct_number:
print("Correct! You've guessed the number.")
break
else:
print("Wrong guess. Try again!")
Example Output:
Guess the number (between 1 and 100): 50
Wrong guess. Try again!
Guess the number (between 1 and 100): 42
Correct! You've guessed the number.
6. Explanation of the Bisection Method
Practice Exercise 1 (Basic)
Task:
Write a program that uses the bisection method to find the square root of a number (you can use any positive number). The program should narrow the search range and stop once the approximation is within a certain tolerance.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Function to find the square root using bisection method
def bisection_method_sqrt(number, tolerance=1e-7, max_iterations=100):
low = 0
high = max(1, number)
root = None
for _ in range(max_iterations):
mid = (low + high) / 2
square_mid = mid ** 2
if abs(square_mid - number) < tolerance:
root = mid
break
elif square_mid < number:
low = mid
else:
high = mid
return root
# Test with the number 25
number = 25
sqrt_result = bisection_method_sqrt(number)
# Display the result
print(f"The square root of {number} is approximately {sqrt_result}")
Example Output:
The square root of 25 is approximately 5.0
Practice Exercise 2 (Complex)
Task:
Write a program that uses the bisection method to find the root of a function, such as f(x)=x2ā4f(x) = x^2 - 4f(x)=x2ā4, where the root is x=2x = 2x=2. The program should narrow the search range to find the root of the function.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Function to find the root of f(x) = x^2 - 4 using bisection method
def bisection_method_root(func, low, high, tolerance=1e-7, max_iterations=100):
root = None
for _ in range(max_iterations):
mid = (low + high) / 2
func_mid = func(mid)
if abs(func_mid) < tolerance:
root = mid
break
elif func_mid < 0:
l ow = mid
else:
high = mid
return root
# Define the function
f(x) = x^2 - 4
def func(x):
return x ** 2 - 4
# Test with the function to find the root between 0 and 5
low = 0
high = 5
root_result = bisection_method_root(func, low, high)
# Display the result
print(f"The root of the function is approximately {root_result}")
Example Output:
The root of the function is approximately 2.0
Coupon Code Generator
1. Importing Python libraries - purpose of re
, secrets
, and string
Basic Practice Exercise:
Task: Import the
string
library and print a list of all uppercase letters and digits.
Your code:
Click here to write code in a Python learning environment.
Example:
import string
# Print uppercase letters and digits
print("Uppercase Letters:", string.ascii_uppercase)
print("Digits:", string.digits)
Explanation:
This exercise uses the string
library to access the ascii_uppercase
and digits
constants. These provide a string of all uppercase English letters and digits, respectively.
Advanced Practice Exercise:
Task: Import the
secrets
library and generate a random number between 1 and 100 usingsecrets.randbelow()
.
Your code:
Click here to write code in a Python learning environment.
Example:
import secrets
# Generate a secure random number
random_number = secrets.randbelow(100) + 1
# Random number between 1 and 100
print("Secure Random Number:", random_number)
Explanation:
This task uses secrets.randbelow()
to generate a random number securely. secrets
is preferred over random
for generating cryptographically secure numbers.
2. Using methods from string libraries
Basic Practice Exercise:
Task: Use
string.ascii_uppercase
andstring.digits
to print a combined string of uppercase letters followed by digits.
Your code:
Click here to write code in a Python learning environment.
Example:
import string
# Combine uppercase letters and digits
combined_string = string.ascii_uppercase + string.digits
print(combined_string)
Explanation:
This exercise combines string.ascii_uppercase
(uppercase letters) and string.digits
(digits) into a single string. The +
operator is used to concatenate them.
Advanced Practice Exercise:
Task: Create a random string of length 10 containing uppercase letters and digits using
secrets.choice()
.
Your code:
Click here to write code in a Python learning environment.
Example:
import secrets
import string
# Generate a random string of length 10
random_string = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
for _ in range(10))
print("Random String:", random_string)
Explanation:
Here, secrets.choice()
is used to select random characters from a combination of uppercase letters and digits. The join()
method then combines these into a single string.
3. Combining Strings
Basic Practice Exercise:
Task: Concatenate two strings using the
+
operator and print the result.
Your code:
Click here to write code in a Python learning environment.
Example:
# Concatenate two strings
str1 = "Hello"
str2 = "World"
combined = str1 + " " + str2
print(combined)
Explanation:
The +
operator is used to combine the two strings, and a space is added between them.
Advanced Practice Exercise:
Task: Combine uppercase letters, digits, and special characters into a single string, ensuring no repetition.
Your code:
Click here to write code in a Python learning environment.
Example:
import string
# Combine uppercase letters, digits, and symbols
combined = string.ascii_uppercase + string.digits + "!@#$%^&*"
print(combined)
Explanation:
In this task, multiple string constants (string.ascii_uppercase
, string.digits
, and a manually defined symbol set) are combined into one string. This demonstrates combining different character sets.
4. Using set()
Basic Practice Exercise:
Task: Create a set containing the numbers 1, 2, and 3, then print the set.
Your code:
Click here to write code in a Python learning environment.
Example:
# Create a set
my_set = {1, 2, 3}
print(my_set)
Explanation:
A set is a collection of unique items. This exercise demonstrates how to create and print a simple set.
Advanced Practice Exercise:
Task: Create a set of unique coupon codes and print the set.
Your code:
Click here to write code in a Python learning environment.
Example:
# Create a set to store unique coupon codes
coupon_set = {"AB123", "XY456", "LM789"}
print("Coupon Codes:", coupon_set)
Explanation:
This task demonstrates how to use a set to store unique coupon codes. Sets automatically remove duplicates.
5. The .add()
Method
Basic Practice Exercise:
Task: Create a set and add an item to it using the
.add()
method.
Your code:
Click here to write code in a Python learning environment.
Example:
# Create a set
my_set = {1, 2, 3}
# Add an item to the set
my_set.add(4)
print(my_set)
Explanation:
The .add()
method is used to add an item to a set. If the item already exists, it will not be added again since sets only store unique items.
Advanced Practice Exercise:
Task: Generate a unique coupon code and add it to a set using
.add()
.
Your code:
Click here to write code in a Python learning environment.
Example:
import secrets
import string
# Generate a random coupon code
coupon_code = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
for _ in range(10))
# Set to store unique coupon codes
coupon_set = set()
# Add the coupon code to the set
coupon_set.add(coupon_code)
print("Coupon Set:", coupon_set)
Explanation:
In this example, a random coupon code is generated and added to a set. Since sets automatically manage uniqueness, duplicate coupon codes will not be added.
6. Recap on a while True
Loop
Basic Practice Exercise:
Task: Write a
while True
loop that prints numbers from 1 to 5 and then exits when the number 5 is printed.
Your code:
Click here to write code in a Python learning environment.
Example:
# Simple while True loop
count = 1
while True:
print(count)
if count == 5:
break
count += 1
Explanation:
This is a basic while True
loop that continues indefinitely until the condition count == 5
is met. The break
statement exits the loop once the condition is true.
Advanced Practice Exercise:
Task: Write a
while True
loop that generates unique coupon codes until it creates one that contains both uppercase letters and digits.
Your code:
Click here to write code in a Python learning environment.
Example:
import secrets
import string
while True:
coupon_code = ''.join(secrets.choice(string.ascii_uppercase + string.digits)
for _ in range(10))
if any(char.isdigit() for char in coupon_code) and any(char.isupper() for char in coupon_code):
print("Valid Coupon Code:", coupon_code)
break
Explanation:
The loop generates coupon codes until one satisfies the condition of containing both uppercase letters and digits. Once the condition is met, the break
statement exits the loop.
7. Using ifā¦in
and ifā¦not in
Basic Practice Exercise:
Task: Create a list of integers and use
ifā¦in
to check if a certain number exists in the list.
Your code:
Click here to write code in a Python learning environment.
Example:
# List of integers
numbers = [1, 2, 3, 4, 5]
# Check if 3 is in the list
if 3 in numbers:
print("3 is in the list!")
Explanation:
This task demonstrates how to use ifā¦in
to check if a specific item exists in a list. If 3
is found in the list, the message "3 is in the list!" is printed.
Advanced Practice Exercise:
Task: Check if a coupon code is already in a set of existing coupon codes using
ifā¦in
.
Your code:
Click here to write code in a Python learning environment.
Example:
# Set of existing coupon codes
existing_coupons = {"AB123", "XY456", "LM789"}
# New coupon code
new_coupon = "AB123"
# Check if the new coupon already exists
if new_coupon in existing_coupons:
print("Coupon code already used.")
else:
print("Coupon code is available.")
Explanation:
In this task, the ifā¦in
condition checks if the new coupon code exists in the set existing_coupons
. If it does, it prints a message indicating that the coupon is already used; otherwise, it indicates that the coupon is available.
8. Tuples (What a tuple is - Purpose - How to write)
Basic Practice Exercise:
Task: Create a tuple containing three items and print it.
Your code:
Click here to write code in a Python learning environment.
Example:
# Create a tuple
my_tuple = (1, 2, 3)
# Print the tuple
print(my_tuple)
Explanation:
A tuple is an ordered, immutable collection of items. This task demonstrates how to create a tuple and print its contents. Unlike lists, tuples cannot be modified after creation.
Advanced Practice Exercise:
Task: Create a tuple containing a string, a number, and a list. Print the tuple and access each element.
Your code:
Click here to write code in a Python learning environment.
Example:
# Create a tuple
my_tuple = ("Coupon", 123, [1, 2, 3])
# Print the entire tuple
print(my_tuple)
# Access elements
print("First element:", my_tuple[0])
print("Second element:", my_tuple[1])
print("Third element (list):", my_tuple[2])
Explanation:
This task demonstrates how to create a tuple with various types of elements (string, number, list). It also shows how to access individual elements within the tuple using indexing. Tuples are immutable, so we can't change the tuple itself, but we can access and use its elements.
9. Regex Library
Basic Practice Exercise:
Task: Use the
re
library to check if a string contains any digits.
Your code:
Click here to write code in a Python learning environment.
Example:
import re
# Sample string
text = "Coupon123"
# Check if there are any digits in the string
if re.search(r'\d', text):
print("The string contains digits.")
else:
print("The string does not contain digits.")
Explanation:
The re.search()
method is used to search for a pattern in a string. The pattern r'\d'
is used to match any digit. If any digits are found in the string, the message "The string contains digits." is printed.
Advanced Practice Exercise:
Task: Use regular expressions to validate a coupon code format (e.g., 3 uppercase letters followed by 3 digits).
Your code:
Click here to write code in a Python learning environment.
Example:
import re
# Sample coupon code
coupon_code = "ABC123"
# Validate coupon format (3 uppercase letters followed by 3 digits)
if re.match(r'^[A-Z]{3}\d{3}$', coupon_code):
print("Valid coupon code.")
else:
print("Invalid coupon code.")
Explanation:
In this task, re.match()
is used to check if the coupon code matches the pattern ^[A-Z]{3}\d{3}$
, which represents three uppercase letters followed by three digits. If the code matches the pattern, it prints "Valid coupon code"; otherwise, it prints "Invalid coupon code."
10. How to Use the all()
Function
Basic Practice Exercise:
Task: Use the
all()
function to check if all numbers in a list are positive.
Your code:
Click here to write code in a Python learning environment.
Example:
# List of numbers
numbers = [1, 2, 3, 4]
# Check if all numbers are positive
if all(num > 0 for num in numbers):
print("All numbers are positive.")
else:
print("Some numbers are not positive.")
Explanation:
The all()
function returns True
if all elements in the iterable satisfy the given condition. In this case, it checks if every number in the list is greater than zero. If they are, the message "All numbers are positive" is printed.
Advanced Practice Exercise:
Task: Use the
all()
function to ensure that a coupon code contains at least one uppercase letter, one digit, and one special character.
Your code:
Click here to write code in a Python learning environment.
Example:
import re
# Sample coupon code
coupon_code = "ABC123@"
# Validate that coupon contains at least one uppercase letter, one digit, and one special character
if all([re.search(r'[A-Z]', coupon_code), re.search(r'\d', coupon_code), re.search(r'[!@#$%^&*]', coupon_code)]):
print("Valid coupon code.")
else:
print("Invalid coupon code.")
Explanation:
In this example, the all()
function checks that the coupon code contains at least one uppercase letter, one digit, and one special character. It uses re.search()
to match each condition. If all conditions are met, it prints "Valid coupon code"; otherwise, it prints "Invalid coupon code."
Pig Latin Translator
1. Recap on Defining Functions
Practice Exercise 1 (Easier)
Task: Write a function called greet()
that prints a greeting message "Hello, World!"
.
Your code:
Click here to write code in a Python learning environment.
Example:
def greet():
print("Hello, World!")
greet()
Practice Exercise 2 (More Complex)
Task: Write a function called add_numbers(a, b)
that returns the sum of two numbers.
Your code:
Click here to write code in a Python learning environment.
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
2. Recap on Returning Values to Functions
Practice Exercise 1 (Easier)
Task: Write a function multiply_by_two()
that takes a number and returns the number multiplied by two.
Your code:
Click here to write code in a Python learning environment.
Example:
def multiply_by_two(number):
return number * 2
result = multiply_by_two(4)
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function rectangle_area(length, width)
that returns the area of a rectangle (length * width).
Your code:
Click here to write code in a Python learning environment.
Example:
def rectangle_area(length, width):
return length * width
area = rectangle_area(5, 3)
print(area)
3. Recap on Conditional Statements
Practice Exercise 1 (Easier)
Task: Write a function is_even()
that takes a number and returns True
if the number is even, False
otherwise.
Your code:
Click here to write code in a Python learning environment.
Example:
def is_even(number):
if number % 2 == 0:
return True
else:
return False
result = is_even(4)
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function check_number_range()
that takes a number and prints whether the number is "low" (less than 10), "medium" (between 10 and 50), or "high" (greater than 50).
Your code:
Click here to write code in a Python learning environment.
Example:
def check_number_range(number):
if number < 10:
return "low"
elif 10 <= number <= 50:
return "medium"
else:
return "high"
result = check_number_range(25)
print(result)
4. Ifā¦in⦠Statements
Practice Exercise 1 (Easier)
Task: Write a function is_present()
that checks if a word exists in a list of words. Return True
if the word is in the list, False
otherwise.
Your code:
Click here to write code in a Python learning environment.
Example:
def is_present(word, word_list):
if word in word_list:
return True
else:
return False
result = is_present("apple", ["banana", "apple", "orange"])
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function find_duplicates()
that takes a list and returns a new list of the duplicated elements.
Your code:
Click here to write code in a Python learning environment.
Example:
def find_duplicates(input_list):
duplicates = []
for item in input_list:
if input_list.count(item) > 1 and item not in duplicates:
duplicates.append(item)
return duplicates
result = find_duplicates([1, 2, 3, 1, 2, 4, 5])
print(result)
5. Using a Simple For Loop for Variable Assignment
Practice Exercise 1 (Easier)
Task: Write a simple for loop that prints each element of a list.
Your code:
Click here to write code in a Python learning environment.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Practice Exercise 2 (More Complex)
Task: Write a for loop that assigns the square of each number in a list to a new list.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5]
squares = []
for number in numbers:
squares.append(number ** 2)
print(squares)
6. For Loops and Temporary Variables
Practice Exercise 1 (Easier)
Task: Write a for loop that iterates over a list of numbers and multiplies each number by 10, printing the result.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3]
for number in numbers:
result = number * 10
print(result)
Practice Exercise 2 (More Complex)
Task: Write a for loop that calculates the cumulative sum of numbers in a list and prints each cumulative sum.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4]
cumulative_sum = 0
for number in numbers:
cumulative_sum += number
print(cumulative_sum)
7. Enumerate() Function
Practice Exercise 1 (Easier)
Task: Write a for loop using enumerate()
that prints the index and value of each item in a list.
Your code:
Click here to write code in a Python learning environment.
Example:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
Practice Exercise 2 (More Complex)
Task: Write a function that accepts a list of names and prints the index and name if the name starts with "A".
Your code:
Click here to write code in a Python learning environment.
Example:
def find_names_with_A(names):
for index, name in enumerate(names):
if name.startswith('A'):
print(f"Index: {index}, Name: {name}")
names = ["Alice", "Bob", "Anna", "Charlie"]
find_names_with_A(names)
8. Taking Characters from String
Practice Exercise 1 (Easier)
Task: Write a function that returns the first character of a string.
Your code:
Click here to write code in a Python learning environment.
Example:
def first_character(word):
return word[0]
result = first_character("hello")
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function that returns the first and last character of a string as a tuple.
Your code:
Click here to write code in a Python learning environment.
Example:
def first_last_char(word):
return (word[0], word[-1])
result = first_last_char("hello")
print(result)
9. String Slicing
Practice Exercise 1 (Easier)
Task: Write a function that returns the substring from the second character to the fourth character of a string.
Your code:
Click here to write code in a Python learning environment.
Example:
def substring(word):
return word[1:4]
result = substring("hello")
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function that returns the first half of a string, slicing it based on the length of the string.
Your code:
Click here to write code in a Python learning environment.
Example:
def first_half(word):
return word[:len(word) // 2]
result = first_half("hello")
print(result)
10. Combining Strings Recap
Practice Exercise 1 (Easier)
Task: Write a function that combines two strings into one sentence, with a space between them.
Your code:
Click here to write code in a Python learning environment.
Example:
def combine_strings(str1, str2):
return str1 + " " + str2
result = combine_strings("Hello", "World")
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function that takes three strings (first name, middle name, and last name) and combines them into a full name, with a space between each part.
Your code:
Click here to write code in a Python learning environment.
Example:
def full_name(first, middle, last):
return first + " " + middle + " " + last
result = full_name("John", "Paul", "Jones")
print(result)
11. Using .split() Method
Practice Exercise 1 (Easier)
Task: Write a function that splits a sentence into words and returns the list of words.
Your code:
Click here to write code in a Python learning environment.
Example:
def split_sentence(sentence):
return sentence.split()
result = split_sentence("Hello world Python is fun")
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function that splits a sentence into words and returns the number of words in the sentence.
Your code:
Click here to write code in a Python learning environment.
Example:
def count_words(sentence):
words = sentence.split()
return len(words)
result = count_words("Hello world Python is fun")
print(result)
12. Recap on Calling Functions (Catching Return Values)
Practice Exercise 1 (Easier)
Task: Write a function add_numbers(a, b)
that adds two numbers and returns the result. Then, call the function and print the result.
Your code:
Click here to write code in a Python learning environment.
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Practice Exercise 2 (More Complex)
Task: Write a function calculate_area(length, width)
that calculates the area of a rectangle and returns the result. Call this function from another function print_area()
that prints the result.
Your code:
Click here to write code in a Python learning environment.
Example:
def calculate_area(length, width):
return length * width
def print_area(length, width):
area = calculate_area(length, width)
print(f"Area of the rectangle: {area}")
print_area(5, 3)
13. Recap on f-Print Statements
Practice Exercise 1 (Easier)
Task: Write a function that prints a sentence with a variable value using an f-string.
Your code:
Click here to write code in a Python learning environment.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Practice Exercise 2 (More Complex)
Task: Write a function that takes a name and age, and prints a message with both values using an f-string.
Your code:
Click here to write code in a Python learning environment.
Example:
def introduction(name, age):
print(f"My name is {name} and I am {age} years old.")
introduction("John", 25)
Graph Representation Converter
1. Dictionaries
Easier Exercise:
Task: Create a dictionary with three key-value pairs: "name": "Alice"
, "age": 30
, and "city": "New York"
. Print the dictionary.
Click here to write code in a Python learning environment
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)
Explanation:
A dictionary in Python is a collection of key-value pairs. You can define a dictionary using curly braces
{}
.Each key is unique, and each key points to a corresponding value.
More Complex Exercise:
Task: Write a Python program to count how many times each letter appears in a string. Use a dictionary to store the frequency of each letter.
Your Code: Click here to write code in a Python learning environment.
Example:
text = "hello"
letter_count = {}
for letter in text:
if letter in letter_count:
letter_count[letter] += 1
else:
letter_count[letter] = 1
print(letter_count)
Explanation:
We loop through the string
text
and check if the letter exists inletter_count
dictionary.If the letter exists, we increment its value. If it doesn't, we add the letter with a value of 1.
2. Using .keys()
Method
Easier Exercise:
Task: Write a Python program that prints all the keys of a given dictionary.
Your Code: Click here to write code in a Python learning environment.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
keys = my_dict.keys()
print(keys)
Explanation:
.keys()
returns a view object that displays a list of all the keys in the dictionary.The output will be a
dict_keys
object which is similar to a list.
More Complex Exercise:
Task: Write a Python program to check if a specific key exists in the dictionary.
Your Code: Click here to write code in a Python learning environment.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
key_to_check = "age"
if key_to_check in my_dict.keys():
print(f"Key '{key_to_check}' found!")
else:
print(f"Key '{key_to_check}' not found.")
Explanation:
You use
.keys()
to check if thekey_to_check
exists in the dictionary.If the key exists, a message is printed; otherwise, another message is printed.
3. Using .items()
Method
Easier Exercise:
Task: Write a program to print both keys and values of a dictionary using the .items()
method.
Your Code: Click here to write code in a Python learning environment.
Example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Explanation:
.items()
returns a view of the dictionaryās items (key-value pairs), which can be iterated over using afor
loop.The loop unpacks each item into
key
andvalue
, allowing access to both.
More Complex Exercise:
Task: Write a program that returns the key with the highest value in a dictionary.
Your Code: Click here to write code in a Python learning environment.
Example:
my_dict = {"Alice": 30, "Bob": 25, "Charlie": 35}
max_key = max(my_dict.items(), key=lambda x: x[1])[0]
print(f"The person with the highest age is {max_key}.")
Explanation:
.items()
returns key-value pairs, andmax()
finds the pair with the highest value usinglambda x: x[1]
.The
[0]
extracts the key associated with the highest value.
4. sorted()
Method
Easier Exercise:
Task: Sort a list of numbers in ascending order.
Your Code: Click here to write code in a Python learning environment.
Example:
numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Explanation:
sorted()
returns a sorted list without modifying the original list. The default order is ascending.The sorted list is printed.
More Complex Exercise:
Task: Sort a list of dictionaries by a specific key.
Your Code: Click here to write code in a Python learning environment.
Example:
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}]
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
Explanation:
The
key
argument ofsorted()
allows sorting by a specific criterionāin this case,"age"
.lambda x: x["age"]
is used to extract the age value from each dictionary for sorting.
5. len()
Method
Easier Exercise:
Task: Write a Python program to find the length of a string.
Your Code: CClick here to write code in a Python learning environment.
Example:
text = "Hello, world!"
print(len(text))
Explanation:
len()
returns the number of characters in the string.It counts spaces, punctuation, and special characters as well.
More Complex Exercise:
Task: Write a Python program to find the length of each list in a list of lists.
Your Code: Click here to write code in a Python learning environment.
Example:
lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
lengths = [len(lst) for lst in lists]
print(lengths)
Explanation:
A list comprehension is used to calculate the length of each list inside the outer list.
len(lst)
returns the length of each inner list, and the result is stored inlengths
.
6. enumerate()
Method
Easier Exercise:
Task: Write a program that iterates over a list and prints each element with its index.
Your Code: Click here to write code in a Python learning environment.
Example:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
Explanation:
enumerate()
provides both the index and the value of the items in the list. It returns a tuple with the index and the element, which can be unpacked intoindex
andfruit
.This allows you to easily access both the index and the value when iterating over a list.
More Complex Exercise:
Task: Write a program that finds the index of a specific item in a list, using enumerate()
.
Your Code: Click here to write code in a Python learning environment.
Example:
fruits = ["apple", "banana", "cherry", "date"]
target_fruit = "cherry"
for index, fruit in enumerate(fruits):
if fruit == target_fruit:
print(f"Found {target_fruit} at index {index}")
break
Explanation:
We use
enumerate()
to loop throughfruits
and compare eachfruit
with thetarget_fruit
.When we find the target fruit, we print the index and stop the loop with
break
.
7. Recap on Using Simple for
Loops
Easier Exercise:
Task: Write a program to multiply all numbers in a list by 2 and store them in a new list.
Your Code: Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5]
doubled = []
for number in numbers:
doubled.append(number * 2)
print(doubled)
Explanation:
A
for
loop is used to iterate through eachnumber
innumbers
.We then multiply each number by 2 and append the result to the
doubled
list.
More Complex Exercise:
Task: Write a program to calculate the cumulative sum of a list of numbers (the sum at each index is the sum of all numbers before it, including itself).
Your Code: Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4]
cumulative_sum = []
current_sum = 0
for number in numbers:
current_sum += number
cumulative_sum.append(current_sum)
print(cumulative_sum)
Explanation:
We initialize
current_sum
to 0. Then, we loop through each number, adding it tocurrent_sum
and appending the result tocumulative_sum
.This gives us a list of running totals.
8. Nested for
Loops
Easier Exercise:
Task: Write a program that prints a multiplication table (from 1 to 3).
Your Code: Click here to write code in a Python learning environment.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
Explanation:
This code uses two nested
for
loops: the outer loop (i
) iterates from 1 to 3, and the inner loop (j
) does the same.For each combination of
i
andj
, the product is printed.
More Complex Exercise:
Task: Write a program to create a 2D matrix (list of lists) where each element is the product of its row and column indices.
Your Code: Click here to write code in a Python learning environment.
Example:
size = 4
matrix = []
for i in range(size):
row = []
for j in range(size):
row.append(i * j)
matrix.append(row)
print(matrix)
Explanation:
The outer
for
loop iterates over rows, and the inner loop iterates over columns.The product of the row and column indices is appended to the current row, and the row is added to the matrix.
9. Explanation on Graph Coding Structure in Computer Science
Easier Exercise:
Task: Represent a simple graph using an adjacency list (dictionary).
Your Code: Click here to write code in a Python learning environment.
Example:
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"] }
print(graph)
Explanation:
A graph is often represented using an adjacency list, where each node (key) has a list of its neighboring nodes (values).
In this case, node
"A"
is connected to nodes"B"
and"C"
, and so on.
More Complex Exercise:
Task: Write a program to find all the neighbors of a specific node in a graph.
Your Code: Click here to write code in a Python learning environment.
Example:
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"] }
node = "A"
neighbors = graph[node]
print(f"Neighbors of {node}: {neighbors}")
Explanation:
We use the dictionary
graph
to retrieve the list of neighbors of a specific node (in this case,"A"
).The program then prints the list of neighbors for that node.
10. Explanation on What an Adjacency List Is
Easier Exercise:
Task: Create a simple graph using an adjacency list representation (dictionary).
Your Code: Click here to write code in a Python learning environment.
Example:
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"] }
print(graph)
Explanation:
An adjacency list is a way to represent a graph, where each key in the dictionary represents a node, and the value is a list of neighboring nodes.
For example, node
"A"
is connected to nodes"B"
and"C"
, and so on for other nodes.
More Complex Exercise:
Task: Write a program that checks if two nodes are connected in an adjacency list.
Your Code: Click here to write code in a Python learning environment.
Example:
graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"] }
def are_connected(graph, node1, node2):
return node2 in graph[node1] or node1 in graph[node2]
print(are_connected(graph, "A", "B")) # True
print(are_connected(graph, "A", "D")) # False
Explanation:
The function
are_connected
checks ifnode1
andnode2
are neighbors by looking up one node's list of neighbors and checking if the other node is present.This helps determine if there is a direct edge between two nodes.
11. Explanation on What an Adjacency Matrix Is
Easier Exercise:
Task: Represent a simple graph using an adjacency matrix.
Your Code: Click here to write code in a Python learning environment.
Example:
# Example of an adjacency matrix for a graph with 4 nodes (A, B, C, D)
# A -> 0, B -> 1, C -> 2, D -> 3
adj_matrix = [ [0, 1, 1, 0], #A's connections
[1, 0, 1, 1], # B's connections
[1, 1, 0, 1], # C's connections
[0, 1, 1, 0] # D's connections
]
for row in adj_matrix: print(row)
Explanation:
An adjacency matrix is a 2D array (matrix) where the rows and columns represent nodes. A
1
indicates that there is an edge between two nodes, and a0
indicates no edge.For example,
adj_matrix[0][1] = 1
means there is an edge between node A (index 0) and node B (index 1).
More Complex Exercise:
Task: Write a program that checks if two nodes are connected using an adjacency matrix.
Your Code: Click here to write code in a Python learning environment.
Example:
# Example adjacency matrix for a graph with 4 nodes (A, B, C, D)
adj_matrix = [ [0, 1, 1, 0], # A's connections
[1, 0, 1, 1], # B's connections
[1, 1, 0, 1], # C's connections
[0, 1, 1, 0] # D's connections
]
def are_connected(matrix, node1, node2):
return matrix[node1][node2] == 1 or matrix[node2][node1] == 1
print(are_connected(adj_matrix, 0, 1)) # True (A-B)
print(are_connected(adj_matrix, 0, 3)) # False (A-D)
Explanation:
This function checks if the nodes (using their indices) are connected by checking if the value at the intersection of their row and column is
1
. This indicates that there's a connection (edge) between the nodes.
12. How to Initialize an Adjacency Matrix with 0's Using For Loops
Easier Exercise:
Task: Write a program to create an empty 4x4 adjacency matrix initialized with 0's.
Your Code: Click here to write code in a Python learning environment.
Example:
size = 4
matrix = [[0 for _ in range(size)] for _ in range(size)]
for row in matrix:
print(row)
Explanation:
We use a nested list comprehension to create a square matrix of size
4x4
, where each element is initialized to0
.This represents a graph with 4 nodes and no edges between them initially.
More Complex Exercise:
Task: Write a program to create an adjacency matrix of any size, initialized with 0's.
Your Code: Click here to write code in a Python learning environment.
Example:
size = int(input("Enter the size of the adjacency matrix: "))
matrix = [[0 for _ in range(size)] for _ in range(size)]
for row in matrix:
print(row)
Explanation:
The program takes the size of the matrix as input and uses a list comprehension to initialize an adjacency matrix of the specified size.
Each element in the matrix is set to
0
, representing no edges between nodes.
13. Adding Items in an Adjacency Matrix Using Indexing
Easier Exercise:
Task: Write a program that adds an edge between two nodes in an adjacency matrix.
Your Code: Click here to write code in a Python learning environment.
Example:
adj_matrix = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]
# Add an edge between node 0 (A) and node 1 (B)
adj_matrix[0][1] = 1
adj_matrix[1][0] = 1
for row in adj_matrix:
print(row)
Explanation:
To add an edge between two nodes in the adjacency matrix, we change the value at the corresponding indices to
1
.Since the matrix is undirected, we set both
adj_matrix[0][1]
andadj_matrix[1][0]
to1
.
More Complex Exercise:
Task: Write a program to add multiple edges to an adjacency matrix.
Your Code: Click here to write code in a Python learning environment.
Example:
adj_matrix = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]
edges = [(0, 1), (1, 2), (2, 3)]
for edge in edges:
node1, node2 = edge
adj_matrix[node1][node2] = 1
adj_matrix[node2][node1] = 1
for row in adj_matrix:
print(row)
Explanation:
The
edges
list contains tuples representing pairs of connected nodes. We iterate over this list and update the adjacency matrix accordingly, marking the presence of edges.
14. Iterating Through Tuples Within a List
Easier Exercise:
Task: Write a program that iterates through a list of tuples and prints both elements of each tuple.
Your Code: Click here to write code in a Python learning environment.
Example:
pairs = [(1, 2), (3, 4), (5, 6)]
for a, b in pairs:
print(f"a: {a}, b: {b}")
Explanation:
We iterate over
pairs
, and for each tuple, the values are unpacked into the temporary variablesa
andb
.This makes it easy to work with each element of the tuple individually within the loop.
More Complex Exercise:
Task: Write a program that sums the first elements and the second elements of a list of tuples separately.
Your Code: Click here to write code in a Python learning environment.
Example:
pairs = [(1, 2), (3, 4), (5, 6)]
sum_first = sum(a for a, b in pairs)
sum_second = sum(b for a, b in pairs)
print(f"Sum of first elements: {sum_first}")
print(f"Sum of second elements: {sum_second}")
Explanation:
We use a generator expression to sum the first and second elements of each tuple separately.
The
sum()
function computes the sum for each set of elements.
15. Adding Items to an Adjacency List Using Nested For Loops
Easier Exercise:
Task: Write a program that creates an empty adjacency list with a size of 4 and adds edges between the nodes using nested loops.
Your Code: Click here to write code in a Python learning environment.
Example:
size = 4
adj_list = {i: [] for i in range(size)}
# Adding edges using nested loops
for i in range(size):
for j in range(i + 1, size):
adj_list[i].append(j)
adj_list[j].append(i)
print(adj_list)
Explanation:
We create an empty adjacency list using a dictionary comprehension where each key (node) maps to an empty list of neighbors.
We then use nested loops to iterate over all pairs of nodes, adding an edge between them (i.e., appending each node to the other node's neighbor list).
More Complex Exercise:
Task: Write a program that creates an adjacency list using nested loops, but only adds edges between nodes if they satisfy a certain condition (e.g., if the sum of the node numbers is even).
Your Code: Click here to write code in a Python learning environment.
Example:
size = 4
adj_list = {i: [] for i in range(size)}
# Adding edges only if the sum of the node numbers is even
for i in range(size):
for j in range(i + 1, size):
if (i + j) % 2 == 0:
adj_list[i].append(j)
adj_list[j].append(i)
print(adj_list)
Explanation:
We again use nested loops to iterate through pairs of nodes. This time, edges are only added if the sum of the node indices is even (i.e.,
(i + j) % 2 == 0
).This introduces conditional logic inside the nested loop to control which edges are added.
16. How to Extract Items from an Adjacency Matrix Using Indexing
Easier Exercise:
Task: Write a program that extracts the value from an adjacency matrix at a given position (e.g., node 0 to node 1).
Your Code: Click here to write code in a Python learning environment.
Example:
adj_matrix = [ [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0] ]
# Extract value for edge between node 0 and node 1
value = adj_matrix[0][1]
print(f"Edge between node 0 and node 1: {value}")
Explanation:
We use indexing (
adj_matrix[0][1]
) to access the value at row 0 and column 1 in the matrix, which represents whether there's an edge between node 0 and node 1.If the value is
1
, thereās an edge; if itās0
, there isnāt.
More Complex Exercise:
Task: Write a program that extracts values from an adjacency matrix for a specific row (all edges for a given node).
Your Code: Click here to write code in a Python learning environment.
Example:
adj_matrix = [ [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0] ]
# Extract values for all edges from node 2
node = 2
edges = adj_matrix[node]
print(f"Edges for node {node}: {edges}")
Explanation:
By accessing
adj_matrix[node]
, we get the entire row corresponding to the edges of the specified node. This tells us which nodes are connected to the given node (node 2 in this case).The output will be a list showing the connections (
[0, 1, 0, 1]
means node 2 is connected to nodes 1 and 3).
17. How to Extract Items from an Adjacency List Using Indexing
Easier Exercise:
Task: Write a program that extracts the list of neighbors for a specific node from an adjacency list.
Your Code: Click here to write code in a Python learning environment.
Example:
adj_list = { 0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [1, 2] }
# Extract neighbors of node 1
neighbors = adj_list[1]
print(f"Neighbors of node 1: {neighbors}")
Explanation:
We use indexing to access the list of neighbors for node
1
by accessingadj_list[1]
. The list[0, 2]
shows that node 1 is connected to nodes 0 and 2.
More Complex Exercise:
Task: Write a program that extracts neighbors for multiple nodes and prints them in a formatted way.
Your Code: CClick here to write code in a Python learning environment.
Example:
adj_list = { 0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [1, 2] }
# Extract and print neighbors for all nodes
for node, neighbors in adj_list.items():
print(f"Neighbors of node {node}: {neighbors}")
Explanation:
We use
.items()
to iterate through the adjacency list, extracting both the node and its neighbors. This allows us to print the neighbors for every node in the graph.
18. Recap on Logic Operators in Conditional Statements
Easier Exercise:
Task: Write a program that uses logical operators (and
, or
, not
) to check if two numbers are both positive or at least one is negative.
Your Code: Click here to write code in a Python learning environment.
Example:
num1 = 5
num2 = -3
# Check if both numbers are positive
if num1 > 0 and num2 > 0:
print("Both numbers are positive.")
else:
print("At least one number is negative.")
Explanation:
The condition
num1 > 0 and num2 > 0
uses theand
operator to check if both numbers are greater than zero.If the condition is
True
, the message "Both numbers are positive" is printed; otherwise, "At least one number is negative" is printed.
More Complex Exercise:
Task: Write a program that checks if two numbers are either both even or both odd using logical operators.
Your Code: Click here to write code in a Python learning environment.
Example:
num1 = 4
num2 = 8
# Check if both numbers are even or both odd
if (num1 % 2 == 0 and num2 % 2 == 0) or (num1 % 2 != 0 and num2 % 2 != 0):
print("Both numbers are either even or both odd.")
else:
print("One number is even, the other is odd.")
Explanation:
The condition uses logical
or
to check two cases: both numbers are even or both are odd.The modulo operator (
%
) is used to check if a number is even (% 2 == 0
) or odd (% 2 != 0
).
19. Catching Two Return Values from a Function Into Two Variables at Once
Easier Exercise:
Task: Write a program that defines a function that returns two values and assigns them to two variables.
Your Code: Click here to write code in a Python learning environment.
Example:
def get_coordinates():
return 5, 10 # Assign the two return values to two variables
x, y = get_coordinates()
print(f"X: {x}, Y: {y}")
Explanation:
The function
get_coordinates
returns two values, which are then unpacked into the variablesx
andy
.This is called tuple unpacking, where the function's return values are automatically assigned to the variables in the same order.
More Complex Exercise:
Task: Write a program that defines a function that returns the sum and difference of two numbers, and assigns the results to two variables.
Your Code: Click here to write code in a Python learning environment.
Example:
def calculate_sum_and_difference(a, b):
return a + b, a - b
# Assign the sum and difference to two variables
sum_result, diff_result = calculate_sum_and_difference(10, 4)
print(f"Sum: {sum_result}, Difference: {diff_result}")
Explanation:
The function
calculate_sum_and_difference
returns both the sum and the difference of two numbers. The return values are unpacked intosum_result
anddiff_result
for further use.This technique allows for returning multiple values from a function in a clean and concise manner.
Maze Solver
1. Recap on Accessing Elements of Lists through Indexes
Practice Exercise 1 (Easier):
Access the second element in a list of fruits.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given list
fruits = ["apple", "banana", "cherry", "date"]
# Access the second element
second_fruit = fruits[1]
print("Second fruit:", second_fruit)
Practice Exercise 2 (More Complex):
Access the last element of a list without knowing its length.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given list fruits = ["apple", "banana", "cherry", "date"]
# Access the last element
last_fruit = fruits[-1]
print("Last fruit:", last_fruit)
2. What is a 2D Array and How Do We Create Them in Python
Practice Exercise 1 (Easier):
Create a 2D array (list of lists) to represent a 3x3 grid of zeros.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Create a 2D array
grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
print("2D Array:", grid)
Practice Exercise 2 (More Complex):
Create a 2D array of size 4x4 where the diagonal elements are 1, and the rest are 0.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Create a 4x4 2D array with 1s on the diagonal
grid = [[1 if i == j else 0 for j in range(4)] for i in range(4)]
print("2D Array:", grid)
3. How to Access Elements from a 2D Array (Tuple within List) Using Indexing
Practice Exercise 1 (Easier):
Access the first row and the first element of a 2D array.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given 2D array
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Access the first element of the first row
first_element = matrix[0][0]
print("First element:", first_element)
Practice Exercise 2 (More Complex):
Access all elements in the last column of a 2D array.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given 2D array
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Access the last column
last_column = [row[-1] for row in matrix]
print("Last column:", last_column)
4. Recap on .append Method
Practice Exercise 1 (Easier):
Append a new fruit to an existing list of fruits.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given list
fruits = ["apple", "banana", "cherry"]
# Append a new fruit
fruits.append("date")
print("Updated list:", fruits)
Practice Exercise 2 (More Complex):
Create a list of even numbers from 1 to 10 using .append()
inside a loop.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Create an empty list
even_numbers = []
# Append even numbers
for number in range(1, 11):
if number % 2 == 0:
even_numbers.append(number)
print("Even numbers:", even_numbers)
5. If Statements with Boolean Values
Practice Exercise 1 (Easier):
Check if a variable is_sunny
is True
and print "Go outside!" if it is.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given boolean
is_sunny = True
# Check the condition
if is_sunny:
print("Go outside!")
Practice Exercise 2 (More Complex):
Check if a number is positive, negative, or zero using nested if
statements.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given number
number = -5
# Check conditions
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else: print("Zero")
6. Recap on Using and/or/not in Conditionals
Practice Exercise 1 (Easier):
Check if a number is both greater than 10 and even using and
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given number
number = 12
# Check condition
if number > 10 and number % 2 == 0:
print("The number is greater than 10 and even.")
Practice Exercise 2 (More Complex):
Check if a number is either less than 5 or greater than 20 using or
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Given number
number = 25
# Check condition
if number < 5 or number > 20:
print("The number is either less than 5 or greater than 20.")
7. Calling Functions Within If Statements
Practice Exercise 1 (Easier):
Create a function is_even(n)
that returns True
if n
is even and use it inside an if
statement.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define function
def is_even(n):
return n % 2 == 0
# Call function inside if statement
number = 4
if is_even(number):
print("The number is even.")
Practice Exercise 2 (More Complex):
Create a function is_adult(age)
that returns True
if age is 18 or older, then use it in an if-else statement to print a message.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define function
def is_adult(age):
return age >= 18
# Call function inside if statement
age = 16
if is_adult(age):
print("You are an adult.")
else:
print("You are not an adult yet.")
8. Returning Values to Functions Within If Statements
Practice Exercise 1 (Easier):
Write a function is_positive(n)
that returns True
if n
is positive and False
otherwise. Use it inside an if statement.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define function
def is_positive(n):
return n > 0
# Call function inside if statement
number = -3
if is_positive(number):
print("Positive number")
else:
print("Not a positive number")
Practice Exercise 2 (More Complex):
Write a function can_vote(age)
that returns True
if age
is 18 or older; otherwise, return False
. Use it inside an if-else statement.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define function
def can_vote(age):
return True if age >= 18 else False
# Call function inside if statement
age = 20
if can_vote(age):
print("You can vote!")
else:
print("You cannot vote yet.")
9. Detailed Explanation on Recursion (What Recursion Is - How It Works)
Practice Exercise 1 (Easier):
Write a recursive function countdown(n)
that prints numbers from n
to 1
, then prints "Done!"
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define recursive function
def countdown(n):
if n <= 0:
print("Done!")
return
print(n)
countdown(n - 1)
# Call function
countdown(5)
Practice Exercise 2 (More Complex):
Write a recursive function factorial(n)
that returns the factorial of n
(n! = n Ć (n-1) Ć ... Ć 1).
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define recursive function
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
# Call function
print(factorial(5)) # Output: 120
10. Preventing an Infinite Loop in Recursion
Practice Exercise:
Modify the factorial(n)
function to include an error check that prevents negative values from causing an infinite loop.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define recursive function
def factorial(n):
if n < 0:
return "Error: Factorial is not defined for negative numbers."
if n == 0:
return 1
return n * factorial(n - 1)
# Call function
print(factorial(-5)) # Output: Error message
11. How to Know When to Use Recursion in Code and How to Go About It
Practice Exercise 1 (Easier):
Write a recursive function sum_digits(n)
that returns the sum of the digits of n
.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define recursive function
def sum_digits(n):
if n < 10:
return n
return n % 10 + sum_digits(n // 10)
# Call function
print(sum_digits(1234)) # Output: 10
Practice Exercise 2 (More Complex):
Write a recursive function reverse_string(s)
that reverses a string.
Your Code:
Click here to write code in a Python learning environment.
Example:
# Define recursive function
def reverse_string(s):
if len(s) == 0:
return s
return s[-1] + reverse_string(s[:-1])
# Call function
print(reverse_string("hello")) # Output: "olleh"
Quick sort
1. What a Sorting Algorithm Is
A sorting algorithm is a way to arrange items in a list (like numbers or words) in a particular order, such as ascending or descending.
Practice Exercise (Basic)
Task: Given the list nums = [4, 2, 9, 1]
, use Pythonās built-in sorted()
function to sort the numbers in ascending order and print the result.
Your Code:
Click here to write code in a Python learning environment.
Example:
nums = [4, 2, 9, 1]
sorted_nums = sorted(nums)
print(sorted_nums)
Practice Exercise (More Complex)
Task: Given the list words = ["banana", "apple", "pear"]
, use sorted()
to sort the words in reverse alphabetical order.
Your Code:
Click here to write code in a Python learning environment.
Example:
words = ["banana", "apple", "pear"]
sorted_words = sorted(words, reverse=True)
print(sorted_words)
2. Recap on Simple For Loops in Variable Assignment
Practice Exercise (Basic)
Task: Create a new list called squares
that stores the square of each number in the list [1, 2, 3]
, using a single line of code.
Your Code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3]
squares = [num * num for num in numbers]
print(squares)
Practice Exercise (More Complex)
Task: Loop through the list [2, 4, 6, 8, 9, 11]
and create a new list called even_doubles
that stores only the even numbers from the list, each multiplied by 2 ā all using a one-line for
loop with a condition.
Your Code:
Click here to write code in a Python learning environment.
Example:
numbers = [2, 4, 6, 8, 9, 11]
even_doubles = [num * 2 for num in numbers if num % 2 == 0]
print(even_doubles)
3. Recap on Extracting a Section from a List
Practice Exercise (Basic)
Task: Print the first three elements of the list [5, 10, 15, 20, 25]
.
Your Code:
Click here to write code in a Python learning environment.
Example:
nums = [5, 10, 15, 20, 25]
print(nums[0:3])
Practice Exercise (More Complex)
Task: From the list ["a", "b", "c", "d", "e", "f"]
, create a new list called middle
that contains the elements from index 2 to index 4 (inclusive of 2, but not 5), then print it.
Your Code:
Click here to write code in a Python learning environment.
Example:
letters = ["a", "b", "c", "d", "e", "f"]
middle = letters[2:5]
print(middle)
4. Syntax for Extracting a Section from a List Either Till the End or From the Beginning
Practice Exercise (Basic)
Task: From the list nums = [10, 20, 30, 40, 50]
, print all values from the start until index 3 (not including index 3).
Your Code:
Click here to write code in a Python learning environment.
Example:
nums = [10, 20, 30, 40, 50]
print(nums[:3])
Practice Exercise (More Complex)
Task: From the list nums = [100, 200, 300, 400, 500]
, create a new list called last_half
that includes all elements starting from index 2 to the end. Print last_half
.
Your Code:
Click here to write code in a Python learning environment.
Example:
nums = [100, 200, 300, 400, 500]
last_half = nums[2:]
print(last_half)
5. Recap on How to Access the Last Element from a List
Practice Exercise (Basic)
Task: Print the last item from the list fruits = ["apple", "banana", "cherry"]
.
Your Code:
Click here to write code in a Python learning environment.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
Practice Exercise (More Complex)
Task: From the list temperatures = [72, 75, 78, 80, 77]
, store the last value in a variable called latest_temp
and print it with the sentence: The latest temperature is X degrees.
Your Code:
Click here to write code in a Python learning environment.
Example:
temperatures = [72, 75, 78, 80, 77]
latest_temp = temperatures[-1]
print(f"The latest temperature is {latest_temp} degrees.")
6. Recap on Returning Values to Functions Within Conditional Statements
Practice Exercise (Basic)
Task: Define a function called check_even
that takes one number as a parameter. If the number is even, return "Even"
. If not, return "Odd"
.
Your Code:
Click here to write code in a Python learning environment.
Example:
def check_even(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
print(check_even(4))
Practice Exercise (More Complex)
Task: Define a function called grade_result
that takes a number and returns "Pass"
if the number is greater than or equal to 50, and "Fail"
otherwise. Test it with two different values.
Your Code:
Click here to write code in a Python learning environment.
Example:
def grade_result(score):
if score >= 50:
return "Pass"
else:
return "Fail"
print(grade_result(75))
print(grade_result(42))
7. Recap on Recursion
Recursion is when a function calls itself in order to solve a smaller version of a problem.
Practice Exercise (Basic)
Task: Write a function called countdown
that prints numbers starting from a given number down to 1 using recursion.
Your Code:
Click here to write code in a Python learning environment.
Example:
def countdown(n):
if n <= 0:
return
print(n)
countdown(n - 1)
countdown(3)
Practice Exercise (More Complex)
Task: Define a function called sum_to_n
that uses recursion to return the sum of all numbers from n
down to 1. (e.g. sum_to_n(5) returns 15)
Your Code:
Click here to write code in a Python learning environment.
Example:
def sum_to_n(n):
if n == 1:
return 1
else:
return n + sum_to_n(n - 1)
print(sum_to_n(5))
8. Use of Recursion in Sorting Algorithms
This task is focused on recognizing how recursion is used, rather than writing the full algorithm yet.
Practice Exercise (Basic)
Task: Look at the function below. What is the purpose of the recursive call? Fill in the missing word in the comment:
# This function calls itself to handle a ___________ part of the problem.
def example(n):
if n <= 1:
return
print(n)
example(n - 1)
Your Code:
Click here to write code in a Python learning environment.
Example:
# This function calls itself to handle a smaller part of the problem.
Practice Exercise (More Complex)
Task: In your own words (in a comment), explain how recursion might be useful in breaking down a sorting problem (e.g. dividing a list into smaller chunks). Use this template:
# Sorting a list with recursion means...
Your Code:
Click here to write code in a Python learning environment.
Example:
# Sorting a list with recursion means breaking it into smaller parts,
# sorting those parts, and then combining them into a full sorted list.
9. How the Quick Sort Algorithm Works
(Note: No coding required yet, this is a theory-based task to understand the concept.)
Practice Exercise (Basic)
Task: Read the following steps and fill in the blanks with the correct keywords:
Choose a ________ element from the list.
Divide the remaining elements into two ________: one with values less than the pivot and one with values greater than the pivot.
________ step 1 and 2 for the smaller lists until they contain only one element.
Your Code:
Click here to write code in a Python learning environment.
Example:
# 1. Choose a pivot element from the list.
# 2. Divide the remaining elements into two parts: one with values less than the pivot and one with values greater than the pivot.
# 3. Repeat step 1 and 2 for the smaller lists until they contain only one element.
Practice Exercise (More Complex)
Task: In your own words, describe why recursion is helpful in quick sort. Use this format:
# Recursion is useful in quick sort because...
Your Code:
Click here to write code in a Python learning environment.
Example:
# Recursion is useful in quick sort because it allows the function to repeatedly break the list
# into smaller parts and sort them individually, then combine the results for the full list.
10. Using Recursion Within a Return to a Function
Practice Exercise (Basic)
Task: Create a recursive function called multiply
that multiplies two numbers by repeated addition. Only use addition and recursion (no *
operator).
Your Code:
Click here to write code in a Python learning environment.
Example:
def multiply(a, b):
if b == 0:
return 0
return a + multiply(a, b - 1)
print(multiply(3, 4)) # Outputs: 12
Practice Exercise (More Complex)
Task: Write a recursive function called power(base, exponent)
that returns base
raised to the power of exponent
using recursion and a return statement.
Your Code:
Click here to write code in a Python learning environment.
Example:
def power(base, exponent):
if exponent == 0:
return 1
return base * power(base, exponent - 1)
print(power(2, 3)) # Outputs: 8
Tic-Tac-Toe Game
What a Class Is
Practice Exercise 1 (Easier Task):
Create a basic class called Dog
with no methods. The class should simply have one attribute: name
.
Your code:
Click here to write code in a Python learning environment.
Example:
class Dog:
name = "Buddy"
dog = Dog()
print(dog.name)
Practice Exercise 2 (More Complex Task):
Create a class called Car
with two attributes: make
and model
. Add a method describe()
that prints the carās details.
Your code:
Click here to write code in a Python learning environment.
Example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
print(f"This is a {self.make} {self.model}")
car = Car("Toyota", "Camry")
car.describe()
2. What an Object Is
Practice Exercise 1 (Easier Task):
Create an instance (object) of the Dog
class from the first exercise and print the name
attribute.
Your code:
Click here to write code in a Python learning environment.
Example:
dog = Dog()
print(dog.name) # Output: Buddy
Practice Exercise 2 (More Complex Task):
Create multiple Car
objects with different make
and model
values and use the describe()
method to display each car's details.
Your code:
Click here to write code in a Python learning environment.
Example:
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
car1.describe()
car2.describe()
3. The Self Keyword and the Constructor Method
Practice Exercise 1 (Easier Task):
Define a Person
class with a name
attribute in the constructor. Create an instance of Person
and print the name
.
Your code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name):
self.name = name
person = Person("Alice")
print(person.name)
Practice Exercise 2 (More Complex Task):
Create a Book
class with a constructor that takes title
and author
as parameters. Create an object of Book
and display the book details.
Your code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def show_details(self):
print(f"Title: {self.title}, Author: {self.author}")
book = Book("1984", "George Orwell")
book.show_details()
4. Accessing Object Attributes
Practice Exercise 1 (Easier Task):
Create a Car
object with an attribute color
and print its value.
Your code:
Click here to write code in a Python learning environment.
Example:
class Car:
def __init__(self, color):
self.color = color
car = Car("Red")
print(car.color)
Practice Exercise 2 (More Complex Task):
Create a Laptop
class with brand
and model
attributes. Create an object of Laptop
and access both attributes.
Your code:
Click here to write code in a Python learning environment.
Example:
class Laptop:
def __init__(self, brand, model):
self.brand = brand
self.model = model
laptop = Laptop("Dell", "XPS 13")
print(f"Brand: {laptop.brand}, Model: {laptop.model}")
5. Variables Inside a Class (+ Scope of the Variables Inside a Class)
Practice Exercise 1 (Easier Task):
Create a Fruit
class with an attribute color
and print its value. Define the attribute inside the constructor.
Your code:
Click here to write code in a Python learning environment.
Example:
class Fruit:
def __init__(self, color):
self.color = color
fruit = Fruit("Yellow")
print(fruit.color)
Practice Exercise 2 (More Complex Task):
Create a Person
class with an attribute age
. Add a method greet()
that prints a greeting message using self.name
and self.age
. Create an object and call the method.
Your code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person = Person("Bob", 30)
person.greet()
6. Methods (Functions Inside a Class)
Practice Exercise 1 (Easier Task):
Define a Dog
class with a method bark()
that prints "Woof!". Create an object and call bark()
.
Your code:
Click here to write code in a Python learning environment.
Example:
class Dog:
def bark(self):
print("Woof!")
dog = Dog()
dog.bark()
Practice Exercise 2 (More Complex Task):
Create a BankAccount
class with methods deposit()
and withdraw()
. Use the deposit()
method to add money to the account and the withdraw()
method to subtract money.
Your code:
Click here to write code in a Python learning environment.
Example:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient funds")
account = BankAccount()
account.deposit(100)
account.withdraw(50)
print(account.balance)
7. How to Initialize and Display a Grid Within a Class (2D Array)
Practice Exercise 1 (Easier Task):
Create a Grid
class that initializes a 3x3 grid (2D array) filled with zeros and displays it.
Your code:
Click here to write code in a Python learning environment.
Example:
class Grid:
def __init__(self):
self.grid = [[0 for _ in range(3)] for _ in range(3)]
def display(self):
for row in self.grid:
print(row)
grid = Grid()
grid.display()
Practice Exercise 2 (More Complex Task):
Create a Matrix
class that initializes a grid based on the user's input size (rows and columns). Display the grid in a formatted way.
Your code:
Click here to write code in a Python learning environment.
Example:
class Matrix:
def __init__(self, rows, cols):
self.grid = [[0 for _ in range(cols)] for _ in range(rows)]
def display(self):
for row in self.grid:
print(" ".join(map(str, row)))
matrix = Matrix(4, 5)
matrix.display()
8. Using Range() Specifically in For Loops
Practice Exercise 1 (Easier Task):
Write a for
loop using range()
to print the numbers from 0 to 4.
Your code:
Click here to write code in a Python learning environment.
Example:
for i in range(5):
print(i)
Practice Exercise 2 (More Complex Task):
Write a for
loop that prints all even numbers from 0 to 20 using range()
with a step value of 2.
Your code:
Click here to write code in a Python learning environment.
Example:
for i in range(0, 21, 2):
print(i)
9. Using All()
Practice Exercise 1 (Easier Task):
Write a Python code using the all()
function to check if all elements in a list of numbers are positive.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4]
result = all(num > 0 for num in numbers)
print(result) # Output: True
Practice Exercise 2 (More Complex Task):
Create a list of lists and use all()
to check if all the numbers in each inner list are positive.
Your code:
Click here to write code in a Python learning environment.
Example:
lists = [[1, 2, 3], [4, -5, 6], [7, 8, 9]]
result = all(all(num > 0 for num in inner_list) for inner_list in lists)
print(result) # Output: False
10. Recap on Python Operators (== , >, <=, etc.)
Practice Exercise 1 (Easier Task):
Use comparison operators (==
, >
) to check if two numbers are equal and if one number is greater than the other.
Your code:
Click here to write code in a Python learning environment.
Example:
a = 5
b = 10
print(a == b) # Output: False
print(a > b) # Output: False
Practice Exercise 2 (More Complex Task):
Write a program that checks if a number is within a specific range using >=
and <=
operators, and prints the result.
Your code:
Click here to write code in a Python learning environment.
Example:
number = 7
if 5 <= number <= 10:
print("Number is in the range.")
else:
print("Number is out of range.")
11. Assigning Attributes Within a Class as Other Objects
Practice Exercise 1 (Easier Task):
Create a class called Library
and assign an object of the Book
class as an attribute to it. Print the bookās title using the object attribute.
Your code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title):
self.title = title
class Library:
def __init__(self, book):
self.book = book
book = Book("1984")
library = Library(book)
print(library.book.title)
Practice Exercise 2 (More Complex Task):
Create a Course
class that assigns an object of Instructor
as an attribute. The Instructor
class should have a method to display the instructor's name.
Your code:
Click here to write code in a Python learning environment.
Example:
class Instructor:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Instructor: {self.name}")
class Course:
def __init__(self, instructor):
self.instructor = instructor
instructor = Instructor("Mr. Smith")
course = Course(instructor)
course.instructor.display_name()
12. Using Simple If Else Statements Within Variable Assignment
Practice Exercise 1 (Easier Task):
Assign a value to a variable using an if
statement based on a simple condition.
Your code:
Click here to write code in a Python learning environment.
Example:
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
Practice Exercise 2 (More Complex Task):
Write a program that assigns a grade based on a test score using if-elif-else
statements.
Your code:
Click here to write code in a Python learning environment.
Example:
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(f"Grade: {grade}")
13. Using While Not
Practice Exercise 1 (Easier Task):
Write a while
loop that runs as long as a variable is not equal to 5.
Your code:
Click here to write code in a Python learning environment.
Example:
count = 0
while count != 5:
print(count)
count += 1
Practice Exercise 2 (More Complex Task):
Write a program that continues prompting for a valid number (between 1 and 10) until the user enters a valid input using a while
loop.
Your code:
Click here to write code in a Python learning environment.
Example:
while True:
number = int(input("Enter a number between 1 and 10: "))
if 1 <= number <= 10:
print("Valid number!")
break
else:
print("Invalid number, try again.")
14. Assigning Values to Two Variables at Once
Practice Exercise 1 (Easier Task):
Assign two values to two variables in one line.
Your code:
Click here to write code in a Python learning environment.
Example:
x, y = 10, 20
print(x, y)
Practice Exercise 2 (More Complex Task):
Swap the values of two variables without using a third temporary variable.
Your code:
Click here to write code in a Python learning environment.
Example:
x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10, 5
15. Using Map()
Practice Exercise 1 (Easier Task):
Use map()
to square each number in a list of numbers.
Your code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
Practice Exercise 2 (More Complex Task):
Use map()
to convert a list of strings to uppercase.
Your code:
Click here to write code in a Python learning environment.
Example:
words = ["hello", "world", "python"]
uppercase_words = list(map(str.upper, words))
print(uppercase_words)
16. Using .split()
Practice Exercise 1 (Easier Task):
Use .split()
to separate a string into a list of words.
Your code:
Click here to write code in a Python learning environment.
Example:
sentence = "Python is awesome"
words = sentence.split()
print(words)
Practice Exercise 2 (More Complex Task):
Use .split()
to split a comma-separated string of values into a list and then print each item individually.
Your code:
Click here to write code in a Python learning environment.
Example:
data = "apple,banana,cherry"
items = data.split(",")
for item in items:
print(item)
17. Nested Conditional Statements
Practice Exercise 1 (Easier Task):
Write a program that checks if a number is positive, negative, or zero using if-elif-else
statements.
Your code:
Click here to write code in a Python learning environment.
Example:
number = -5
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
Practice Exercise 2 (More Complex Task):
Write a program that checks if a studentās grade falls within certain ranges, and assigns a letter grade based on multiple conditions.
Your code:
Click here to write code in a Python learning environment.
Example:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
18. How to Use Objects Throughout Code
Practice Exercise 1 (Easier Task):
Create an object of a class and call a method of that object.
Your code:
Click here to write code in a Python learning environment.
Example:
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} says woof!")
dog = Dog("Buddy")
dog.speak()
Practice Exercise 2 (More Complex Task):
Create an object of a Person
class with a method that calculates the age of the person based on their birth year. Call this method after creating the object.
Your code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
def calculate_age(self, current_year):
return current_year - self.birth_year
person = Person("Alice", 1990)
age = person.calculate_age(2024)
print(f"{person.name} is {age} years old.")
Phone Book
1. Recap on Objects
Easier Exercise: Creating and Accessing an Object
Task: Create a class called Car
with attributes like make
, model
, and year
. Create an object of the class and print its attributes.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2020
More Complex Exercise: Modifying Object Attributes
Task: Create a class called Book
with attributes title
, author
, and pages
. Then, create a method to update the number of pages in a book and print the updated details.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def update_pages(self, new_pages):
self.pages = new_pages
my_book = Book("1984", "George Orwell", 328)
my_book.update_pages(350)
print(f"{my_book.title} by {my_book.author} has {my_book.pages} pages.") # Output: 1984 by George Orwell has 350 pages.
2. Recap on Classes
Easier Exercise: Creating a Simple Class
Task: Create a class called Person
that has attributes for name
and age
. Initialize them and print them.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 25)
print(p1.name) # Output: John
print(p1.age) # Output: 25
More Complex Exercise: Adding Methods to a Class
Task: Create a class called Student
with attributes name
, age
, and grade
. Add a method that returns a string showing whether the student passed or failed based on their grade.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def pass_or_fail(self):
if self.grade >= 50:
return f"{self.name} passed!"
else:
return f"{self.name} failed."
s1 = Student("Alice", 20, 45)
print(s1.pass_or_fail()) # Output: Alice failed.
3. Recap on Accessing Attributes of Objects
Easier Exercise: Accessing an Attribute
Task: Create a class called Animal
with an attribute species
. Access and print this attribute.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Animal:
def __init__(self, species):
self.species = species
a1 = Animal("Dog")
print(a1.species) # Output: Dog
More Complex Exercise: Modifying an Attribute Based on Conditions
Task: Create a class called Employee
with an attribute salary
. Create a method that checks if the salary is above a certain threshold and prints a message accordingly.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def check_salary(self):
if self.salary > 50000:
return f"{self.name} has a high salary."
else:
return f"{self.name} has a low salary."
e1 = Employee("John", 60000)
print(e1.check_salary()) # Output: John has a high salary.
4. Recap on Constructor Method
Easier Exercise: Using the Constructor to Initialize Attributes
Task: Create a class called Rectangle
with attributes length
and width
. Initialize them using the constructor and print the area.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
rect = Rectangle(5, 3)
print(f"Area: {rect.area()}") # Output: Area: 15
More Complex Exercise: Using the Constructor for Multiple Objects
Task: Create a class Book
with attributes title
, author
, and year
. Initialize multiple objects and print their details.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
book1 = Book("1984", "George Orwell", 1949)
book2 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
print(f"{book1.title} by {book1.author}, published in {book1.year}")
print(f"{book2.title} by {book2.author}, published in {book2.year}")
5. Helper Functions/Nested Functions
Easier Exercise: Nested Function Example
Task: Write a function that calculates the square of a number using a helper function inside the main function.
Your Code:
Click here to write code in a Python learning environment.
Example:
def square_number(x):
def square(y):
return y * y
return square(x)
print(square_number(5)) # Output: 25
More Complex Exercise: Using a Helper Function to Sum Numbers in a List
Task: Write a function that takes a list of numbers and returns the sum using a nested helper function.
Your Code:
Click here to write code in a Python learning environment.
Example:
def sum_numbers(numbers):
def helper_sum(nums):
total = 0
for num in nums:
total += num
return total
return helper_sum(numbers)
print(sum_numbers([1, 2, 3, 4])) # Output: 10
6. Passing Parameters into Methods Being Used on an Object
Easier Exercise: Passing Parameters into Methods
Task: Create a class Person
with a method greet
that takes a name
parameter and prints a greeting.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Person: def greet(self, name): print(f"Hello, {name}!") p1 = Person() p1.greet("Alice") # Output: Hello, Alice!
More Complex Exercise: Passing Multiple Parameters to Update Attributes
Task: Create a class Account
with attributes balance
and owner_name
. Create a method deposit
that accepts the amount to deposit and updates the balance.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Account:
def __init__(self, owner_name, balance):
self.owner_name = owner_name
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"New balance: {self.balance}")
acc = Account("John", 500)
acc.deposit(150) # Output: New balance: 650
7. Recap on Using if...is None
Easier Exercise: Checking if a Variable is None
Task: Write a function that checks if an input is None
and prints a message if it is.
Your Code:
Click here to write code in a Python learning environment.
Example:
def check_none(value):
if value is None:
print("Value is None")
else: print("Value is not None")
check_none(None) # Output: Value is None
check_none(5) # Output: Value is not None
More Complex Exercise: Checking Object Attributes for None
Task: Create a class Person
with an attribute phone_number
. Write a method that checks if phone_number
is None
and prints a message accordingly.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name, phone_number=None):
self.name = name
self.phone_number = phone_number
def check_phone(self):
if self.phone_number is None:
print(f"{self.name} does not have a phone number.")
else:
print(f"{self.name}'s phone number is {self.phone_number}")
p1 = Person("Alice")
p1.check_phone() # Output: Alice does not have a phone number.
8. Returning Values to Functions with if else
Statements
Easier Exercise: Using if else
for Return Statements
Task: Write a function that returns "Positive" if a number is greater than zero, otherwise returns "Non-positive".
Your Code:
Click here to write code in a Python learning environment.
Example:
def check_number(num):
if num > 0:
return "Positive"
else:
return "Non-positive"
print(check_number(5)) # Output: Positive
print(check_number(-3)) # Output: Non-positive
More Complex Exercise: Using if else
with Multiple Conditions
Task: Write a function that returns the highest value from three numbers using if else
.
Your Code:
Click here to write code in a Python learning environment.
Example:
def find_max(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(find_max(1, 3, 2)) # Output: 3
9. What is a Binary Search Tree and How Does it Work?
Easier Exercise: Understanding Binary Search Tree Logic
Task: Imagine you have a list of numbers. Manually describe how a binary search tree would organize these numbers: 50, 30, 70, 20, 40, 60, 80
.
Your Code:
Click here to write code in a Python learning environment.
Example:
First, 50 will be the root. Then 30 goes to the left of 50, as itās smaller. 70 goes to the right of 50, as itās larger. 20 is less than both 50 and 30, so it goes to the left of 30. 40 is greater than 30 but less than 50, so it goes to the right of 30. 60 is less than 70 but greater than 50, so it goes to the left of 70. Finally, 80 goes to the right of 70.
More Complex Exercise: Writing a Function to Insert into a Binary Search Tree
Task: Write a Python function to insert a number into a binary search tree (BST). The function should return the updated tree.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_bst(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert_bst(root.left, value)
else:
root.right = insert_bst(root.right, value)
return root
# Example of use
root = Node(50)
root = insert_bst(root, 30)
root = insert_bst(root, 70)
root = insert_bst(root, 20)
root = insert_bst(root, 40)
10. Recap on Recursion
Easier Exercise: Basic Recursion Example
Task: Write a recursive function that prints the numbers from 1 to n
(inclusive). The function should print the number and then call itself with n-1
.
Your Code:
Click here to write code in a Python learning environment.
Example:
def print_numbers(n):
if n == 0:
return print(n)
print_numbers(n-1)
print_numbers(5) # Output: 5 4 3 2 1
More Complex Exercise: Factorial Calculation Using Recursion
Task: Write a recursive function to calculate the factorial of a number n
. The factorial of a number is the product of all positive integers less than or equal to n
.
Your Code:
Click here to write code in a Python learning environment.
Example:
def factorial(n):
if n == 0: # Base case
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
11. Difficult Binary Search Tree Concepts - Overlapping Classes
Easier Exercise: Understanding How One Class Can Affect Another
Task: Create a simple class structure with two classes: Book
and Library
. The Library
class should have a method to add a book, and the Book
class should have a method that prints the book's title. This will demonstrate how an instance of Book
can be accessed from Library
.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title):
self.title = title
def print_title(self):
print(f"Book title: {self.title}")
class Library:
def __init__(self):
self.books = []
def add_book(self, title):
new_book = Book(title)
self.books.append(new_book)
new_book.print_title() # Using an attribute of Book inside Library method
# Example of use
library = Library()
library.add_book("The Great Gatsby") # Output: Book title: The Great Gatsby
More Complex Exercise: Working with Overlapping Classes and Recursion
Task: Create two classes: Person
and Group
. The Group
class will have a method that adds Person
objects and uses recursion to go through a list of people and print their names. The method will use a class attribute from Person
within the Group
class.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print(f"Hello, my name is {self.name}.")
class Group:
def __init__(self):
self.members = []
def add_member(self, person):
self.members.append(person)
def introduce_members(self, index=0):
if index < len(self.members):
self.members[index].introduce() # Accessing Person's method from Group
self.introduce_members(index + 1) # Recursion to introduce the next person # Example of use
person1 = Person("Alice")
person2 = Person("Bob")
person3 = Person("Charlie")
group = Group()
group.add_member(person1)
group.add_member(person2)
group.add_member(person3)
group.introduce_members() # Output: Hello, my name is Alice. Hello, my name is Bob. Hello, my name is
Charlie.
12. Recursion in a Binary Search Tree
Easier Exercise: Recursion for Tree Traversal
Task: Write a recursive function to print the values of a binary search tree (BST) in in-order traversal (left subtree, root, right subtree).
Your Code:
Click here to write code in a Python learning environment.
Example:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def in_order_traversal(root):
if root is not None:
in_order_traversal(root.left)
print(root.value, end=" ")
in_order_traversal(root.right)
# Example use
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.left.left = Node(20)
root.left.right = Node(40)
in_order_traversal(root) # Output: 20 30 40 50 70
More Complex Exercise: Recursion for Searching a Value in a BST
Task: Write a recursive function that searches for a value in a binary search tree. The function should return True
if the value is found and False
if itās not.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def search_bst(root, value):
if root is None:
return False
if root.value == value:
return True
elif value < root.value:
return search_bst(root.left, value)
else:
return search_bst(root.right, value)
# Example use
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.left.left = Node(20)
root.left.right = Node(40)
print(search_bst(root, 40)) # Output: True
print(search_bst(root, 100)) # Output: False
2D point program
1. Constructor Method in Classes
Practice Exercise 1 (Basic):
Task: Create a class Person
with a constructor (__init__
) that initializes name
and age
. Create an instance and print the attributes.
Your Code:
Click here to write code in a Python learning environment
Example:
class Person: def __init__(self, name, age): self.name = name self.age = age person1 = Person("Alice", 30) print(person1.name, person1.age)
Output:
Alice 30
Practice Exercise 2 (Advanced):
Task: Create a class Book
with attributes title
, author
, and year
. Include a constructor that initializes these attributes. Create a method get_book_info
that returns a string with the book's information. Instantiate the class and print the information using the method.
Your Code:
Click here to write code in a Python learning environment
Example:
class Book: def __init__(self, title, author, year): self.title = title self.author = author self.year = year def get_book_info(self): return f"'{self.title}' by {self.author}, published in {self.year}" book1 = Book("1984", "George Orwell", 1949) print(book1.get_book_info())
Output:
'1984' by George Orwell, published in 1949
2. Using type()
Practice Exercise 1 (Basic):
Task: Use type()
to check the data type of different variables like an integer, string, and list.
Your Code:
Click here to write code in a Python learning environment
Example:
a = 10 b = "Hello" c = [1, 2, 3] print(type(a)) # <class 'int'> print(type(b)) # <class 'str'> print(type(c)) # <class 'list'>
Practice Exercise 2 (Advanced):
Task: Create a function check_data_type
that takes an argument and returns a string indicating whether the argument is an integer, string, or list using type()
.
Your Code:
Click here to write code in a Python learning environment
Example:
def check_data_type(data): if type(data) == int: return "This is an integer." elif type(data) == str: return "This is a string." elif type(data) == list: return "This is a list." else: return "Unknown type." print(check_data_type(42)) # This is an integer. print(check_data_type("abc")) # This is a string. print(check_data_type([1, 2, 3])) # This is a list.
3. Using isinstance()
Practice Exercise 1 (Basic):
Task: Use isinstance()
to check if an object is a specific type, such as checking if a variable is a string or a number.
Your Code:
Click here to write code in a Python learning environment
Example:
x = "Hello" y = 10 print(isinstance(x, str)) # True print(isinstance(y, int)) # True
Practice Exercise 2 (Advanced):
Task: Create a function check_object_type
that checks if an object is a subclass of a certain class and returns whether it is or not.
Your Code:
Click here to write code in a Python learning environment
Example:
class Animal: pass class Dog(Animal): pass def check_object_type(obj): if isinstance(obj, Animal): return "This is an Animal." else: return "This is not an Animal." dog = Dog() print(check_object_type(dog)) # This is an Animal.
4. Recap on Using all()
Practice Exercise 1 (Basic):
Task: Use all()
to check if all elements in a list are True
.
Your Code:
Click here to write code in a Python learning environment
Example:
numbers = [1, 2, 3, 4] print(all(x > 0 for x in numbers)) # True
Practice Exercise 2 (Advanced):
Task: Create a function check_conditions
that checks if all items in a list of conditions are met (e.g., all items are positive, even, etc.).
Your Code:
Click here to write code in a Python learning environment
Example:
def check_conditions(conditions): return all(cond for cond in conditions) conditions = [True, True, False] print(check_conditions(conditions)) # False
5. Using tuple()
Practice Exercise 1 (Basic):
Task: Convert a list of numbers into a tuple and print it.
Your Code:
Click here to write code in a Python learning environment
Example:
my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # (1, 2, 3)
Practice Exercise 2 (Advanced):
Task: Convert a dictionary's values into a tuple and print the tuple.
Your Code:
Click here to write code in a Python learning environment
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3} my_tuple = tuple(my_dict.values()) print(my_tuple) # (1, 2, 3)
6. Using vars(self)
Practice Exercise 1 (Basic):
Task: Create a class Car
with a constructor that takes make
and model
as parameters. Use vars(self)
to print all the attributes of an instance.
Your Code:
Click here to write code in a Python learning environment
Example:
class Car: def __init__(self, make, model): self.make = make self.model = model def display_attributes(self): print(vars(self)) car1 = Car("Toyota", "Corolla") car1.display_attributes() # {'make': 'Toyota', 'model': 'Corolla'}
Practice Exercise 2 (Advanced):
Task: Create a method that iterates over the attributes of an object using vars(self)
and returns the names and values of attributes in a readable format.
Your Code:
Click here to write code in a Python learning environment
Example:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def display_attributes(self): for attr, value in vars(self).items(): print(f"{attr}: {value}") car1 = Car("Toyota", "Corolla", 2020) car1.display_attributes()
Output:
make: Toyota model: Corolla year: 2020
7. Using vars(self).items()
Practice Exercise 1 (Basic):
Task: Use vars(self).items()
in a class to print the attribute names and values of an instance.
Your Code:
Click here to write code in a Python learning environment
Example:
class Book: def __init__(self, title, author, year): self.title = title self.author = author self.year = year def display_attributes(self): for attr, value in vars(self).items(): print(f"{attr}: {value}") book1 = Book("1984", "George Orwell", 1949) book1.display_attributes()
Output:
title: 1984 author: George Orwell year: 1949
Practice Exercise 2 (Advanced):
Task: Create a method that dynamically prints all attributes of an instance and their values, formatted with labels (e.g., "Title:", "Author:", etc.), using vars(self).items()
.
Your Code:
Click here to write code in a Python learning environment
Example:
class Book: def __init__(self, title, author, year): self.title = title self.author = author self.year = year def display_attributes(self): for attr, value in vars(self).items(): print(f"{attr.capitalize()}: {value}") book1 = Book("1984", "George Orwell", 1949) book1.display_attributes()
Output:
Title: 1984 Author: George Orwell Year: 1949
8. Using vars(self).values()
Practice Exercise 1 (Basic):
Task: Use vars(self).values()
to print just the values of the instance attributes.
Your Code:
Click here to write code in a Python learning environment
Example:
class Person: def __init__(self, name, age): self.name = name self.age = age def display_values(self): for value in vars(self).values(): print(value) person1 = Person("Alice", 30) person1.display_values()
Output:
Alice 30
Practice Exercise 2 (Advanced):
Task: Create a method that prints the sum of all numerical attributes (like age or year) from an instance by iterating over vars(self).values()
.
Your Code:
Click here to write code in a Python learning environment
Example:
class Person: def __init__(self, name, age, year): self.name = name self.age = age self.year = year def sum_numerical_values(self): total = 0 for value in vars(self).values(): if isinstance(value, int): total += value return total person1 = Person("Alice", 30, 1990) print(person1.sum_numerical_values()) # 2020
9. How to Iterate Through vars(self)
Using a For Loop
Practice Exercise 1 (Basic):
Task: Use a for
loop to iterate through the attributes and print both their names and values using vars(self)
.
Your Code:
Click here to write code in a Python learning environment
Example:
class Product: def __init__(self, name, price): self.name = name self.price = price def display_attributes(self): for attr, value in vars(self).items(): print(f"{attr}: {value}") product1 = Product("Laptop", 1200) product1.display_attributes()
Output:
name: Laptop price: 1200
Practice Exercise 2 (Advanced):
Task: Create a method that prints the attribute names in uppercase using a for
loop with vars(self)
.
Your Code:
Click here to write code in a Python learning environment
Example:
class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category def display_uppercase_attributes(self): for attr in vars(self): print(attr.upper()) product1 = Product("Laptop", 1200, "Electronics") product1.display_uppercase_attributes()
Output:
NAME PRICE CATEGORY
10. Using getattr()
Method
Practice Exercise 1 (Basic):
Task: Use getattr()
to access an object's attribute and print its value.
Your Code:
Click here to write code in a Python learning environment
Example:
class Car: def __init__(self, make, model): self.make = make self.model = model car1 = Car("Toyota", "Corolla") print(getattr(car1, "make")) # Toyota
Practice Exercise 2 (Advanced):
Task: Create a method that checks if an attribute exists in an object. If the attribute exists, return its value using getattr()
, otherwise return a default value.
Your Code:
Click here to write code in a Python learning environment
Example:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def get_attribute(self, attr, default="Unknown"): return getattr(self, attr, default) car1 = Car("Toyota", "Corolla", 2020) print(car1.get_attribute("make")) # Toyota print(car1.get_attribute("color", "Red")) # Red
11. Using getattr()
Method Using self
Keyword in a Class
Practice Exercise 1 (Basic):
Task: Use getattr()
with the self
keyword in a method to access an attribute of an object and print its value.
Your Code:
Click here to write code in a Python learning environment
Example:
class Animal: def __init__(self, species, name): self.species = species self.name = name def display_name(self): print(getattr(self, "name")) dog = Animal("Dog", "Buddy") dog.display_name()
Output:
Buddy
Practice Exercise 2 (Advanced):
Task: Create a method that takes an attribute name as an argument, uses getattr()
with self
, and returns its value. If the attribute doesn't exist, return "Attribute not found"
.
Your Code:
Click here to write code in a Python learning environment
Example:
class Animal: def __init__(self, species, name, age): self.species = species self.name = name self.age = age def get_attribute(self, attribute): return getattr(self, attribute, "Attribute not found") dog = Animal("Dog", "Buddy", 3) print(dog.get_attribute("name")) # Buddy print(dog.get_attribute("color")) # Attribute not found
12. Using a For Loop to Dynamically Access Object Attributes and Perform Tasks with Them (e.g., multiplication)
Practice Exercise 1 (Basic):
Task: Use a for
loop and getattr()
to dynamically access attributes of two objects and multiply their corresponding attributes.
Your Code:
Click here to write code in a Python learning environment
Example:
class Product: def __init__(self, price, quantity): self.price = price self.quantity = quantity product1 = Product(10, 2) product2 = Product(5, 3) total_value = sum(getattr(product1, attr) * getattr(product2, attr) for attr in vars(product1)) print(total_value)
Output:
40
Practice Exercise 2 (Advanced):
Task: Modify the previous exercise to calculate the total value of multiple products with different attributes using a for
loop and getattr()
. Include a check to ensure both objects have the same attributes.
Your Code:
Click here to write code in a Python learning environment
Example:
class Product: def __init__(self, price, quantity, discount): self.price = price self.quantity = quantity self.discount = discount product1 = Product(10, 2, 5) product2 = Product(5, 3, 2) # Calculate total using common attributes total_value = sum(getattr(product1, attr) * getattr(product2, attr) for attr in vars(product1) if hasattr(product2, attr)) print(total_value)
Output:
38
13. Dynamic Object Creation with Argument Unpacking
Practice Exercise 1 (Basic):
Task: Use argument unpacking to create an object dynamically using a dictionary for initialization.
Your Code:
Click here to write code in a Python learning environment
Example:
class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade student_data = {"name": "John", "age": 15, "grade": "A"} student = Student(**student_data) print(student.name, student.age, student.grade)
Output:
John 15 A
Practice Exercise 2 (Advanced):
Task: Use self._class_(**dictionary)
to create a dynamic object within a method. The method should dynamically instantiate the class using the dictionary and return the object.
Your Code:
Click here to write code in a Python learning environment
Example:
class Employee: def __init__(self, name, position, salary): self.name = name self.position = position self.salary = salary def create_employee(self, employee_data): return self.__class__(**employee_data) employee_data = {"name": "Alice", "position": "Manager", "salary": 50000} employee_instance = Employee("Temp", "Temp", 0).create_employee(employee_data) print(employee_instance.name, employee_instance.position, employee_instance.salary)
Output:
Alice Manager 50000
In this example, self.__class__(**employee_data)
dynamically creates an instance of the Employee
class using the data in employee_data
passed as keyword arguments.
This version of item 13 now includes an example using self._class_(**dictionary)
to dynamically create an instance of a class inside a method. Let me know if you need further adjustments!
14. Special Methods in Python
Practice Exercise 1 (Basic):
Task: Implement a special method (__str__
) in a class to define how an object should be represented when printed.
Your Code:
Click here to write code in a Python learning environment
Example:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} is {self.age} years old." person = Person("Bob", 25) print(person)
Output:
Bob is 25 years old.
Practice Exercise 2 (Advanced):
Task: Implement a special method (__eq__
) to compare two objects for equality based on a specific attribute.
Your Code:
Click here to write code in a Python learning environment
Example:
class Product: def __init__(self, name, price): self.name = name self.price = price def __eq__(self, other): return self.price == other.price product1 = Product("Laptop", 1000) product2 = Product("Tablet", 1000) product3 = Product("Phone", 800) print(product1 == product2) # True print(product1 == product3) # False
15. The Use of other
Keyword in Special Methods in Python (How It Can Be Used Throughout the Method)
Practice Exercise 1 (Basic):
Task: Create a class that uses the other
keyword within a special method to compare two objects for equality. You should use other
to refer to the second object in the method.
Your Code:
Click here to write code in a Python learning environment
Example:
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __eq__(self, other): if isinstance(other, Rectangle): return self.width == other.width and self.height == other.height return False r1 = Rectangle(5, 10) r2 = Rectangle(5, 10) r3 = Rectangle(4, 8) print(r1 == r2) # True print(r1 == r3) # False
Output:
True False
Practice Exercise 2 (Advanced):
Task: Use the other
keyword to implement a special method that compares the area of two shapes (circle and rectangle). The other
parameter should allow the method to access the second object and perform the comparison accordingly.
Your Code:
Click here to write code in a Python learning environment
Example:
import math class Circle: def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius**2 def __eq__(self, other): if isinstance(other, Circle): return self.area() == other.area() elif isinstance(other, Rectangle): return self.area() == other.area() return False class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height c1 = Circle(3) c2 = Circle(3) r1 = Rectangle(3, 3) print(c1 == c2) # True print(c1 == r1) # True
Output:
True True
In this example, the other
keyword is used to compare the area of objects, whether they are Circle
or Rectangle
instances, within the __eq__
method.
16. Using Special Methods in Main Program
Practice Exercise 1 (Basic):
Task: Use the __add__
method to define how two objects of a class should be added together. Implement this in the main program and create instances of the class.
Your Code:
Click here to write code in a Python learning environment
Example:
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) p1 = Point(1, 2) p2 = Point(3, 4) result = p1 + p2 print(f"Result: ({result.x}, {result.y})")
Output:
Result: (4, 6)
Practice Exercise 2 (Advanced):
Task: Use multiple special methods (__add__
, __mul__
, __str__
) in the main program. Implement objects with the ability to add, multiply, and print the result.
Your Code:
Click here to write code in a Python learning environment
Example:
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) def __str__(self): return f"Vector({self.x}, {self.y})" v1 = Vector(1, 2) v2 = Vector(3, 4) added = v1 + v2 multiplied = v1 * 2 print(f"Added: {added}") print(f"Multiplied: {multiplied}")
Output:
Added: Vector(4, 6) Multiplied: Vector(2, 4)
In this example, multiple special methods are used together in the main program to perform vector operations and print the results.
17. Returning NotImplemented
Practice Exercise 1 (Basic):
Task: Implement a class with a special method (__eq__
) that returns NotImplemented
when comparing objects of different types.
Your Code:
Click here to write code in a Python learning environment
Example:
class Book: def __init__(self, title, author): self.title = title self.author = author def __eq__(self, other): if not isinstance(other, Book): return NotImplemented return self.title == other.title and self.author == other.author book1 = Book("1984", "George Orwell") book2 = Book("1984", "George Orwell") book3 = "Not a book" print(book1 == book2) # True print(book1 == book3) # False
Output:
True False
Practice Exercise 2 (Advanced):
Task: Use the NotImplemented
return value in a method that compares objects of different types. Extend the functionality to allow the __eq__
method to handle comparisons of multiple types, returning NotImplemented
if the comparison is invalid.
Your Code:
Click here to write code in a Python learning environment
Example:
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __eq__(self, other): if isinstance(other, Rectangle): return self.width == other.width and self.height == other.height if isinstance(other, Circle): return self.width * self.height == other.radius**2 return NotImplemented class Circle: def __init__(self, radius): self.radius = radius def __eq__(self, other): if isinstance(other, Circle): return self.radius == other.radius return NotImplemented r1 = Rectangle(4, 5) r2 = Rectangle(4, 5) c1 = Circle(2) c2 = Circle(2) print(r1 == r2) # True print(r1 == c1) # True print(c1 == c2) # True
Output:
True True True
In this exercise, the NotImplemented
return value is used to indicate when an operation or comparison isn't valid for the given object types. It ensures that Python will attempt alternative methods or return False
if no appropriate method is found.
Shape Area Calculator
1. Abstract Classes
Practice Exercise: Basi
Create an abstract class called Animal
with an abstract method make_sound
. Create a concrete class Dog
that inherits from Animal
and implements the make_sound
method to print "Bark".
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Bark")
dog = Dog()
dog.make_sound()
Practice Exercise: More Complex
Extend the Animal
class to include a class-level attribute type
that specifies the type of animal. Use this in a new subclass Cat
, which makes the sound "Meow".
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
type = "General Animal"
@abstractmethod
def make_sound(self):
pass
class Cat(Animal):
type = "Feline"
def make_sound(self):
print("Meow")
cat = Cat()
print(cat.type)
cat.make_sound()
2. Abstract Methods
Practice Exercise: Basic
Define an abstract method area
in a class Shape
and implement it in a subclass Square
. The area
method should calculate the area of a square.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
square = Square(4)
print(square.area())
Practice Exercise: More Complex
Add another abstract method perimeter
to the Shape
class. Implement it in the Square
class to calculate both the area and the perimeter.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
square = Square(4)
print(square.area())
print(square.perimeter())
3. Creating Children (Concrete Classes)
Practice Exercise: Basic
Create an abstract class Vehicle
with an abstract method start
. Implement it in a subclass Car
and make it print "Car started".
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
car = Car()
car.start()
Practice Exercise: More Complex
Add another subclass Bike
and implement its start
method to print "Bike started".
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
class Bike(Vehicle):
def start(self):
print("Bike started")
bike = Bike()
bike.start()
4. Using __init__()
in an Abstract Class
Practice Exercise: Basic
Create an abstract class Person
with an __init__()
method that initializes a name. Implement a subclass Student
that inherits Person
and print the student's name.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def role(self):
pass
class Student(Person):
def role(self):
print(f"{self.name} is a student")
student = Student("Alice")
student.role()
Practice Exercise: More Complex
Add an additional attribute, age
, to the __init__()
method in Person
. Use it in the Student
class to print the name and age.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def role(self):
pass
class Student(Person):
def role(self):
print(f"{self.name}, aged {self.age}, is a student")
student = Student("Alice", 20)
student.role()
5. Using __init_subclass__()
in an Abstract Class
Practice Exercise: Basic
Create an abstract class Base
that uses __init_subclass__()
to enforce that every subclass has a class-level attribute type
. Implement a subclass Derived
with type = "Custom"
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC
class Base(ABC):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'type'):
raise AttributeError("Subclasses of Base must define 'type' attribute")
class Derived(Base):
type = "Custom"
derived = Derived()
print(derived.type)
Practice Exercise: More Complex
Extend the Base
class to require that subclasses also have a description
class attribute. Implement this in a SpecialDerived
subclass.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC class Base(ABC):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'type') or not hasattr(cls, 'description'):
raise AttributeError("Subclasses of Base must define 'type' and 'description' attributes")
class SpecialDerived(Base):
type = "Special"
description = "This is a special class"
special = SpecialDerived()
print(special.type)
print(special.description)
6. The Difference Between the Use of __init__()
and __init_subclass__()
in Abstract Classes
Practice Exercise: Basic
Create an abstract class Entity
that uses __init__()
to initialize instance attributes and __init_subclass__()
to enforce class attributes. Implement a concrete class Item
with both instance and class attributes.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC
class Entity(ABC):
def __init__(self, name):
self.name = name
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'category'):
raise AttributeError("Subclasses of Entity must define 'category' attribute")
class Item(Entity):
category = "General"
def __init__(self, name):
super().__init__(name)
item = Item("Box")
print(item.name)
print(Item.category)
Practice Exercise: More Complex
Expand the Entity
class to require subclasses to define a subcategory
attribute. Create a concrete class Furniture
with category
and subcategory
attributes, and ensure the instance also initializes name
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC
class Entity(ABC):
def __init__(self, name):
self.name = name
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'category') or not hasattr(cls, 'subcategory'):
raise AttributeError("Subclasses of Entity must define 'category' and 'subcategory' attributes")
class Furniture(Entity):
category = "Household"
subcategory = "Furniture"
def __init__(self, name):
super().__init__(name)
furniture = Furniture("Table")
print(furniture.name)
print(Furniture.category)
print(Furniture.subcategory)
7. What an Interface Is and How We Simulate Interfaces in Python
Practice Exercise: Basic
Create an interface using an abstract class Flyable
with an abstract method fly()
. Implement this interface in a concrete class Bird
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Flyable(ABC):
@abstractmethod
def fly(self):
pass
class Bird(Flyable):
def fly(self):
print("The bird is flying!")
bird = Bird()
bird.fly()
Practice Exercise: More Complex
Create another class Airplane
that also implements the Flyable
interface. Both Bird
and Airplane
should have unique implementations of the fly()
method.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Flyable(ABC):
@abstractmethod
def fly(self):
pass
class Bird(Flyable):
def fly(self):
print("The bird is flying with its wings!")
class Airplane(Flyable):
def fly(self):
print("The airplane is flying using its engines!")
bird = Bird()
airplane = Airplane()
bird.fly()
airplane.fly()
8. The Difference Between an Interface and Abstract Classes (Specifically in Python)
Practice Exercise: Basic
Create an abstract class Animal
with a concrete method eat()
and an interface Swimmable
with an abstract method swim()
. Implement both in a class Fish
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
def eat(self):
print("This animal eats food.")
class Swimmable(ABC):
@abstractmethod
def swim(self):
pass
class Fish(Animal, Swimmable):
def swim(self):
print("The fish is swimming.")
fish = Fish()
fish.eat()
fish.swim()
Practice Exercise: More Complex
Create another class Duck
that implements both the Animal
abstract class and the Swimmable
interface, adding a unique behavior for swim()
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
def eat(self):
print("This animal eats food.")
class Swimmable(ABC):
@abstractmethod
def swim(self):
pass
class Duck(Animal, Swimmable):
def swim(self):
print("The duck paddles in the water.")
duck = Duck()
duck.eat()
duck.swim()
9. The Use of Annotating Variables to Clarify They Will Hold a Specific Data Type in Abstract Classes
Practice Exercise: Basic
Create an abstract class Vehicle
that annotates a variable speed
as an integer. Create a concrete class Car
that assigns a value to speed
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC
class Vehicle(ABC):
speed: int
class Car(Vehicle):
speed = 120
car = Car()
print(f"The car's speed is {car.speed} km/h.")
Practice Exercise: More Complex
Add another annotated variable fuel
as a float in the Vehicle
class. Assign values to both speed
and fuel
in a Motorcycle
class.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC class Vehicle(ABC):
speed: int
fuel: float
class Motorcycle(Vehicle):
speed = 80
fuel = 15.5
motorcycle = Motorcycle()
print(f"The motorcycle's speed is {motorcycle.speed} km/h and fuel level is {motorcycle.fuel} liters.")
10. Class Attributes
Practice Exercise: Basic
Create a class Dog
with a class attribute species
set to "Canine"
. Create an instance of Dog
and access the species
attribute.
Your Code
Click here to write code in a Python learning environment
Example:
class Dog:
species = "Canine"
dog = Dog()
print(dog.species)
Practice Exercise: More Complex
Add another class attribute num_legs
and write a method that prints both class attributes.
Your Code
Click here to write code in a Python learning environment
Example:
class Dog:
species = "Canine"
num_legs = 4
@classmethod def info(cls):
print(f"A {cls.species} has {cls.num_legs} legs.")
Dog.info()
11. The Difference Between Class Attributes and Instance Attributes
Practice Exercise: Basic
Create a class Person
with a class attribute species
set to "Homo sapiens"
and an instance attribute name
. Create two instances of Person
with different names, but both sharing the same species.
Your Code
Click here to write code in a Python learning environment
Example:
class Person:
species = "Homo sapiens"
def __init__(self, name):
self.name = name
person1 = Person("Alice")
person2 = Person("Bob")
print(f"{person1.name} belongs to the species {person1.species}.")
print(f"{person2.name} belongs to the species {person2.species}.")
Practice Exercise: More Complex
Add a method change_species
that modifies the class attribute species
. Demonstrate that changing the class attribute affects all instances of the class.
Your Code
Click here to write code in a Python learning environment
Example:
class Person:
species = "Homo sapiens"
def __init__(self, name):
self.name = name
@classmethod
def change_species(cls, new_species):
cls.species = new_species
person1 = Person("Alice")
person2 = Person("Bob")
print(person1.species)
print(person2.species)
Person.change_species("Homo novus")
print(person1.species)
print(person2.species)
12. Accessing Class Attributes Using self
Practice Exercise: Basic
Create a class Animal
with a class attribute kingdom
set to "Animalia"
. Write an __init__
method that prints the kingdom
attribute using self
.
Your Code
Click here to write code in a Python learning environment
Example:
class Animal:
kingdom = "Animalia"
def __init__(self):
print(self.kingdom)
animal = Animal()
Practice Exercise: More Complex
Demonstrate that if an instance attribute with the same name as the class attribute exists, it takes priority. Create an instance of Animal
with an instance attribute kingdom
set to "Plantae"
, and verify the output.
Your Code
Click here to write code in a Python learning environment
Example:
class Animal:
kingdom = "Animalia"
def __init__(self):
print(self.kingdom)
animal1 = Animal()
animal1.kingdom = "Plantae"
print(animal1.kingdom)
print(Animal.kingdom)
13. How to Define Class Attributes in Abstract Classes
Practice Exercise: Basic
Create an abstract class Polygon
with class attributes name
(type str
) and num_sides
(type int
). Create a concrete class Triangle
that assigns values to these attributes.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC class
Polygon(ABC):
name: str
num_sides: int
class Triangle(Polygon):
name = "Triangle"
num_sides = 3
triangle = Triangle()
print(f"A {triangle.name} has {triangle.num_sides} sides.")
Practice Exercise: More Complex
Create another concrete class Square
that also inherits from Polygon
and assigns different values to name
and num_sides
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC
class Polygon(ABC):
name: str
num_sides: int
class Square(Polygon):
name = "Square"
num_sides = 4
square = Square()
print(f"A {square.name} has {square.num_sides} sides.")
14. Using Type Hints in Python
Practice Exercise: Basic
Create a class Circle
with a method area()
that accepts a parameter radius: int
and returns a value of type float
.
Your Code
Click here to write code in a Python learning environment
Example:
class Circle:
def area(self, radius: int) -> float:
return 3.14159 * radius ** 2
circle = Circle()
print(circle.area(5))
Practice Exercise: More Complex
Create an abstract class Shape
with a method perimeter()
annotated to return a float
. Create a concrete class Rectangle
that implements this method, taking parameters length: int
and width: int
.
Your Code
Click here to write code in a Python learning environment
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def perimeter(self, length: int, width: int) -> float:
pass
class Rectangle(Shape):
def perimeter(self, length: int, width: int) -> float:
return 2 * (length + width)
rectangle = Rectangle()
print(rectangle.perimeter(5, 3))
15. Recap on Special Methods
Practice Exercise: Basic
Create a class Book
with attributes title
and author
. Override the __str__()
method to return a string in the format "Title by Author"
.
Your Code
Click here to write code in a Python learning environment
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("1984", "George Orwell")
print(book)
Practice Exercise: More Complex
Create a class Movie
with attributes title
, director
, and year
. Override the __str__()
method to return a string in the format "Title (Year) directed by Director"
.
Your Code
Click here to write code in a Python learning environment
Example:
class Movie:
def __init__(self, title, director, year):
self.title = title
self.director = director
self.year = year
def __str__(self):
return f"{self.title} ({self.year}) directed by {self.director}"
movie = Movie("Inception", "Christopher Nolan", 2010) print(movie)
16. Recap on Arithmetic Operators in Python
Practice Exercise: Basic
Write a function calculate
that takes two integers and performs addition, subtraction, multiplication, and division, returning the results as a tuple.
Your Code
Click here to write code in a Python learning environment
Example:
def calculate(a, b):
return a + b, a - b, a * b, a / b
result = calculate(10, 2)
print(result)
Practice Exercise: More Complex
Modify the calculate
function to also compute the modulus (%
) and integer division (//
) and return all results.
Your Code
Click here to write code in a Python learning environment
Example:
def calculate(a, b):
return a + b, a - b, a * b, a / b, a % b, a // b
result = calculate(10, 3)
print(result)
17. Recap on Raising a ValueError
in Python
Practice Exercise: Basic
Write a function validate_age
that raises a ValueError
if the input age is negative.
Your Code
Click here to write code in a Python learning environment
Example:
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return "Valid age"
print(validate_age(25))
print(validate_age(-5)) # This will raise an error
Practice Exercise: More Complex
Write a function validate_score
that raises a ValueError
if the input score is not between 0 and 100.
Your Code
Click here to write code in a Python learning environment
Example:
def validate_score(score):
if score < 0 or score > 100:
raise ValueError("Score must be between 0 and 100.")
return "Valid score"
print(validate_score(85))
print(validate_score(150)) # This will raise an error
18. Recap on Using isinstance()
Practice Exercise: Basic
Write a function check_type
that takes an input and returns "It's a string"
if the input is a string and "It's not a string"
otherwise.
Your Code
Click here to write code in a Python learning environment
Example:
def check_type(value):
if isinstance(value, str):
return "It's a string"
else:
return "It's not a string"
print(check_type("hello"))
print(check_type(42))
Practice Exercise: More Complex
Write a function type_checker
that takes a list and counts how many elements are integers, returning the count.
Your Code
Click here to write code in a Python learning environment
Example:
def type_checker(values):
count = 0
for value in values:
if isinstance(value, int):
count += 1
return count
print(type_checker([1, "apple", 3.5, 2]))
19. Recap on Using *
When Passing Parameters into Functions or Methods
Practice Exercise: Basic
Write a function sum_all
that takes any number of arguments and returns their sum.
Your Code
Click here to write code in a Python learning environment
Example:
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4))
Practice Exercise: More Complex
Write a function combine_strings
that takes any number of string arguments and returns them concatenated into a single string.
Your Code
Click here to write code in a Python learning environment
Example:
def combine_strings(*args):
return " ".join(args)
print(combine_strings("This", "is", "a", "test"))
20. Using Python Built-in Function any()
Practice Exercise: Basic
Write a function contains_positive
that takes a list of integers and returns True
if any of the integers are positive, otherwise returns False
.
Your Code
Click here to write code in a Python learning environment
Example:
def contains_positive(numbers):
return any(num > 0 for num in numbers)
print(contains_positive([-3, -2, -1, 0]))
print(contains_positive([-3, -2, 1, 0]))
Practice Exercise: More Complex
Write a function has_vowel
that takes a string and returns True
if any of the characters in the string are vowels, otherwise returns False
.
Your Code
Click here to write code in a Python learning environment
Example:
def has_vowel(text):
vowels = "aeiouAEIOU"
return any(char in vowels for char in text)
print(has_vowel("sky"))
print(has_vowel("hello"))
21. Unpacking Values from an Iterable into Two Variables
Practice Exercise: Basic
Write a function unpack_pair
that takes a tuple containing two elements and returns the two elements separately.
Your Code
Click here to write code in a Python learning environment
Example:
def unpack_pair(pair):
a, b = pair
return a, b
print(unpack_pair((10, 20)))
Practice Exercise: More Complex
Write a function split_first_last
that takes a list and unpacks the first and last elements into separate variables, returning them as a tuple.
Your Code
Click here to write code in a Python learning environment
Example:
def split_first_last(lst):
first, *_, last = lst
return first, last
print(split_first_last([1, 2, 3, 4, 5]))
22. Unpacking a Single Value from an Iterable (Using a Comma)
Practice Exercise: Basic
Write a function extract_first
that takes a list and unpacks the first element, returning it.
Your Code
Click here to write code in a Python learning environment
Example:
def extract_first(lst):
first, *_ = lst
return first
print(extract_first([10, 20, 30]))
Practice Exercise: More Complex
Write a function extract_last
that takes a list and unpacks the last element using a comma, returning it.
Your Code
Click here to write code in a Python learning environment
Example:
def extract_last(lst):
*_, last = lst
return last
print(extract_last([10, 20, 30]))
23. Using the pass
Keyword in Python
Practice Exercise: Basic
Write a function empty_function
that does nothing when called.
Your Code
Click here to write code in a Python learning environment
Example:
def empty_function():
pass
print("This function does nothing:", empty_function())
Practice Exercise: More Complex
Write a class Shape
with a method draw()
that uses the pass
keyword to indicate that it will be implemented later in a subclass.
Your Code
Click here to write code in a Python learning environment
Example:
class Shape:
def draw(self):
pass
# Subclass to implement draw method
class Circle(Shape):
def draw(self):
return "Drawing a Circle"
shape = Circle() print(shape.draw())
24. Using Python Built-in Function hasattr()
Practice Exercise: Basic
Write a function has_attribute
that checks if an object has an attribute named name
and returns True
or False
.
Your Code
Click here to write code in a Python learning environment
Example:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
def has_attribute(obj):
return hasattr(obj, "name")
print(has_attribute(p))
print(has_attribute("string"))
Practice Exercise: More Complex
Write a function check_and_get
that checks if an object has an attribute named data
and returns the value of the attribute if it exists; otherwise, returns "Attribute not found"
.
Your Code
Click here to write code in a Python learning environment
Example:
class DataContainer:
def __init__(self, data):
self.data = data
container = DataContainer([1, 2, 3])
def check_and_get(obj):
if hasattr(obj, "data"):
return obj.data
return "Attribute not found"
print(check_and_get(container))
print(check_and_get("string"))
25. Using AttributeError
in Python (Raise AttributeError
)
Practice Exercise: Basic
Write a function get_attribute
that attempts to access an attribute named value
from an object. If the object does not have this attribute, raise an AttributeError
with a custom message.
Your Code
Click here to write code in a Python learning environment
Example:
class MyObject:
def __init__(self, value):
self.value = value
def get_attribute(obj):
if not hasattr(obj, "value"):
raise AttributeError("The object does not have the 'value' attribute.")
return obj.value
obj = MyObject(42)
print(get_attribute(obj))
try:
print(get_attribute("string"))
except AttributeError as e:
print(e)
Practice Exercise: More Complex
Write a function safe_get_attribute
that takes an object and an attribute name. Attempt to access the attribute. If it does not exist, raise an AttributeError
with a detailed message including the missing attribute name.
Your Code
Click here to write code in a Python learning environment
Example:
class MyObject:
def __init__(self, name):
self.name = name
def safe_get_attribute(obj, attr_name):
if not hasattr(obj, attr_name):
raise AttributeError(f"The object does not have an attribute named '{attr_name}'.")
return getattr(obj, attr_name)
obj = MyObject("Test Object")
print(safe_get_attribute(obj, "name"))
try:
print(safe_get_attribute(obj, "value"))
except AttributeError as e:
print(e)
26. Using the Math Library (Specifically to Find the Exact Value of pi
)
Practice Exercise: Basic
Write a function calculate_circle_area
that takes a radius as input and uses the math.pi
constant to calculate and return the area of a circle.
Your Code
Click here to write code in a Python learning environment
Example:
import math
def calculate_circle_area(radius):
return math.pi * radius ** 2
print(calculate_circle_area(5))
Practice Exercise: More Complex
Write a function compare_circle_circumference
that takes two radii as input, calculates their circumferences using math.pi
, and returns a tuple indicating which radius is larger and by how much.
Your Code
Click here to write code in a Python learning environment
Example:
import math
def compare_circle_circumference(radius1, radius2):
circumference1 = 2 * math.pi * radius1
circumference2 = 2 * math.pi * radius2
difference = abs(circumference1 - circumference2)
larger_radius = radius1 if circumference1 > circumference2 else radius2
return larger_radius, difference
print(compare_circle_circumference(5, 10))
Bank management system
1. Encapsulation
Practice Exercise 1 (Easier):
Define a class
Person
with private attributes (name
,age
) and write methods to interact with these attributes indirectly (e.g.,get_name()
andget_age()
).
Practice Exercise 2 (More Complex):
Define a class
Employee
that has private attributes forsalary
andposition
, and implement methods to change the position (setter) while ensuring the salary remains confidential and cannot be modified externally.
2. Private Attributes and Name Mangling
Practice Exercise 1 (Easier)
Create a class
Product
with a private attribute__price
. Try accessing and modifying__price
directly from outside the class and observe the result.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Product:
def __init__(self, price):
self.__price = price
# Attempting to access the private attribute
product = Product(100)
print(product.__price) # This will raise an AttributeError
Practice Exercise 2 (More Complex)
Create a class
Car
with a private__mileage
attribute. Use name mangling to modify__mileage
and demonstrate how name mangling works to hide the attribute.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Car:
def __init__(self, mileage):
self.__mileage = mileage
def get_mileage(self):
return self._Car__mileage
# Access using name mangling
car = Car(15000)
print(car.get_mileage()) # Outputs: 15000
3. Getters
Practice Exercise 1 (Easier)
Define a class
Rectangle
with private attributes__length
and__width
. Implement a getter method for each attribute using the@property
decorator.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Rectangle:
def __init__(self, length, width):
self.__length = length
self.__width = width
@property
def length(self):
return self.__length
@property
def width(self):
return self.__width
rectangle = Rectangle(10, 5)
print(rectangle.length) # Outputs: 10
print(rectangle.width) # Outputs: 5
Practice Exercise 2 (More Complex)
Create a class
Circle
with a private attribute__radius
. Use the@property
decorator to implement a getter that returns the area of the circle, not the radius directly.
Your Code:
Click here to write code in a Python learning environment.
Example:
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
@property
def area(self):
return math.pi * (self.__radius ** 2)
circle = Circle(3)
print(circle.area) # Outputs: 28.274333882308138
4. Setters
Practice Exercise 1 (Easier)
Create a class
BankAccount
with a private attribute__balance
. Implement a setter using the@property
decorator to update the balance, ensuring it cannot be set to a negative value.
Your Code:
Click here to write code in a Python learning environment.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
raise ValueError("Balance cannot be negative")
account = BankAccount(100)
account.balance = 150 # Valid update
print(account.balance) # Outputs: 150
# account.balance = -50 # This will raise a ValueError
Practice Exercise 2 (More Complex)
Create a class
Temperature
with a private attribute__celsius
. Use the@property
decorator for a getter that returns the temperature in Fahrenheit, and a setter that allows you to set the temperature in Fahrenheit and converts it to Celsius.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Temperature:
def __init__(self, celsius):
self.__celsius = celsius
@property
def fahrenheit(self):
return (self.__celsius * 9/5) + 32
@fahrenheit.setter
def fahrenheit(self, temp_fahrenheit):
self.__celsius = (temp_fahrenheit - 32) * 5/9
temperature = Temperature(25)
print(temperature.fahrenheit) # Outputs: 77.0
temperature.fahrenheit = 100
print(temperature.__celsius) # Outputs: 37.77777777777778
5. Using the slots Variable
Practice Exercise 1 (Easier)
Create a class
Student
using the__slots__
variable to limit the attributes toname
andage
. Try to add an extra attribute and observe the result.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Student:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("John", 20)
# student.grade = 'A' # This will raise an AttributeError
Practice Exercise 2 (More Complex)
Create a class
Library
that uses__slots__
to store the attributesbook_title
andauthor
. Attempt to add an attribute dynamically and observe what happens.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Library:
__slots__ = ['book_title', 'author']
def __init__(self, book_title, author):
self.book_title = book_title
self.author = author
library = Library("1984", "George Orwell")
# library.publisher = "Secker & Warburg" # This will raise an AttributeError
6. Using the repr Special Method
Practice Exercise 1 (Easier)
Define a class
Book
with attributestitle
andauthor
. Implement a__repr__
method to return a string representation of the book.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __repr__(self):
return f"Book(title={self.title}, author={self.author})"
book = Book("1984", "George Orwell")
print(book) # Outputs: Book(title=1984, author=George Orwell)
Practice Exercise 2 (More Complex)
Create a class
Movie
with attributesname
,director
, andrelease_year
. Implement the__repr__
method to return a string representation of the movie. Override the__str__
method for user-friendly output.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Movie:
def __init__(self, name, director, release_year):
self.name = name
self.director = director
self.release_year = release_year
def __repr__(self):
return f"Movie(name={self.name}, director={self.director}, release_year={self.release_year})"
def __str__(self):
return f"{self.name} by {self.director}, released in {self.release_year}"
movie = Movie("Inception", "Christopher Nolan", 2010) print(movie) # Outputs: Inception by Christopher Nolan, released in 2010
7. Using eval() with the repr Special Method
Practice Exercise 1 (Easier)
Create a class
Expression
with a__repr__
method that returns a string representation of a mathematical expression. Then, use theeval()
function in another method to evaluate the expression and return the result.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Expression:
def __init__(self, expression):
self.expression = expression
def __repr__(self):
return f"Expression('{self.expression}')"
def evaluate(self):
return eval(self.expression)
expr = Expression("3 + 4 * 2")
print(expr) # Outputs: Expression('3 + 4 * 2')
print(expr.evaluate()) # Outputs: 11
Practice Exercise 2 (More Complex)
Write a class
MathEvaluator
that holds a list of mathematical expressions. Use the__repr__
method to return a string that represents all the expressions in the list. Then, useeval()
to evaluate each expression and return the results as a list.
Your Code:
Click here to write code in a Python learning environment.
Example:
class MathEvaluator:
def __init__(self, expressions):
self.expressions = expressions
def __repr__(self):
return f"MathEvaluator({self.expressions})"
def evaluate_all(self):
results = [eval(expr) for expr in self.expressions]
return results
eval_obj = MathEvaluator(["2 + 2", "10 / 2", "3 * 5"])
print(eval_obj) # Outputs: MathEvaluator(['2 + 2', '10 / 2', '3 * 5'])
print(eval_obj.evaluate_all()) # Outputs: [4, 5.0, 15]
8. Recap on Using ValueError in Python
Practice Exercise 1 (Easier)
Write a function
check_age
that raises aValueError
if the age is less than 0 or greater than 120. Call the function with an invalid age to see the error raised.
Your Code:
Click here to write code in a Python learning environment.
Example:
def check_age(age):
if age < 0 or age > 120:
raise ValueError("Age must be between 0 and 120")
return age
try:
print(check_age(-1)) # This will raise a ValueError
except ValueError as e:
print(e) # Outputs: Age must be between 0 and 120
Practice Exercise 2 (More Complex)
Write a function
divide_numbers
that accepts two numbers as arguments. If the second number is zero, raise aValueError
indicating division by zero is not allowed.
Your Code:
Click here to write code in a Python learning environment.
Example:
def divide_numbers(num1, num2):
if num2 == 0:
raise ValueError("Cannot divide by zero")
return num1 / num2
try:
print(divide_numbers(10, 0)) # This will raise a ValueError
except ValueError as e:
print(e) # Outputs: Cannot divide by zero
9. Using += and -=
Practice Exercise 1 (Easier)
Create a variable
total
and increment it by 10 using+=
. Then, decrement it by 5 using-=
.
Your Code:
Click here to write code in a Python learning environment.
Example:
total = 0
total += 10 # Increment by 10
total -= 5 # Decrement by 5
print(total) # Outputs: 5
Practice Exercise 2 (More Complex)
Write a function
track_balance
that accepts a list of transactions (positive for deposits and negative for withdrawals). Use+=
and-=
to update the balance with each transaction in the list.
Your Code:
Click here to write code in a Python learning environment.
Example:
def track_balance(transactions):
balance = 0
for transaction in transactions:
balance += transaction # Increment or decrement based on the transaction
return balance
transactions = [100, -50, 20, -10]
print(track_balance(transactions)) # Outputs: 60
10. Recap on .append Method
Practice Exercise 1 (Easier)
Create an empty list and use the
.append()
method to add a string element to the list. Then, print the list.
Your Code:
Click here to write code in a Python learning environment.
Example:
fruits = []
fruits.append("apple")
print(fruits)
# Outputs: ['apple']
Practice Exercise 2 (More Complex)
Create a list of numbers. Use
.append()
to add the square of each number in the list to a new list. Then, print the new list.
Your Code:
Click here to write code in a Python learning environment.
Example:
numbers = [1, 2, 3, 4]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print(squared_numbers) # Outputs: [1, 4, 9, 16]
11. Using if not on a List (To See if It's Empty)
Practice Exercise 1 (Easier)
Create a function that takes a list of items and returns a message saying whether the list is empty or not. Use
if not
to check if the list is empty.
Your Code:
Click here to write code in a Python learning environment.
Example:
def check_empty(items):
if not items: # This checks if the list is empty
return "The list is empty."
return "The list is not empty."
print(check_empty([])) # Outputs: The list is empty.
print(check_empty([1, 2, 3])) # Outputs: The list is not empty.
Practice Exercise 2 (More Complex)
Create a class
Inventory
that contains a list of items. Add a method to check if the list of items is empty using theif not
statement and return a message accordingly.
Your Code:
Click here to write code in a Python learning environment.
Example:
class Inventory:
def __init__(self):
self.items = []
def check_inventory(self):
if not self.items: # This checks if the list is empty
return "No items in inventory."
return f"Items in inventory: {', '.join(self.items)}"
inv = Inventory()
print(inv.check_inventory()) # Outputs: No items in inventory.
inv.items.append("Apples")
print(inv.check_inventory()) # Outputs: Items in inventory: Apples
Explanation of if not
In both tasks, the
if not
statement is used to check whether the list (orself.items
) is empty.The
if not
condition evaluates toTrue
when the list is empty (since an empty list is considered "falsy" in Python). If the list is not empty, theelse
branch would be executed.The key point is that
if not list_name
is a Pythonic way to check if a list is empty.
12. Using ā\nā.join() for Formatting
Practice Exercise 1 (Easier)
Create a list of words and use
'\n'.join()
to format the list into a string where each word appears on a new line.
Your Code:
Click here to write code in a Python learning environment.
Example:
words = ["apple", "banana", "cherry"]
formatted_words = "\n".join(words)
print(formatted_words) # Outputs: # apple # banana # cherry
Practice Exercise 2 (More Complex)
Write a function
format_text
that accepts a list of sentences and uses'\n'.join()
to return a formatted string with each sentence on a new line, ensuring no extra spaces at the end.
Your Code:
Click here to write code in a Python learning environment.
Example:
def format_text(sentences):
return "\n".join(sentence.strip() for sentence in sentences)
sentences = ["Hello, world! ", "Python is great.", "Enjoy coding."]
formatted_text = format_text(sentences)
print(formatted_text) # Outputs: # Hello, world! # Python is great. # Enjoy coding.