You are on page 1of 29

Python Exercises for CSE 1310

December 3, 2010

Contents
1 Statements 2 Conditionals 3 Loops 4 Functions 5 Lists 6 Strings 7 File I/O 8 Dictionaries 9 Bugs A Answers A.1 Statements . A.2 Conditionals A.3 Loops . . . A.4 Functions . A.5 Lists . . . . A.6 Strings . . . A.7 File I/O . . A.8 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 7 9 11 13 15 17 19 21 25 25 25 25 26 27 28 28 28

CONTENTS

CONTENTS

Chapter 1 Statements
1. (added 8/26/2010) The program below calculates the area of a rectangle: print "I will calculate the area of a rectangle for you." sideA = input("Enter the length of one side:") sideB = input("Enter the length of an adjacent side:") area = sideA * sideB print "The area is", area Modify the program to add a third dimension, that is, nd the area of a rectangular cuboid. 2. (added 8/30/2010) Write a program that prompts the user for a number and then uses it to evaluate the following mathematical function: f (x) = 3x2 + 5x 6 3. (added 8/26/2010) Write a program that will prompt the user for a temperature in Fahrenheit and then convert it to Celsius. You may recall that the formula is C = 5 (F 32)/9. 4. (added 8/26/2010) Run the program below, using both integers (e.g., 10) and nonintegers (e.g., 13.89): numerator = input(What is the numerator? denominator = 4.0 )

print numerator, "/", denominator, "=", numerator/denominator Notice that the variable denominator has a value of 4.0, not 4. Change the value to 4 and run the program again. You should notice that when you provide an integer as the numerator, you never get a non-integer answer, even when you should. Why is this? 5

CHAPTER 1. STATEMENTS

Chapter 2 Conditionals
1. (added 8/26/2010) Compare the two programs below. Do you expect them to produce the same output? Why? version 1: x = 5 if x < 4: print x, elif x < 6: print x, elif x < 8: print x, elif x < 10: print x, else: print x, version 2: x = 5 if x < 4: print x, if x < 6: print x, if x < 8: print x, if x < 10: print x, else:

"is less than 4" "is less than 6" "is less than 8" "is less than 10" "is greater than or equal to 10"

"is less than 4" "is less than 6" "is less than 8" "is less than 10"

CHAPTER 2. CONDITIONALS print x, "is greater than or equal to 10" 2. (added 8/29/2010) Modify the program in question 1.3 to state whether or not water would boil at the temperature given. Your output might look like this: What is the temperature in Fahrenheit? 100 A temperature of 100 degrees Fahrenheit is 37 in Celsius Water does not boil at this temperature (under typical conditions).

Chapter 3 Loops
1. (added 8/26/2010) Write a program that picks a random integer in the range of 1 to 100. It then prompts the user for a guess of the value, with hints of too high or too low from the program. The program continues to run until the user guesses the integer. To have the program choose a random integer in the range of 1 to 100, use the statement value = random.randint(1, 100) 2. (added 8/29/2010) Write a program that prompts the user for two positive integers, which we will call b and e. The program will calculate be . That is, the program will raise a positive integer to a positive integer power. Hint: think about how you would explain to a rst-grader what be means. 3. (added 8/30/2010) Write a program that prompts the user for two positive integers, a and b, and then sums the integers from a to b, inclusive. Output might look like this: Enter a starting integer: 5 Enter a stopping integer: 15 The sum from 5 to 15 is 110 4. (added 8/30/2010) Write a program that prompts the user for two positive integers, a and b, and then counts the number of even integers in the range of a to b. Print the even integers in this range. Output might look like this: Enter a starting integer: Enter a stopping integer: 8 10 12 14 8 19

CHAPTER 3. LOOPS 16 18 There are 6 even integers between 8 and 19

10

Chapter 4 Functions
1. (added 8/30/2010) Rewrite the program for question 3.4. This time, write a function to determine the count of even integers. Therefore, the pseudocode for the main section of the program will be: prompt user for starting and stopping values call function to determine count of even integers (function returns count) print count 2. (added 10/12/2010) The program below calls a function, swap(), that receives two numbers, swaps the two numbers, and then returns them. Write swap(). ### main x = 99 y = 1000 ###

print x, y x, y = swap( x, y ) print x, y 3. (added 10/12/2010) Write a function that when given an integer, n, prints a pyramid n levels high from asterisks. Example: how tall should the pyramid be? * * * * * * * * * * * * * * * how tall should the pyramid be? 5

10 11

CHAPTER 4. FUNCTIONS * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

12

Chapter 5 Lists
Many of these ask that you write a function. If you are unsure of how to do that, try writing it without using a function. That is, put all of the code in the main body of the program. 1. (added 10/17/2010) Write a function that when given a 2-dimensional list will print the list in its original shape. For example, if given the list dataList = [ [ 1, 2, 3, 4] , [ 5, 6, 7, 8], [ 9, 10, 11, 12] ] the function will print 1 5 9 2 6 10 3 7 11 4 8 12

You can assume that all of the values in the list are integers of one or two digits each. 2. (added 10/12/2010) Rewrite the function in problem 4.2. This time, instead of returning two separate numbers, the function will return a list with the two numbers in it. 3. (added 10/12/2010) Write a function that when given a 1-dimensional list will sum the values in the list and return the sum. 4. (added 10/17/2010) Write a function that when given a 2-dimensional list will sum and print the values of each row. This can be done using for loops, but if you wish to use while loops you will need to know the number of rows and columns. For a 2-dimensional list called aList, you can nd the number of rows and columns using the code 13

CHAPTER 5. LISTS numRows = len( aList ) numCols = len( aList[0] ) 5. (added 10/17/2010) Write a function that when given a 2-dimensional list will sum and print the values of each column. 6. (added 9/29/2010) Write your own version of Pythons range() function. The function, myrange(), will be called using the form myrange(a, b) where a < b. If you want more of a challenge, add a third parameter, c, that is the increment for the values in the list. 7. (added 10/17/2010) Write a function that when given two 1-dimensional lists of the same length, add the elements in the same position and saves the results in another list which the function returns. 8. (added 10/28/2010) Write a function that when given a two-dimensional list returns the row and column indices of the maximum value in the list. Your function should be able to handle a list with any number of rows and columns. Remember that in Python, a function can return multiple values, for example return rowIndex, colIndex

14

Chapter 6 Strings
1. (added 10/28/2010) Write a function that will receive a string of comma-separated words and count how many of the words have more than ve letters. The function will return the count when nished. 2. (added 10/28/2010) Write a function that receives a string that consists of any combination of spaces, digits, uppercase or lowercase letters. The function should count the number of uppercase letters and return this count.

15

CHAPTER 6. STRINGS

16

Chapter 7 File I/O


1. (added 10/17/2010) Read a le, saving it to a list. Then print the le from this list. 2. (added 10/17/2010) Read a le in CSV format, swapping the columns as you print them. For example, if each line consists of two numbers separated by a comma, print the two numbers in reverse order. A rst few lines of a sample le might be 1,3 5,9 6,8

3. (added 10/17/2010) Read a CSV le in which each line consists of numbers separated by commas. Sum the numbers in the last column. 4. (added 10/17/2010) Read a CSV le in which each line consists of numbers separated by commas. If all lines have the same quantity of numbers (e.g., three numbers per line), prompt the user for an integer, n, and then sum the numbers in column n. 5. (added 10/28/2010) Write a program that reads a le, numbers.txt, in which each line consists of a single integer. The integers can be positive, negative, or zero. The program should nd the maximum value in the le and print it.

17

CHAPTER 7. FILE I/O

18

Chapter 8 Dictionaries
1. (added 11/1/2010) Create a dictionary with peoples names as keys and their ages as values and print each persons name and age. 2. (added 11/1/2010) Modify the previous program to only print the names and ages of people over 20 years old. 3. (added 11/1/2010) Modify the previous program to nd the youngest person in the dictionary. 4. (added 11/1/2010) Store the names and ages in a CSV le and read in the le, creating a dictionary from it. 5. (added 12/2/2010) We have the following data: Name Age Tom 43 John 50 Susan 35 Weight 185 170 125

Store this data in a dictionary with the name as the key. Write a function that when given a dictionary of this form and either the word age or weight will print the name of the user with the largest age or weight (depending on the word passed). For example, the function call might look like this: fx( data, "age" ) You can assume that age and weight will be the only two things stored for each name, but dont make assumptions about the number of entries in the dictionary.

19

CHAPTER 8. DICTIONARIES

20

Chapter 9 Bugs
All of the programs below have logic errors. 1. (added 12/2/2010) The program below reads data01.csv and stores the entries in a dictionary. When printing the dictionary, we get the following results: {dog: 200, cat: 100} Why arent all of the lines from the le stored?

inFile = open("data01.csv", "r") data = inFile.readlines() inFile.close() d = {} for line in data : animal, quantity = line.strip().split(,) d[animal] = quantity print d # data01.csv """ cat,14 dog,58 cat,100 dog,200 """ 21

CHAPTER 9. BUGS 2. (added 12/2/2010) The program below prints The contents of the list are: 5 7 56 14 23

Why arent all of the list elements printed? d = [99, 5, 7, 56, 14, 23] print "The contents of the list are: " , i = 1 while i < 6 : print d[i] i += 1

3. (added 12/2/2010) The program prints there are 1 even integers in the list Why? def even( data ) : count = 0 for n in data : if n % 2 == 0 : count += 1 return count

###

main

###

d = [8, 10, 7, 9, 4, 2] print "there are %d even integers in the list" % even( d ) 4. (added 12/3/2010) The program prints the average is 2.00 22

CHAPTER 9. BUGS d = [1, 2, 3, 4] sum = 0 i = 0 while i < 4 : sum += d[i] i += 1 print "the average is %3.2f" % (sum/4) 5. (added 12/3/2010) The program below produces the following output: [4, 5, 6, 7] [4, 5, 6, 7] The function reverse() should reverse the list in place. Why doesnt it? def reverse( aList ) : length = len(aList) i = 0 while i < length : temp = aList[i] aList[i] = aList[length - 1 - i] aList[length - 1 - i] = temp i += 1

###

main

###

d = [ 4, 5, 6, 7 ] print d reverse( d ) print d 6. (added 12/3/2010) The program should print the 4 4 multiplication table 1 2 3 4 the 2 3 4 4 6 8 6 9 12 8 12 16 end 23

CHAPTER 9. BUGS but instead prints 1 2 3 4

the end Why? r = 1 c = 1 while r <= 4 : while c <= 4 : print "%2d" % (r * c) , c += 1 print r += 1 print "the end"

24

Appendix A Answers
Answers to select problems.

A.1

Statements

A1.3 This is one possible implementation. f = input(What is the temperature in Fahrenheit? c = 5 * (f - 32) / 9 print "A temperature of", f, "degrees Fahrenheit is", c, "in Celsius" A1.4 Division of integers in Python (and many other languages) uses integer division. That is, dividing an integer by an integer produces an integer. When the variable denominator had a value of 4.0, it was stored as a oating-point value (i.e., something that can store the decimal part of a number). The result of dividing an integer by a oating-point number is a oating-point number. )

A.2 A.3

Conditionals Loops

A3.1 Here is pseudocode for the solution: generate random integer in the range 1 to 100 while guess not equal to random value prompt the user for guess 25

A.4. FUNCTIONS if guess > random value print too high else print too low

APPENDIX A. ANSWERS

A3.3 start = input("Enter a starting integer: ") stop = input("Enter a stopping integer: ") count = start sum = 0 while count <= stop : sum = sum + count count = count + 1 print "The sum from", start, "to", stop, "is", sum

A.4

Functions

A4.1 def evenCount(count, stop) : sum = 0 while count <= stop : if count%2 == 0 : sum = sum + 1 print count count = count + 1 return sum

start = input("Enter a starting integer: ") stop = input("Enter a stopping integer: ") total = evenCount(start, stop) print "There are", total, "even integers between", start, "and", stop 26

APPENDIX A. ANSWERS

A.5. LISTS

A.5

Lists

A5.1 def printList( aList ) : for row in aList : for col in row : print "%2d " % ( col ) print

dataList = [ [ 1, 2, 3, 4] , [ 5, 6, 7, 8], [ 9, 10, 11, 12] ] printList( dataList ) A5.3 def sumList( aList ) : sum = 0 for i in aList : sum += i return sum A5.7 def addLists( aList, bList ) : length = len( aList ) cList = [] i = 0 while i < length : cList.append( aList[i] + bList[i] ) i += 1 return cList #### a b d e = = = = main ####

[1, 2, 3] [10, 20, 30] [100, 200, 300, 400, 500] [ 5, 4, 3, 2, 1]

print addLists(a, b) print addLists(d, e) 27

A.6. STRINGS

APPENDIX A. ANSWERS

A.6

Strings

A6.1 def countCap( s ) : count = 0 length = len( s ) i = 0 while i < length : if A <= s[i] and s[i] <= Z : print s[i] count += 1 i += 1 return count

A.7

File I/O

A7.2 inFile = open("sample.csv", "r") dataList = inFile.readlines() inFile.close() for line in dataList : line = line.strip() tokens = line.split(,) print tokens[1], tokens[0]

A.8

Dictionaries

A8.5 def printMax( data, col ) : if col == "age" : index = 0 elif col == "weight" : index = 1 maxVal = -1 # neither weight nor age can be less than zero

keys = data.keys() for k in keys : if data[k][index] > maxVal : maxVal = data[k][index] maxName = k 28

APPENDIX A. ANSWERS

A.8. DICTIONARIES

print "%s has the maximum %s" % (maxName, col)

###

main

###

data = {"Tom" : [43, 185], "John" : [50, 170], "Susan" : [35, 125] } printMax(data, "age") printMax(data, "weight")

29

You might also like