let's learn python: exercises - prince of songkla...

17
1 Let's Learn Python: Exercises Saenthong School, January February 2016 Teacher: Aj. Andrew Davison CoE, PSU Hat Yai Campus E-mail: [email protected] Starting with Python 1 Solve the following problems inside IDLE, or by writing small programs: a. Three people eat dinner at a restaurant and want to split the bill. The total is 352 Baht, and they want to leave a 15% tip. How much should each person pay? b. Calculate the area and perimeter of a rectangular room, 12.5 meters by 16.7 meters. c. If there are 3 buildings with 25 Ninjas hiding on each roof and 2 tunnels with 40 Samurai hiding inside each tunnel, how many Ninjas and Samurai are about to do battle? 2. Practice using Python as a calculator: a. The volume of a sphere with radius r is 4/3 π r 3 . What is the volume of a sphere with radius 5? Hints: π is about 3.141592, and 392.6 is the wrong answer! b. Suppose the cover price of a book is 249 Baht, but bookstores get a 40% discount. Shipping costs 30 Baht for the first copy and 15 Baht for each additional copy. What is the total cost for 60 copies? 3. Let x = 8 and y = 2. Write the values of the following expressions: a. x + y * 3 b. (x + y) * 3 c. x ** y d. x % y e. x / 12.0 f. x // 6 4. Let x = 4.66. Write the values of the following expressions: a. round(x) b. int(x) 5. Write a program that calculates and prints the number of minutes in a year. 6. Light travels at 3 * 10 8 meters per second. A light-year is the distance a light beam travels in one year. Write a program that calculates and displays the value of a light-year. 7. How does a Python programmer round a float value to the nearest int value? 8. How does a Python programmer add a number to the end of a string? Variables 1. Make a variable, and assign a number to it. Then display the variable using print().

Upload: buixuyen

Post on 22-May-2018

234 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

1

Let's Learn Python: Exercises

Saenthong School, January – February 2016

Teacher: Aj. Andrew Davison

CoE, PSU Hat Yai Campus

E-mail: [email protected]

Starting with Python

1 Solve the following problems inside IDLE, or by writing small programs:

a. Three people eat dinner at a restaurant and want to split the bill. The total is 352 Baht,

and they want to leave a 15% tip. How much should each person pay?

b. Calculate the area and perimeter of a rectangular room, 12.5 meters by 16.7 meters.

c. If there are 3 buildings with 25 Ninjas hiding on each roof and 2 tunnels with 40

Samurai hiding inside each tunnel, how many Ninjas and Samurai are about to do

battle?

2. Practice using Python as a calculator:

a. The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with

radius 5? Hints: π is about 3.141592, and 392.6 is the wrong answer!

b. Suppose the cover price of a book is 249 Baht, but bookstores get a 40% discount.

Shipping costs 30 Baht for the first copy and 15 Baht for each additional copy. What

is the total cost for 60 copies?

3. Let x = 8 and y = 2. Write the values of the following expressions:

a. x + y * 3

b. (x + y) * 3

c. x ** y

d. x % y

e. x / 12.0

f. x // 6

4. Let x = 4.66. Write the values of the following expressions:

a. round(x)

b. int(x)

5. Write a program that calculates and prints the number of minutes in a year.

6. Light travels at 3 * 108 meters per second. A light-year is the distance a light beam travels

in one year. Write a program that calculates and displays the value of a light-year.

7. How does a Python programmer round a float value to the nearest int value?

8. How does a Python programmer add a number to the end of a string?

Variables

1. Make a variable, and assign a number to it. Then display the variable using print().

Page 2: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

2

2. Modify the variable of question 1, either by replacing the old value with a new value, or

by adding something to the old value. Display the new value using print().

3. Get Python to calculate the number of minutes in a week using variables. Use variables

called daysPerWeek, hoursPerDay, and minsPerHour, and then multiply them together.

4. How many minutes would there be in a week if there were 26 hours in a day? (Hint:

Change the hoursPerDay variable in question 3.)

5. Assume that the foo variable has the value 33. What is the value of foo after the command

foo = foo*2 executes?

a. 35

b. 33

c. 66

6. The temperature converter program (tempConverter.py) outputs a number that shows too

many decimal places. Modify the program to display at most two decimal places in the

output number.

Input

1. Write a program that asks for your first name, your last name, and then prints a message

containing both your first and last names.

2. Write a program that asks for the dimensions (in meters) of a rectangular room, and then

calculates and displays the total amount of carpet needed to cover the room.

3. Write a program that does the same as in question 2, but also asks for the cost per square

meter of carpet. Then have the program display three things:

The total amount of carpet, in square meters

The total amount of carpet, in square cms

The total cost of the carpet

4. Write a program to calculate the volume and surface area of a sphere from its radius,

given as input. Some formulas that might be useful: V = 4/3 πr3, A = 4 πr2.

5. Write a program that calculates the cost per square inch of a circular pizza, given its

diameter and price as input. A = πr2.

6. You can calculate the surface area of a cube if you know the length of an edge. Write a

program that takes the length of an edge (an integer) as input and prints the cube’s surface

area as output.

7. An object’s momentum is its mass multiplied by its velocity. Write a program that

accepts an object’s mass (in kilograms) and velocity (in meters per second) as inputs, then

outputs its momentum.

Random and Maths

1. Write commands using the random module to print the following.

a. A random integer in the range 0 to 10

b. A random float in the range -0.5 to 0.5

Page 3: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

3

c. A random number representing the roll of a six-sided die

d. A random number representing the sum resulting from rolling two six-sided dice

e. A random float in the range -10.0 to 10.0

2. The math module includes a pow() function that raises a number to a given power. The

first argument is the number, and the second argument is the exponent. Write code that

imports this function and calls it to print the values 82 and 54.

3. The expression round(23.67) evaluates to which of the following values?

a. 23

b. 23.7

c. 24.0

4. Write an import statement that imports just the functions sqrt() and log() from the math

module.

5. Translate each of the following math expressions into a Python command. Assume that

the math library has been imported (using import math).

6. Write a program that accepts four floats representing the points (x1,y1) and (x2,y2) and

determines the distance d between them. Use 𝑑 = √(𝑦2 − 𝑦1)2 + (𝑥2 − 𝑥1)2

7. Write a program to calculate the area of a triangle given the length of its three sides a, b,

and c. Use s = 𝑎+𝑏+𝑐

2 and A = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)

8. Write a program to calculate the length of a ladder required to reach a given height when

leaned against a wall. The height h and angle A of the ladder are given as inputs.

Use length = ℎ

sin 𝐴

9. The area of a hexagon can be calculated using the following formula (s is the length of a

side of the hexagon):

Write a program that prompts the user to enter the side of a hexagon, and then displays its

area.

Turtles

1. The Müller-Lyer illusion is shown below. Although the lines are the same length, they

appear to be unequal. Draw this illusion with turtle graphics.

Page 4: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

4

2. Draw all following shapes using turtle graphics.

a. A pentagon of length 50.

b. A hexagon of length 60.

c. An octagon of length 80.

3. Write a turtle program to draw a box without corners, like this one:

4. Write a turtle program to draw the shape:

5. Write a turtle program to draw the star shape:

6. Write a turtle program to draw the heart shape:

Hints: the shape is made of two semi-circles and two straight lines.

7. Write a turtle program to draw the spiral shape:

Page 5: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

5

I do not mind if the spiral looks different from this one (there are many kinds of spirals).

EasyGui

1. Change the temperature conversion program (tempConverter.py) from the "Variables"

slides to use easygui input and output instead of input() and print().

2. Write a program that asks for your name, house number, street, city, province, and zip

code using EasyGui dialog boxes. The program should display the full address in another

dialog box.

3. Write a program that asks for the dimensions (in meters) of a rectangular room, and then

calculates and displays the total amount of carpet needed to cover the room. Use easygui

for the input and output instead of input() and print()

If Statements

1. Assume that x is 3 and y is 5. Write the values of the following expressions:

a. x == y

b. x > y - 3

c. x <= y - 2

d. x == y or x > 2

e. x != 6 and y > 10

f. x > 0 and x < 100

2. A complex test using the and operator returns True when

a. both test parts are true

b. one test part is true

c. neither test part is true

3. Does the test count > 0 and total/count > 0 contain an error? If not, why not?

4. What if statement would you use to check if a number was greater than 30 but less than

or equal to 40?

5. What if statement would you use to check if the user entered the letter “Q” in either

uppercase or lowercase?

6. Write an if statement that prints the string “That’s too many” if the ninjas variable

contains a number that’s less than 50. Or it prints “It’ll be a struggle, but I can take ’em”

if the number is less than 30. It prints “I can fight those ninjas!” if the number is less than

10.

Page 6: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

6

7. Assume that x refers to a number. Write code that prints the number’s absolute value

without using Python’s abs() function.

8. Assume that the variables x and y refer to two strings. Write code that prints these strings

in alphabetical order.

9. The variables x and y refer to numbers. Write code that asks the user for a maths

operation (i.e. +, -, /, *), and prints the value obtained by applying that operation to x and

y.

10. Write a program that finds the average of three exam scores.

11. A teacher gives quizzes marked out of 5 that are graded on the scale 5-A, 4-B, 3-C, 2-D,

1-F, 0-F. Write a program that accepts a quiz score as input and prints out the grade.

12. A teacher gives 100-point exams that are graded on the scale 80–100:A, 70–79:B, 60–

69:C, 50–59:D, 0-49:F. Write a program that accepts an exam score as input and prints

out the grade.

13. The body mass index (BMI) is calculated as a person’s weight (in pounds) times 720,

divided by the square of the person’s height (in inches). A BMI in the range 19–25 is

healthy. Write a program that calculates a person’s BMI and prints a message telling

whether they are above, within, or below the healthy range.

14. The international standard letter/number mapping on the telephone is:

Write a program that prompts the user to enter a letter and displays its number.

15. Write a program that prompts the user to enter a letter and check whether the letter is a

vowel (a, e, i, o, u) or consonant.

16. Write a program which prompts the user for a 3 digit integer and checks whether the

middle digit is equal to the sum of the other two digits. The program should print an

appropriate response. Hint: use the // and % operations.

17. The speeding ticket fine in Hat Yai is 5000 Baht plus 500 for each mph over the limit plus

a penalty of 2000 for any speed over 90 mph. Write a program that inputs a speed limit

and a clocked speed, and either prints a message indicating the speed was legal, or prints

the amount of the fine if the speed was illegal.

18. A Western calendar year is a leap year if it is divisible by 4, unless it is a century year that

is not divisible by 400. (1800 and 1900 are not leap years while 1600 and 2000 are.)

Write a program that calculates whether an input Western calendar year is a leap year.

19. Suppose you shop for rice in two different packages. You would like to write a program

to compare the cost. The program prompts the user to enter the weight and price of the

each package and displays the one with the better price.

Page 7: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

7

20. A shipping company uses the following function to calculate the cost (in Baht) of

shipping based on the weight of the package (in kg).

Write a program that prompts the user to enter the weight of the package and display the

shipping cost. If the weight is greater than 50, display the message “The package cannot

be shipped.”

21. A store is having a sale. It’s giving 10% off purchases of 100 Baht or lower, and 20% off

purchases of greater than 100 Baht. Write a program that asks for the purchase price and

displays the discount (10% or 20%), and the final price.

22. Write a program that randomly generates an integer between 1 and 12 and displays the

English month name January, February, …, December for the number 1, 2, …, 12,

accordingly.

23. Write a program that accepts the lengths of three sides of a triangle as inputs. The

program output should say whether or not the triangle is an equilateral triangle.

24. Write a program that accepts the lengths of three sides of a triangle as inputs. The

program output should indicate whether or not the triangle is a right triangle. Hint: use

the Pythagorean theorem to test the sides.

25. A soccer team is looking for boys from ages 12 to 16 to play on their team. Write a

program to ask the user’s age and whether the user is male or female (using “m” or “f”).

Print a message saying whether the person is allowed to play on the team.

26. You’re on a long car trip and arrive at a gas station. It’s 200 km to the next station. Write

a program to figure out if you need to buy gas here, or if you can wait for the next station.

The program should ask these questions:

How big is your gas tank, in liters?

How full is your tank (in percent – for example, half full == 50)?

How many km per liter can your car travel?

The output should look something like this

Size of tank: 60

percent full: 40

km per liter: 10

You can go another 240 km

The next gas station is 200 km away

You can wait for the next station.

or

Size of tank: 60

percent full: 30

km per liter: 8

You can go another 144 km

The next gas station is 200 km away

Get gas now!

Page 8: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

8

Loops

1. What numbers would range (1, 8) give you inside a loop?

2. What numbers would range (8) give you inside a loop?

3. What numbers would range (2, 9, 2) give you inside a loop?

4. What numbers would range (10, 0, -2) give you inside a loop?

5. How many times does a loop with the header for count in range(10): execute the

statements in its body?

a. 9 times

b. 10 times

c. 11 times

6. What is the output of the loop for count in range(5): print(count)?

a. 1 2 3 4 5

b. 1 2 3 4

c. 0 1 2 3 4

7. Write the outputs of the following loops: a. for count in range(5):

print(count + 1, end=" ")

b. for count in range(1, 4):

print(count, end=" ")

c. for count in range(1, 6, 2):

print(count, end=" ")

d. for count in range(6, 1, -1):

print(count, end=" ")

8. Show the output that would be printed by the following program fragments.

a. for ch in "aardvark":

print(ch)

b. for w in string.split("Now is the winter of our discontent..."):

print(w)

c. for w in string.split("Mississippi", "i"):

print(w)

d. msg = ""

for s in string.split("secret","e"):

msg = msg + s

print(msg)

9. What special word do you use to stop the current loop and jump ahead to the next loop?

10. Translate the following for loops into equivalent while loops: a. for count in range(100):

print(count)

b. for count in range(1, 101):

print(count)

c. for count in range(100, 0, -1):

print(count)

11. Consider the following code:

count = 5

while count > 1:

Page 9: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

9

print(count, end=" ")

count -= 1

What is the output produced by this code?

a. 1 2 3 4 5

b. 2 3 4 5

c. 5 4 3 2 1

d. 5 4 3 2

12. Consider the following code:

count = 1

while count <= 10:

print(count, end=" ")

Which of the following describes the error in the code?

a. The loop is off by 1.

b. The loop control variable is not properly initialized.

c. The comparison points the wrong way.

d. The loop is infinite.

13. Consider the following code:

sum = 0.0

while True:

number = input("Enter a number: ")

if number == "":

break

sum += float(number)

How many loops does this code carry out?

a. none

b. at least one

c. zero or more

d. ten

14. Modify the multiplication table program (EightTimes.py). Ask which table the user

wants, and ask him how high the table should go. For example, the user would enter 5 and

20 to get the five-times table up to 20.

15. Assume that the variable testString refers to a string. Write a loop that prints each

character in this string separately.

16. Write a loop that counts the number of space characters in a string. Recall that the space

character is ' '.

17. Write a loop that prints even numbers until it reaches your year of age. If your age is an

odd number, then it should print out odd numbers until it reaches your age. For example,

if you are 14, it would print out:

2 4 6 8 10 12 14

18. The factorial of an integer n is the product of all of the integers between 1 and n (e.g.

factorial 5 == 1x2x3x4x5). Write a while loop that calculates the factorial for a given

input integer n.

19. Add a loop to the tempConverter.py program from the "Variables" slides so that it

executes 5 times before quitting (i.e., it converts 5 temperatures in a row).

Page 10: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

10

20. Modify the tempConverter.py program from the "Variables" slides. It should now prints a

table of Fahrenheit to Celsius equivalents for every 20 degrees from 20°F to 220°F.

21. Write a program to calculate the sum of the series:

1/2 + 3/4 + 5/6 + … + 99/100

22. Write a program which calculates

1/1 + 1/3 + 1/5 + 1/7 + ... + 1/21

23. The mathematician Gottfried Leibniz developed the following method to approximate the

value of π:

π/4 = 1 – 1/3 + 1/5 – 1/7 + . . .

Write a program that allows the user to specify the number of fractions used in this

approximation, and then displays the resulting value.

24. Write a program to find the sum of the n terms in the series:

S = 1 + x + x2 + x3 + xn, for given input values of x and n.

25. Write a program to print the sum of the first 20 multiples of 12.

26. Write a program that calculates the following values:

a. Sum of the first n numbers: 1 + 2 + 3 + … + n

b. Sum of the first n odd numbers: 1 + 3 + 5 + … + 2n-1

c. Sum a series of numbers entered by the user until the value 999 is entered. Note: 999

should not be part of the sum.

27. Write a program that reads an unspecified number of integers, determines how many

positive and negative values have been read, and calculates the total and average of the

input values (not counting zeros). Your program ends with the input 0. Display the

average as a floating-point number.

28. Write a program that prints the following table (note that 1 mile is 1.609 kilometers):

Miles Kilometers

1 1.609

2 3.218

...

9 14.481

10 16.090

29. Write a program that prints two tables side-by-side:

Miles Kilometers | Kilometers Miles

1 1.609 | 20 12.430

2 3.218 | 25 15.538

...

9 14.481 | 60 37.290

10 16.090 | 65 40.398

30. Numerologists claim to be able to determine a person’s character based on the “numeric

value” of a name. The value of a name is determined by summing up the values of the

letters of the name where ’a’ is 1, ’b’ is 2, ’c’ is 3 etc., up to ’z’ being 26.

Page 11: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

11

For example, the name “Andrew” has the value 1 + 13 + 4 + 18 + 5 + 23 = 64 (which

happens to be a very good number). Write a program that calculates the numeric value of

a single name provided as input.

31. Extend your solution to the previous question to allow the calculation of a complete name

such as “Andrew Davison” or “James Bond.” The total value is the sum of the numeric

value for each word in the name.

32. Write a program that plays the popular scissors-rock-paper game. (Scissors can cut paper,

rock can break scissors, and paper can wrap rock.) The program randomly generates a

number 0, 1, or 2 representing scissors, rock, and paper. The program prompts the user to

enter a number 0, 1, or 2 and displays a message indicating whether the user or the

computer wins, loses, or draws. Let the user play has many times as they want until they

enter -1.

33. Write a program that simulates tossing a coin one million times, and displays the number

of heads and tails at the end.

34. Write a program that takes an integer n as input, uses random to print n random values

between 0 and 1, and then prints their average value.

35. Write a program to test the divisibility by both 3 and 7 of numbers between 1-100.

36. The Syracuse (also called the Collatz or Hailstone) sequence is generated by starting

with a natural number and repeatedly applying the following function until it returns 1.

𝑠𝑦𝑟(𝑥) = {𝑥/2 if x is even3𝑥 + 1 if x is odd

For example, the Syracuse sequence starting with 5 is: 5, 16, 8, 4, 2, 1.

It is an open question in maths whether this sequence will always end up at 1 for every

possible starting value. Write a program that gets a starting value from the user and prints

its Syracuse sequence.

Nested Loops

1. Write a program that prompts the user to enter the size of the side of a square, then

displays a hollow square of that size made of asterisks (*'s), like the one below. Your

program should work for squares of all side lengths between 1 and 10.

2. Write a program that creates a check board of asterisks, like the one below. Your program

should work for all side lengths between 8 and 12.

Page 12: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

12

3. Write a program that displays the following triangle patterns separately, one below the

other. Hint: The last two patterns require that each line begin with spaces.

4. Write a program that prints the following diamond shape.

5. Modify the program you wrote in the last question to read in an odd number in the range

1 to 19 to specify the number of rows in the diamond. Your program should then display

a diamond of that size.

6. Write a program that reads five numbers between 1 and 30. For each number that’s read,

your program should display the same number of adjacent asterisks (*'s). For example, if

your program reads the number 7, it should display *******. Display the bars of asterisks

after you read all five numbers.

7. Write a program that displays all possible combinations for picking two numbers from

integers 1 to 7. Also display the total number of all combinations.

8. Write a program to print the factorial value of numbers from 5 to 15. The factorial of an

integer n is the product of all of the integers between 1 and n (e.g. factorial 5 ==

1x2x3x4x5).

9. A right triangle can have sides whose lengths are all integers. The set of three integer

values for the lengths of the sides of a right triangle is called a Pythagorean triple. The

lengths of the three sides must satisfy the relationship that the sum of the squares of two

of the sides is equal to the square of the hypotenuse.

Write a program that displays a table of the Pythagorean triples for side1, side2 and the

hypotenuse, all no larger than 100. Use a triple-nested for loop that tries all the

possibilities. The first four triples are: (3, 4, 5), (5, 12, 13), (8, 15, 17), and (7, 24, 25).

Page 13: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

13

Lists, Tuples, Dictionaries

For questions 1–6, assume that the variable data refers to the list [10, 20, 30].

1. data[1] is

a. 10

b. 20

2. data[1:3] is

a. [10, 20, 30]

b. [20, 30]

3. data.index(20) is

a. 1

b. 2

c. True

4. data + [40, 50] is

a. [10, 60, 80]

b. [10, 20, 30, 40, 50]

5. After data[1] = 5, data is

a. [5, 20, 30]

b. [10, 5, 30]

6. After data.insert(1, 15), the original data is

a. [15, 10, 20, 30]

b. [10, 15, 30]

c. [10, 15, 20, 30]

For questions 7–9, assume that the variable info refers to the dictionary {“name”:”Sandy”,

“age”:17}.

7. list(info.keys()) is

a. (“name”, “age”)

b. [“name”, “age”]

8. info.get(“hobbies”, None) is

a. “knitting”

b. None

c. 1000

9. The function to remove an entry from a dictionary is

a. delete

b. pop

c. remove

10. Which of the following are immutable data structures?

a. dictionaries and lists

b. strings and tuples

11. Assume that the variable data refers to the list [5, 3, 7]. Write the values of the following:

a. data[2]

b. data[-1]

c. len(data)

d. data[0:2]

Page 14: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

14

e. 0 in data

f. data + [2, 10, 5]

g. tuple(data)

12. Assume that the variable data refers to the list [5, 3, 7]. Write code that does the

following:

a. Replace the value at position 0 in data with that value’s negation.

b. Add the value 10 to the end of data.

c. Insert the value 22 at position 2 in data.

d. Remove the value at position 1 in data.

e. Add the values in the list newData to the end of data.

f. Locate the index of the value 7 in data.

g. Sort the values in data.

13. Write a program to ask the user for five names. The program should store the names in a

list and print them.

14. Modify the program from question 13 to print both the original list of names and a sorted

list.

15. Modify the program from question 13 to print only the third name the user typed in.

16. Modify the program from question 13 to let the user replace one of the names. He should

be able to choose which name to replace and then type in the new name. Finally, print the

new list.

17. Write a loop that sums all of the numbers in a list named data.

18. Assume that data refers to a list of numbers, and result refers to an empty list. Write a

loop that adds the nonzero values in data to the result list.

19. Write a loop that replaces each number in a list named data with its absolute value.

20. Write a program to find the smallest value in a list of numbers.

21. Implement a two dimensional matrix A using a list of lists. Aij is a saddle point if the

smallest element is in row i and the largest element is in column j. Write a program to

find a matrix's saddle point, if one exist.

22. Write a program to find the second largest number in a list of numbers and print the

position where it occurs.

23. Write a program to print Pascal's triangle. The first 5 rows of the print-out will look like:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

Have the program read in the number of rows that should be printed.

24. Write a program that prompts the user to enter an integer from 1 to 15 and displays a

pyramid, as shown below

Page 15: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

15

25. Write code that prints the following output:

1

1 2 1

1 2 4 2 1

1 2 4 8 4 2 1

1 2 4 8 16 8 4 2 1

1 2 4 8 16 32 16 8 4 2 1

1 2 4 8 16 32 64 32 16 8 4 2 1

1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

26. Write a program which reads the names of three sales people into a list, and their sales

figure for each month for six months into a two dimensional list of lists. The program

then prints the total sales for each sales person, and the grand total for the six month.

27. A palindrome is a sequence of characters that reads the same backward and forward. For

example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554

and 11611. Write a program that reads in a five-digit integer and determines whether it is

a palindrome. If the number is not five digits long, display an error message and allow the

user to enter a new value.

28. Write a program that prompts the user to enter three city names and displays them in

alphabetical order.

29. Assume there are two lists of data about 10 people showing their ages and incomes. Write

a program to calculate the average income of all the people aged between 25 and 30 years

old.

30. Assume that the variable data refers to the dictionary {“b”:20, “a”:35}. Write the values

of the following:

a. data[“a”]

b. data.get(“c”, None)

c. len(data)

d. data.keys()

e. data.values()

f. data.pop(“b”)

g. data # After the pop above

31. Assume that the variable data refers to the dictionary {“b”:20, “a”:35}. Write code that

does the following:

a. Replace the value at the key “b” in data with that value’s negation.

b. Add the key/value pair “c”:40 to data.

c. Remove the value at key “b” in data.

d. Print the keys in data in alphabetical order.

Page 16: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

16

Functions

1. Write a function called even(). This function expects a number as an argument and returns

True if the number is divisible by 2, and returns False otherwise. (Hint: a number is

evenly divisible by 2 if the remainder is 0.)

2. Use the function even() from question 1 to implement the function odd()

3. Write a function called sum(). This function expects two numbers, named low and high,

as arguments. The function calculates and returns the sum of all of the numbers between

low and high, inclusive.

4. The Pythagorean theorem states that the square of the hypotenuse is equal to the sum of

the squares of the other two sides of a right-angled triangle. Write a function named

pyth() which takes the lengths of these two sides as arguments, and returns the triangle’s

hypotenuse.

5. Write a function drawCircle(). This function should take as arguments a Turtle object, the

coordinates of the circle’s center point, and the circle’s radius. The code should draw the

circle by turning 3 degrees and moving a given distance 120 times. Calculate that distance

using the formula 2.0 * π * radius / 120.0.

6. Write a function called drawLine(). This function expects a Turtle object and four

integers as arguments. The integers represent the two end points of a line segment. The

function should draw this line segment with the turtle and do no other drawing.

7. The function drawRectangle() expects a Turtle object and the coordinates of the upper-

left and lower-right corners of a rectangle as arguments. Write this function, which draws

the outline of the rectangle.

8. Write a fillRectangle() function that takes the coordinates of a rectangle’s upper-left and

lower-right corner points and a color string as arguments. The function should fill the

rectangle in the given color.

9. If you are given three sticks, you may or may not be able to arrange them in a triangle.

For example, if one of the sticks is 12 inches long and the other two are 1 inch long, it is

clear that you will not be able to get the short sticks to meet. For any three lengths, there

is a simple test to see if it is possible to form a triangle:

“If any of the three lengths is greater than the sum of the other two, then

you cannot form a triangle. Otherwise, you can."

a. Write a function named isTriangle() that takes three integers as arguments, and

returns True or False depending on whether you can or cannot form a triangle from

sticks with those lengths.

b. Write a function that prompts the user to input three stick lengths, converts them to

integers, and uses isTriangle() to check whether sticks with the given lengths can form

a triangle.

10. Write a function that returns the sum of series of

sin(x) = x - x3/3! + x5/5! - …

up to n terms. Compare the result with the value obtained from math.sin(x) for several

different x and n values.

Page 17: Let's Learn Python: Exercises - Prince of Songkla Universityfivedots.coe.psu.ac.th/Software.coe/learnPython/Exercises.pdf · 1 Let's Learn Python: Exercises Saenthong School, January

17

11. Write a function which takes a string argument and returns a new string where all the

letters are in alphabetical order. For example, the word "andrew" should be returned as

"adenrw".

12. Write a function which takes a string argument and returns a new string where all the

vowels have been deleted.

13. Write a function that return the average of an input argument list. Write a test program

that prompts the user to enter ten double values, invokes the function, and displays the

average value.

14. Write a function that returns the index of the smallest element in a list of integers. If there

are several smallest values, return the index of the first one in the list.

15. Write a function that returns a random number between 1 and 54, excluding the numbers

in the list passed to it as an argument.

16. Write a function that returns a new list by eliminating the duplicate values in the list

passed to it as an argument.

17. The lists list1 and list2 are identical if all their corresponding elements are equal. Write a

function that returns True if list1 and list2 are identical.

18. Write a turtle program that uses a function (or functions) to draw shapes like the

following: