Basic Exercises
Here we will go through some basic exercises first describing the logic to solving the problem and provide the solution. Keep in mind there are multiple ways to solve the exercises but return the same output, in some of the later exercises we propose two ways to tackle them.
1. Print “Hello, World!” to the console.
To do this in Python, you can use the print
function. The print
function is a built-in function in Python that allows you to output text or other values to the console or other output streams. You can pass a string or any other type of value as an argument to the print function, and it will be printed to the console.
In Python, strings are used to represent text values. You can create a string by enclosing a sequence of characters in quotation marks (either single or double).
View Solution
print("Hello, World!")
2. Declare a variable x and set it equal to 10. Print the value of x.
In Python, variables are used to store values that you can use and manipulate in your code. To declare a variable, you simply need to give it a name and use the assignment operator =
to assign a value to it.
View Solution
x = 10
print(x)
3. Declare a variable y and set it equal to the string “hello”. Print the value of y.
This example combines Exercise 1 and 2.
View Solution
y = "hello"
print(y)
4. Use the len function to find the length of the string “hello”.
The len
function can be used to find the length of any string or other sequence type in Python, such as lists, tuples, and dictionaries. It is a useful tool for working with and manipulating strings and other sequences in your code.
View Solution
print(len("hello"))
5. Create a list of numbers from 1 to 10 and store it in a variable numbers. Print the list.
Lists are one of the most commonly used data structures in Python. They are used to store a collection of items that can be of any data type, including numbers, strings, and other lists. You can create a list by enclosing a comma-separated sequence of items in square brackets ([]
).
There are multiple ways you can create the ascending list of numbers, either by defining the list manually or you can use the range
function to create a range of numbers, and then use the list
function to convert the range to a list.
View Solution
# Manually defining the list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers)
# Using the range and list function to create the list
numbers = list(range(1, 11))
print(numbers)
6. Use a for loop to iterate over the list and print each number.
Depending on how you created the list of numbers, you can use a for
loop to iterate over the list and use the print function to print each element of the list. Recall back to For Loops and Lists for a refresher.
For loops are one of the most commonly used control structures in Python. They allow you to iterate over a sequence of elements (such as a list or string) and perform a specific action for each element. The syntax for a for loop in Python is as follows:
for element in sequence:
# code to be executed for each element
View Solution
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
print(number)
7. Create a dictionary that maps the keys “a” through “z” to the values 1 through 26. Print the dictionary.
Similarly to Exercise 5 there are multiple ways to create the alphabet dictionary either manually, using the {}
brackets and specify a comma-separated sequence of key-value pairs inside the brackets. Each key-value pair is specified using the key: value
syntax. Here’s an example of how to define a dictionary in Python:
dictionary = {
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
print(dictionary)
This code will define a dictionary with the keys “a”, “b”, “c”, and “d” and the corresponding values 1, 2, 3, and 4. The print function is used to print the dictionary to the console.
You can also use the dict function to create a dictionary from a sequence of key-value pairs:
dictionary = dict([("a", 1), ("b", 2), ("c", 3), ("d", 4)])
print(dictionary)
Another way of tackling this exercise, would be to use a for
loop to iterate over the letters and add each key-value pair to the dictionary. Create an empty dictionary and with the for
loop is used to iterate over the letters “a” through “z”, and the enumerate
function is used to generate a sequence of tuples containing the index and the value of each element. The i variable is used to store the index of each element, and the letter variable is used to store the value. The key-value pair is then added to the dictionary using the dictionary[key] = value syntax.
View Solution
# Manually defining the dictionary
dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
print(dictionary)
# Using a for loop and the enumerate function
# Initialize an empty dictionary
dictionary = {}
# Iterate through the letters of the alphabet, and their corresponding index
# (starting from 1) using the enumerate function
for i, letter in enumerate("abcdefghijklmnopqrstuvwxyz", start=1):
# Add each letter as a key, and its corresponding index as the value
# to the dictionary
dictionary[letter] = i
print(dictionary)
8. Use a for loop to iterate over the dictionary and print the keys and values.
To iterate over the dictionary and use the items
method to access the keys and values. You can then use the print function to print each key-value pair. Look back to Exercise 7 to the for loop used but instead use dictionary.items
to access the key and values in the dictionary. Remember in this exercise we want to print both the keys and values.
View Solution
dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
for key, value in dictionary.items():
print(key, value)
9. Write a function that takes a list as an argument and returns the sum of the elements in the list. Test the function with the numbers list from exercise 5.
The structure of a Python function can be found in Functions. To calculate the sum we want iterate over the list of numbers, and use the +=
operator to add each element of the list to the total
variable. Start by initialising total = 0
before the for loop and returning it at the end of the loop.
The +=
operator is a compound assignment which adds the right operand to the left operand and assigns the result to the left operand. An example of how the +=
operator works is seen in the following code:
x = 5
x += 2 # x is now equal to 7
# Essentially it can be seen as a short hand to
x = 5
x = x + 2 # here x also will equal to 7
View Solution
def sum_list(lst):
total = 0
for element in lst:
total += element
return total
print(sum_list(numbers))
10. Write a function that takes a string as an argument and returns the string with all vowels removed. Test the function with the string “hello”.
Iterate over the string by using a for
loop, then use an if
statement to check if each character is a vowel, and if it is, you can skip it and continue to the next character. If the character is not a vowel, you can add it to a new string. Finally, you can return the new string at the end of the function.
View Solution
def remove_vowels(s):
vowels = "aeiouAEIOU"
s_without_vowels = ""
for character in s:
if character not in vowels:
s_without_vowels += character
return s_without_vowels
print(remove_vowels("hello"))
Interactive Exercises
Completing interactive exercises on https://www.w3schools.com/python/exercise.asp which is an amazing resource we recommend! It’s a great way to practice and reinforce your Python skills. These exercises can help you to learn about different Python concepts and features that may not have been covered in the exercises you have already completed here. Additionally, if your feeling ready you can tackle the quiz they have available https://www.w3schools.com/quiztest/quiztest.asp?qtest=PYTHON to test your knowledge.