Exercises
Declaration and Display
Exercise: Declare a variable x with the value 10 and display it.
Solution:
x = 10 print(x)
Initialization and Type
Exercise: Initialize a variable name with your first name and display its type.
Solution:
name = "John" print(type(name))
Arithmetic Operations
Exercise: Declare two variables a and b with the values 5 and 3. Compute their sum, difference, product, and quotient.
Solution:
a = 5 b = 3 print("Sum:", a + b) print("Difference:", a - b) print("Product:", a * b) print("Quotient:", a / b)
Variables and Strings
Exercise: Create a variable first_name with your first name and a variable last_name with your last name. Combine them to create a variable full_name and display it.
Solution:
first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name)
Type Conversion
Exercise: Convert a string “25” to an integer and add it to another integer 10.
Solution:
str_number = "25" number = int(str_number) result = number + 10 print(result)
Variables in a Function
Exercise: Create a function multiply that takes two variables and returns their product.
Solution:
def multiply(x, y): return x * y result = multiply(4, 5) print(result)
Global and Local Variables
Exercise: Show the difference between a global variable and a local variable using a function.
Solution:
global_var = "Global" def test(): local_var = "Local" print("Inside the function:", local_var) print("Inside the function, global:", global_var) test() print("Outside the function, global:", global_var)
Variables and Lists
Exercise: Create a list containing three elements and assign it to a variable. Display the second element.
Solution:
my_list = [10, 20, 30] print(my_list[1])
Variable Modification
Exercise: Declare a variable score with the value 0. After adding 10 to this variable, display the new value.
Solution:
score = 0 score += 10 print(score)
Variables and Loops
Exercise: Use a for loop to display the values of i from 0 to 4, where i is a variable.
Solution:
for i in range(5): print(i)
Variables and Conditions
Exercise: Create a variable age and test if it is greater than or equal to 18. Display an appropriate message based on the result.
Solution:
age = 20 if age >= 18: print("You are an adult.") else: print("You are a minor.")
Variables and Dictionaries
Exercise: Create a dictionary with keys name and age, and display the value associated with name.
Solution:
person = {"name": "Alice", "age": 30} print(person["name"])
String Manipulation
Exercise: Create a variable sentence with the value “Hello world!”. Convert it to uppercase and display the result.
Solution:
sentence = "Hello world!" print(sentence.upper())
String Operations
Exercise: Create a variable text containing “Python” and another language containing “is fun”. Concatenate them with a space and display the result.
Solution:
text = "Python" language = "is fun" result = text + " " + language print(result)
String Interpolation
Exercise: Use an f-string to create a string containing your first name and your age.
Solution:
name = "Claire" age = 28 message = f"Hello, my name is {name} and I am {age} years old." print(message)
Variables and Tuples
Exercise: Create a tuple containing the values 1, 2, and 3. Assign it to a variable and display the first element.
Solution:
my_tuple = (1, 2, 3) print(my_tuple[0])
Multiple Assignment
Exercise: Assign the values 5, 10, and 15 to the variables x, y, and z in a single line.
Solution:
x, y, z = 5, 10, 15 print(x, y, z)
Boolean Variables
Exercise: Declare a variable is_sunny with the value True and display a different message depending on whether the variable is True or False.
Solution:
is_sunny = True if is_sunny: print("It's sunny today.") else: print("It's not sunny today.")
Variables and List Updates
Exercise: Create a list of numbers and replace the second element with 99. Display the updated list.
Solution:
numbers = [1, 2, 3, 4, 5] numbers[1] = 99 print(numbers)
Type Checking
Exercise: Declare a variable data and check if it is of type float. Display an appropriate message.
Solution:
data = 10.5 if isinstance(data, float): print("The variable is a float.") else: print("The variable is not a float.")
Conversion to String
Exercise: Convert an integer 42 to a string and concatenate it with another string.
Solution:
number = 42 text = "The number is " + str(number) print(text)
Using input()
Exercise: Ask the user to enter their name and display a welcome message with the entered name.
Solution:
name = input("What is your name? ") print(f"Welcome, {name}!")
Default Parameter Values
Exercise: Create a function that takes one argument with a default value. Display this default value if no argument is provided.
Solution:
def greet(name="Guest"): print(f"Hello, {name}!") greet() # Displays "Hello, Guest!" greet("Alice") # Displays "Hello, Alice!"
Using None
Exercise: Create a variable result initialized to None. Later, assign an integer value to it and display the new value.
Solution:
result = None result = 100 print(result)
Variables and Lists of Strings
Exercise: Create a list of strings and add a new element to the end. Display the updated list.
Solution:
words = ["Python", "is", "great"] words.append("!") print(words)
Variable Swap
Exercise: Swap the values of two variables a and b without using a temporary variable.
Solution:
a = 10 b = 20 a, b = b, a print(a, b)
Variables and Tuple Operations
Exercise: Create a tuple (1, 2, 3, 4) and compute the sum of all its elements.
Solution:
numbers = (1, 2, 3, 4) total = sum(numbers) print(total)
Updating Variables in a Loop
Exercise: Create a variable total initialized to 0. Use a for loop to add numbers from 1 to 5 to total, then display total.
Solution:
total = 0 for i in range(1, 6): total += i print(total)
Nested Dictionaries
Exercise: Create a dictionary with a key student whose value is another dictionary containing name and age. Display the student’s name.
Solution:
data = { "student": { "name": "Paul", "age": 22 } } print(data["student"]["name"])
Variables and Sets
Exercise: Create a set with elements 1, 2, 3, and 4. Add a new element 5 and display the set.
Solution:
my_set = {1, 2, 3, 4} my_set.add(5) print(my_set)
List Comprehension
Exercise: Create a list of the squares of numbers from 1 to 5 using a list comprehension.
Solution:
squares = [x**2 for x in range(1, 6)] print(squares)
Variables and Tuples in Functions
Exercise: Create a function get_coordinates that returns a tuple containing two values x and y. Display these values.
Solution:
def get_coordinates(): return (10, 20) coords = get_coordinates() print("x:", coords[0]) print("y:", coords[1])
List of Lists (Matrix)
Exercise: Create a 2×2 matrix as a list of lists. Modify the element at position [1][1] to 99 and display the updated matrix.
Solution
matrix = [[1, 2], [3, 4]] matrix[1][1] = 99 print(matrix)
String Formatting
Exercise: Create a formatted string using the .format() method to display a sentence with your name and age.
Solution:
name = "Claire" age = 28 message = "Hello, my name is {} and I am {} years old.".format(name, age) print(message)
Dictionaries with Lists as Values
Exercise: Create a dictionary where each key is a color name and each value is a list of RGB color codes. Display the RGB codes for the color “blue”.
Solution:
colors = { "red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255] } print(colors["blue"])
Boolean Variables with Conditions
Exercise: Declare a variable is_raining with the value False. Use a condition to display a different message based on whether is_raining is True or False.
Solution:
is_raining = False if is_raining: print("It is raining, take an umbrella.") else: print("It is not raining, enjoy the nice weather.")
Default Values in Functions
Exercise: Create a function calculate_area that calculates the area of a rectangle. The second argument, height, has a default value of 10. Display the area using the function with and without specifying the height parameter.
Solution:
def calculate_area(width, height=10): return width * height print(calculate_area(5)) # Uses the default value for height print(calculate_area(5, 8)) # Specifies the value for height
Swapping Values with a Function
Exercise: Create a function swap_values that swaps the values of two variables and returns the new values.
Solution:
def swap_values(a, b): return b, a x, y = 3, 7 x, y = swap_values(x, y) print(x, y)
While Loop and Variables
Exercise: Create a variable count initialized to 0. Use a while loop to increment count by 1 until it is greater than 5, then display count.
Solution:
count = 0 while count <= 5: count += 1 print(count)
Advanced String Manipulation
Exercise: Create a string containing “Python programming”. Replace “programming” with “is fun” and display the new string.
Solution:
text = "Python programming" new_text = text.replace("programming", "is fun") print(new_text)