Exercises Python Fundamentals/Advanced
Description
The following exercises are grouped into topics that more or less match the topics in this course. The are marked with icons to indicate their difficulty.



Here you will find a number of exercises grouped together by topic.
Sections
Variables, Values and User Input
Selection
Iteration
Functions
Lists
Dict and Set
Comprehension
File Handling
Function Generators
Misc Exercises
Variables, Values and User Input
Write a program that asks for the name of the user and then prints the message:
Hi name
Name should be the name the user entered. Look at solution
Write a program that asks the user for two numbers and store them in two variables called
num1
andnum2
. Add them together and store the result in a variable calledresult
and print the result back to the user.NOTE! All input we get from the input function will be stored as strings so
num1
andnum2
must first be converted to integers with theint()
function. Look at solution
Write a program that gives an answer to the following problem:
In a group there are three girls and two boys. If we have 5 more identical groups how many persons will there be?
I assume that you can see that the result will be 30, but now let Python do the job. Let the program add 3 and 2 and multiply it with 6. Do this in one line and store the result in a variable and then print the result. Look at solution
Write a program that takes a character (i.e. a string of length 1) and tells the user if the character is a vowel or not. Look at solution
Write a program that asks how old the user is and then tells the user if she is a teen or not. Look at solution
It is common for images of a country’s previous leaders, or other individuals of historical significance, to appear on its money. The individuals that appear on banknotes in the United States are listed in the table below.
Write a program that begins by reading the denomination of a banknote from the user. Then your program should display the name of the individual that appears on the banknote of the entered amount. An appropriate error message should be displayed if no such note exists.Individual Amount George Washington $1 Thomas Jefferson $2 Abraham Lincoln $5 Alexander Hamilton $10 Andrew Jackson $20 Ulysses S. Grant $50 Benjamin Franklin $100 Hint:
While two dollar banknotes are rarely seen in circulation in the United States, they are legal tender that can be spent just like any other denomination. The United States has also issued banknotes in denominations of $500, $1,000, $5,000, and $10,000 for public use. However, high denomination banknotes have not been printed since 1945 and were officially discontinued in 1969. As a result, we will not consider them in this exercise.
The solution given will use a dictionary. If you are not familiar with the use of dictionaries you should wait with this exercise until you are. Look at solution-
Using only simple variables and if statements, you should be able to get this to work; a loop is not needed.Given 3 numbers ( X , Y , Z ), assign variables x, y, z so that x ≤ y ≤ z and x, y, and z are from X , Y , and Z . Use only a series of if-statements and assignment statements.
Hint:
You must define the conditions under which you choose between x← X , x← Y or x← Z. You will do a similar analysis for assigning values to y and z. Note that your analysis for setting y will depend on the value set for x; similarly, your analysis for setting z will depend on values set for x and y. Look at solution -
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:UP 5 DOWN 3 LEFT 3 RIGHT 2
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5 DOWN 3 LEFT 3 RIGHT 2
Then, the output of the program should be:
2
Hint:
In case of input data being supplied to the question, it should be assumed to be a console input.
The solution for this exercise uses functions. If you are not familiar with them yet you should wait with this exercise until you are. Look at solution -
Write a program that capitalizes all the vowels in a string.Hint:
It is up to you to diecide if you want to consider Y a vowel or not.
Remeber that a string is immutable and can therefor not be changed so you will need to create a new string. Look at solution -
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.Hint:
Consider userange(#begin, #end)
method Look at solution -
With a given number n, write a program to generate a dictionary that contains (i, i*i). The dictionary shall include all integer values for i from 1 to n (both included). Then the program should print the dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hint:
As this exercise assume you are familiar with dictionaries you should wait to do it until you know how dictionaries work.
In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() Look at solution -
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.
The numbers obtained should be printed in a comma-separated sequence on a single line.Hint:
Convert the number into a string and use list(converted_number) on the string to get a list of digits Look at solution -
Define a functionmax()
that takes two numbers as arguments and returns the largest of them. Use the if-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.) Look at solution -
Define a functionmax_of_three()
that takes three numbers as arguments and returns the largest of them. Look at solution -
Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) Look at solution -
Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise. Look at solution -
Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon". Look at solution -
Define a functionsum()
and a functionmultiply()
that sums and multiplies (respectively) all the numbers in a list of numbers. For example,sum([1, 2, 3, 4])
should return 10, andmultiply([1, 2, 3, 4])
should return 24. Look at solution -
Define a functionreverse()
that computes the reversal of a string. For example,reverse("I am testing")
should return the string "gnitset ma I". Look at solution -
Define a functionis_palindrome()
that recognizes palindromes (i.e. words that look the same written backwards). For example,is_palindrome("radar")
should return True. Look at solution -
Define a functionoverlapping()
that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops. That two for-loops are nested means that one loop is placed inside the other loop. Look at solution -
Define a functiongenerate_n_chars()
that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example,generate_n_chars(5,"x")
should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.) Look at solution -
Define a functionhistogram()
that takes a list of integers and prints a histogram to the screen. For example,histogram([4, 9, 7])
should print the following:**** ********* *******
Look at solution
-
The functionmax(),
from exercise 13, and the function max_of_three(), from exercise 14, will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one. Look at solution -
In a particular jurisdiction, taxi fares consist of a base fare of $4.00, plus $0.25 for every 140 meters traveled. Write a function that takes the distance traveled (in kilometers) as its only parameter and returns the total fare as its only result. Write a main program that demonstrates the function.Hint:
Taxi fares change over time. Use constants to represent the base fare and the variable portion of the fare so that the program can be updated easily when the rates increase. Look at solution -
Write a function that takes a string of characters as its first parameter, and the width of the terminal in characters as its second parameter. Your function should return a new string that consists of the original string and the correct number of leading spaces so that the original string will appear centered within the provided width when it is printed. Do not add any characters to the end of the string. Look at solution -
Write a functionfind_longest_word()
that takes a list of words and returns the length of the longest one. Look at solution -
Write a functionfilter_long_words()
that takes a list of words and an integer n and returns the list of words that are longer than n. Look at solution -
A prime number is an integer greater than 1 that is only divisible by one and itself. Write a function that determines whether or not its parameter is prime, returning True if it is, and False otherwise. Write a main program that reads an integer from the user and displays a message indicating whether or not it is prime. Ensure that the main program will not run if the file containing your solution is imported into another program.Hint:
Consider using the modulus operator % Look at solution -
In this exercise you will create a function named nextPrime that finds and returns the first prime number larger than some integer, n. The value of n will be passed to the function as its only parameter. Include a main program that reads an integer from the user and displays the first prime number larger than the entered value.Hint:
Use your solution from the previous exercise to solve this Look at solution -
Write a program that maps a string with several words into a list of words, that is each word in the original string will be one item in the new list. Look at solution -
Write a program that reads integers from the user and stores them in a list. Your program should continue reading values until the user enters 0. Then it should display all of the values entered by the user (except for the 0) in order from smallest to largest, with one value appearing on each line.Hint:
Use either the sort method or the sorted function to sort the list. Look at solution -
Write a program that reads integers from the user and stores them in a list. Use 0 as a sentinel value to mark the end of the input. Once all of the values have been read your program should display them (except for the 0) in reverse order, with one value appearing on each line.Hint:
Start by solving the previous exercise Look at solution -
Write a function that determines whether or not a list of values is in sorted order (either ascending or descending). The function should return True if the list is already sorted. Otherwise it should return False. Write a main program that reads a list of numbers from the user and then uses your function to report whether or not the list is sorted.Hint:
Make sure you consider these questions when completing this exercise: Is a list that is empty in sorted order? What about a list containing one element? Look at solution -
In this exercise you will create a program that identifies all of the words in a string entered by the user. Begin by writing a function that takes a string of text as its only parameter.Your function should return a list of the words in the string with the punctuation marks at the edges of the words removed. The punctuation marks that you must remove include commas, periods, question marks, hyphens, apostrophes, exclamation points, colons, and semicolons. Do not remove punctuation marks that appear in the middle of a words, such as the apostrophes used to form a contraction. For example, if your function is provided with the string "Examples of contractions include: don’t, isn’t, and wouldn’t." then your function should return the list["Examples", "of", "contractions", "include", "don’t", "isn’t", "and", "wouldn’t"].
Hint:
As this exercise uses functions you should be familiar with them before you try to solve this one. Look at solution -
Create a program that determines and displays the number of unique characters in a string entered by the user. For example, Hello, World! has 10 unique characters while zzz has only one unique character.Hint:
Use a dictionary or set to solve this problem. Look at solution -
In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message:
Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English. Look at solution
-
Do the same Caesar chipher as in the previous example but the time use ROT-3, that is rotate the letters three steps. Create two functions, one for coding messages and one for decoding them.Hint:
You might want to use two dictionaries to solve this problem. In the solution section you will find three different solutions. For some extra chalenge you can try to solve this in all three ways.The first solution is straight forward as explained in the exercise text
The second solution has two extra functions that will generate the dictionaries. They will both take one argument, a number indicationg how many steps used when rotating the dictionaries. One of the functions generates a dictionary that is used for encryption and the other a dictionary used for encryption. We can also use a single function to encrypt and decrypt if we pass in the dictionary to be used to the enchipher function along with the text that should be encrypted/decrypted.
The third version is the most advanced. Here we use list comphrensions along with the chain function from itertools. If used with the maketrans and translate functions in the string class we can perform this operation using only one line för generating the key tables and encrypt the string and an other line that does the same when decrypting. If you manage to solve this you are working on a professional Python level.
-
In this exercise you will simulate 1,000 rolls of two dice. Begin by writing a function that simulates rolling a pair of six-sided dice. Your function will not take any parameters. It will return the total that was rolled on two dice as its only result.Write a main program that uses your function to simulate rolling two six-sided dice 1,000 times. As your program runs, it should count the number of times that each total occurs. Then it should display a table that summarizes this data. Express the frequency for each total as a percentage of the total number of rolls. Your program should also display the percentage expected by probability theory for each total. Sample output is shown below.
Total Simulated % Expected % 2 2.90 2.78 3 6.90 5.56 4 9.40 8.33 5 11.90 11.11 6 14.20 13.89 7 14.20 16.67 8 15.00 13.89 9 10.50 11.11 10 7.90 8.33 11 4.50 5.56 12 2.60 2.78 Hint:
To simulate dice rolls first import random to your module. Then you can simulate the roll by using the coder = random.randrange(6) +1
The reason we use +1 is that randrange will give us a random number from 0 and up to but not including the number we pass to it. Look at solution
-
Morse code is an encoding scheme that uses dashes and dots to represent numbers and letters. In this exercise, you will write a program that uses a dictionary to store the mapping from letters and numbers to Morse code. Use a period to represent a dot, and a hyphen to represent a dash. The mapping from letters and numbers to dashes and dots is shown in the table below. Your program should read a message from the user. Then it should translate each letter and number in the message to Morse code, leaving a space between each sequence of dashes and dots. Your program should ignore any characters that are not letters or numbers. The Morse code for Hello, World! is shown below:
.... . .-.. .-.. --- .-- --- .-. .-.. -..
Letter Code Letter Code Letter Code Letter Code A .- J .--- S ... 1 .---- B -... K -.- T - 2 ..--- C -.-. L .-.. U ..- 3 ...-- D -.. M -- V ...- 4 ....- E . N -. W .-- 5 ..... F ..-. O --- X -..- 6 -.... G --. P .--. Y -.-- 7 --... H .... Q --.- Z --.. 8 ---.. I .. R .-. 0 ----- 9 ----.
Look at solution -
Write a list comprehension that creates a list of tuples. Each tuple has two values, a temperature in Farenheit and a temperature in Celsius.Create one list for Farenheit values from 0 to 100 in steps of 5 and the matching Celsius values.
Create another list for Celsius values from -10 to 50 in steps of 2 and the matching Farenheit values.
Hint:
The conversion formulas between °F and °C are:°C = (°F - 32) × 5/9
°F = °C × 9/5 + 32 -
Write a list comprehension that uses nested for-clauses to create a single list with all 36 different dice combinations from (1,1) to (6,6).Hint:
The nested for-clauses mean that you have to independent for-loops, one for each dice. Also note that each combintaion can be stored as a tuple. Look at solution -
To solve this exercise you will first need to download this text file. It is the full book of Alice in Wonderland by Lewis Carroll. Write a program that reads the entire file and counts the number of times each word occurs in the text. You must consider removing punction characters, like periods, commas and so on from the text, without touching things like apostrophes found inside a word. When finished the program shall present a sorted list of the 100 most frequent words in the text. It should also present the longest word in the text.Hint:
Consider using the Counter from the collections module and a regex expression to remove all unwanted punctuation marks.When you have solved it you can, for some extra challenge, try to make your program more compact. The solution is only 26 lines long including code that formats a nice output. Can you beat that? Look at solution
-
Define a function generator which can iterate the numbers, which are divisible by 7, between a given range 1 and n.Hint:
You should use a generator by using yield in the function. Look at solution -
Write a version of a palindrome recognizer that also accepts phrase palindromes such as
"Go hang a salami I'm a lasagna hog."
"Was it a rat I saw?"
"Step on no pets"
"Sit on a potato pan, Otis"
"Lisa Bonet ate no basil"
"Satan, oscillate my metallic sonatas"
"I roamed under it as a tired nude Maori"
"Rise to vote sir"
"Dammit, I'm mad!"
Note that punctuation, capitalization, and spacing are usually ignored. Look at solution -
A pangram is a sentence that contains all the letters of the English alphabet at least once, for example:
The quick brown fox jumps over the lazy dog.
Your task here is to write a function to check a sentence to see if it is a pangram or not. Look at solution -
"99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.
Your task here is write a Python program capable of generating all the verses of the song. Look at solution
-
Represent a small bilingual lexicon as a Python dictionary in the following fashion
d = {"merry":"frohe", "christmas":"weihnachten", "and":"und", "happy":"frohes", "new":"neues", "year":"jahr"}
and use it to translate your Christmas cards from English into German. That is, write a functiontranslate()
that takes a list of English words and returns a list of German words. Look at solution -
Write a functionchar_freq(
) that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something likechar_freq("abbabcbdbabdbdbabababcbcbab")
. Look at solution