You are on page 1of 7

Simple exercises designed to get students familiar with the python environment.

Python covered: Int, float, string variables Input, raw_input +, -, *, **, / print 1. Computes the area of a circle with radius 123 cm. 2. Gets the radius of a circle and computes the area. 3. Go to and find how much a Canadian dollar is worth in Euros (EUR). Make a program that allows the user to enter the amount of Canadian they have and tell them what it is worth in Euros. Gets the users first and last name and outputs them in reverse order with a comma between them. 4. Gets the coordinates for two points from the user and computes the distance. Round your answer to two decimal places. 5. At Jennys birthday party she orders a 32 piece pizza. Have the user (probably Jenny) enter the number of people at the party that will be eating pizza and output the number of slices each one gets. As you know the pizza might not divide evenly. There are two ways to handle this. The first is to ignore the extra pieces and give everyone the same amount. The second way is to cut up the extra pieces so that everyone gets the same amount. Your program must output both options. E.g. Number of guests: 10 Option 1: 3 slices each, 2 left over Option 2: 3.2 slices each

There exercises focus on some simple String Manipulation. - Concatenation (+) - Multiplication (*) - Slices - Escape sequences - len() - String Methods upper lower find replace count 1. 2. 3. 4. Get the user's full name with one raw_input and display the name as last, first Get a file name from the user and display just the extension. Get a sentence from the user and display it back with one word per line. Get a number from the user (n) and create an n x n box of "X"es on the screen. e.g. If they entered 12: XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX

XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX 5. Without using the method center, get a string from the user and a field size then display the string centered within that field, with dots "." on either side. You may assume that the field size is larger than the length of the string. 6. Get a string from the user and display how many capital letters are in the string. With what we know now this is not an easy question. When we learn more this will become easier, but try it for now.

There exercises focus on some simple Selection if elif else basic Boolean operators ( >, == ) and / or 1. In Ontario we have two forms of sales tax PST & GST on fast food. GST is 6% and always charged on fast food, PST is 8% but only charged when the price of the meal is $4.00 or over. Create a program that gets the base price of a meal and outputs the total after tax. 2. Write a program that reads in a file name from the user and tells them what kind of file it is by looking at the extension. Your program must be able to recognize at least 5 different file types. e.g. "Dogs.doc" is a Word Document 3. The postage you pay to send a letter from Canada depends on where you are sending it. For a standard sized letter the postage rates are: Mailing within Canada Mailing to USA Mailing Internationally $0.52 $0.93 $1.55

Create a program that asks the user where he/she is mailing their letter then tell him/her how much the postage is. 4. When building and enclosure for a python the amount of area at the base of the enclosure should be proportionate to the length of the snake. The minimum needed is 1/2 square foot for each foot in length up to and including 6 and 3/4 square foot for each foot after that. e.g. 9' python needs 5.25 square feet (6 * + 3 * ) Create a program that asks the user how long their python is and tell them the minimum area they need for the base of its enclosure.

There exercises focus on some simple Selection while break counters, accumulators

1. 2.

Create a program that gets the marks the user has for their classes this year. Tell them how many classes they are failing (despite what many of you think a fail is 50%) As you know the inventor of the game chess was quite a clever fellow. As the story goes the inventor presented the game to the king and the king was quite pleased. The king asked what the inventor wanted as payment. He asked for a grain of cereal for the first square and to have each of the next 63 squares double the previous square. As the story goes the king agrees, but was not to be pleased by the final payment. Create a program that computes how much grain the king had to pay. Express your answer in pounds, assume there are 7000 grains to a pound. Write a program to be used by student council in this upcoming election to tabulate the votes after the election. Your program will list, and number, the three candidates for president then allow the user to enter all of the ballets until they enter 0 then tell them who won the election and what percentage each candidate earned. e.g.
1. Sir John A Macdonald 2. Alexander Mackenzie 3. Sir John Abbott


Enter Vote (0 to exit) : 1 Enter Vote (0 to exit) : 1 Enter Vote (0 to exit) : 1 Enter Vote (0 to exit) : 2
Sir John A Macdonald won Sir John A Macdonald earned 75% of the votes Alexander Mackenzie earned 25% of the votes Sir John Abbott earned 0% of the votes


Palindromes are words that are the same forwards and backwards. Create a program that gets a word from the user and tells them if it is palindrome or not. Your program should not care about capitalization.

1. a)

Trace the following programs.

a = 20 b = a / 2 c = a - b if b < c: print "unfair" elif a > b: print "easy as ABC" print a, b, c

b) i = 0 while i < 10: n = i ** 2 if i % 2 == 0: print n

c) x = y = z while z < x = x y = x z = y print

= 1 # trust me, it works 100: * 2 * 2 * 2 - 10 x,y,z

d) # n1 = "Vincent" n2 = "Massey" ans = "" i = 0 while i < len(n2): ans = ans + n1[i] + n2[i] n1 = n1[2:] n2 = n2[2:] print ans

Create the program: This is an introduction to some more advanced types. This will not be a detailed look at all of the weird and wonderful ways of using these types but instead a basic summary of what they are and HOW to use them. These data types are fundamental to Python. Even the programs from last section are already using tuples without the students knowledge. List - [1, 2, 3, 4] Tuple - (1, 2, 3, 4) String - McKenzie Dictionary - {McKenzie : 149, Annet : 125, Safranyos : 105}

These exercises focus on the nuts and bolts of how lists work. Highlights: creating a list e.g. fruit = [apple, orange, banana, pear] Slices: e.g. fruit[2], fruit[1:3] 1. Make a list of five of your friends and a list of five emotions or action words (e.g. loves, hates, misses ....) For each friend in the list randomly choose a word and another friend in the list. Don't worry if Jack loves Jack, he probably does anyways. Make a list of ten fruits and another list of the price each fruit. Use these two lists to create an attractive fruit stand menu. I had my eight nieces and nephews over to my house in the summer to pick weeds, because I hate doing it myself. I paid each of them $12.50 but it bothered me that some of them gave it their all and some of them spent more time with the Super-Soakers than they did pulling weeds. I've decided that next summer I'm going to pay based on performance. I'm still going to pay $100 in total but this time how much each person gets will be based on how many weeds they pulled. Write a program to help me out. I need your program to let the user type in eight kids names and how many weeds each of

2. 3.

the kids pulled then print out a list of how much each kid has earned. (the percentage of the $100 they get should be based on the percentage of the pile of weeds that they picked) save as 4. Snakes and Ladders can be a fun game for kids to play but you realize when you get older that the players actually have no choices at all. To illustrate just how little input the players have I want you to make a computer program that allows two players to play snakes and ladders on the board given. The rules of the game are simple. On each player's turn they roll one six sided die and move ahead that many squares. If they end their move at the base of a ladder then they automatically climb to the top of the ladder. If they end their move at the end of a snake they automatically slide down to its head. To win the game you must be the first player to land on the last square. If you are near the end and your roll would cause you to go past the end square you don't move for that turn. Your computerized version will look something like: Player 1 hit enter to roll You rolled: 3 You are at spot 3 Player 2 hit enter to roll You rolled: 6 You climbed a ladder You are at spot 17 although you can write this program without using lists, you should ask yourself how you can use lists to encode where the snakes and ladders are.

These exercises focus on creating and using our own functions: def - defining a function parameters return values calling a function 1. Create a function called hypotenuse that calculates the hypotenuse of a right-angle triangle given the other two sides. A palindrome is a word that reads the same both forward and backwards. Create a function called palindrome that takes a single word as a parameter and returns True if the word is a palindrome and False otherwise.



Knights in chess move in an L shape. They go 2 in one direction then one space at a 90 angle, as the diagram shows. Create a function called knightMove that takes in the current location (row, col) of a knight on the chess board and returns a list of tuples (row, col) of all possible places the knight can move.

5. As you know the persistence of a number is the number of steps it takes to get a one-digit number when separating the digits and multiplying them together. What you may not have noticed is that persistence is inherently recursive. The persistence of any one-digit number is zero. The persistence of any other number is one plus the persistence of the digits multiplied together. Create a recursive function called persistence that computes the persistence of any whole number.

These exercises are designed to increase familiarity with using pygame to draw basic graphics. pygame template developed in class draw.line, draw.rect, RGB Colours 1. 2. Draw a pattern of lines from the center of the screen to every 10th pixel on the perimeter of the screen. Use graph paper to draw a scene (e.g. your house.) Determine which python shapes you would need to draw this on the computer and write the important coordinates on the paper. Create a program that draws your scene in python Create a program that draws an attractive black and white chess board. Create a program that draws a simple 2-d pyramid of circles on the screen. The base should have 15 circles and yes this involves some math. This question is fairly hard. I expect you to plan it out on paper first. Create a program that draws 100, 20 x 20 rectangles at random positions on the screen. Create a program that draws 1000 filled circles of

3. 4.



radius 3 at random positions within 200 pixels of the center of

the screen. Also randomly determine the colour of each circle separately. 7. Draw two randomly placed radius 10 circles on the screen then draw radius 2 circles every twenty pixels from the center of one to the center of the other.

These exercises are designed to increase familiarity with the basic syntax of reading and writing with files. open() function. close() method read(), read(1) readline(), readlines() methods write(), writelines() methods 1. In your class folder is a file called "names.txt" Create a program that reads from the names file and simply says hello to each person, but only call them by their first name save as In your class folder is a file called "classes.txt" it is a list of classes of everyone in the school (well, sorta.) Create a program that allows the user to enter a class then have your program open a file with that class name and output the names of everyone who is in that class into the file. So, if the user entered "ICS3M-01" your program would create and fill a file called "ICS3M-01.TXT". In your class folder are two files "stocks.txt" and "stockProfile.txt". stocks is a file that has a list of stocks in it. Each stock has: <name> <code> <value> Each of these are separated by tabs. The value is the value of one share of the stock. stockProfile contains a list of my personal stock profile, it has a list of the stocks that I own in the form of: <code> <num> Where num is the number of shares of the stock I own. Make a program that reads from both of these files and displays a nice table that shows the names, and values of each stock I own, and an overall total. 4. When trying to identify the author of a piece of work it is sometimes useful to examine the frequency that words are used. Read the file "story.txt" and write to a file called "frequency.txt". Your output file will simply be each word in the story with how many times it occurred. This list should be sorted from most to least frequent. Write a program that plays the high-low guessing game with the user. Your program must keep track of a high score list. This list will keep track of the top 10 best scores along with the number that was being guessed.




Creating the functional programming: