======================== Decisions \& Repetitions ======================== Preliminary exercises --------------------- You will learn the most from the exercises in this section, if you check your answers in this order: (1) check if you can find your answer in the reader, (2) try it out in a .py script or in the interactive window. Decisions ~~~~~~~~~ **Exercise 2.1** rectangle or square? **2.1a.** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python width_1 = 3.0 height_1 = 3.0 if width_1 == height_1: print('rectangle 1 is a square') **2.1b.** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python width_2 = 4.0 height_2 = 5.0 if width_2 == height_2: print('rectangle 2 is a square') **Exercise 2.2** handing out cookies **2.2a** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python nr_cookies = 10 nr_children = 5 cookies_per_child = nr_cookies // nr_children print("every child gets", cookies_per_child, "cookies") **2.2b** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python nr_cookies = 4 nr_children = 0 cookies_per_child = nr_cookies // nr_children print("every child gets", cookies_per_child, "cookies") **2.2c** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python nr_cookies = 10 nr_children = 2 if nr_children >= 1: cookies_per_child = nr_cookies // nr_children print("every child gets", cookies_per_child, "cookies") else: print("there must be at least 1 child to give cookies") **2.2d** What is the output of the following code fragment? Try to understand why your answer is right or wrong. .. code-block:: python nr_cookies = 4 nr_children = 0 if nr_children >= 1: cookies_per_child = nr_cookies // nr_children print("every child gets", cookies_per_child, "cookies") else: print("there must be at least 1 child to give cookies") **Exercise 2.3** the traffic light Suppose we have the following code to help decide what to do near a traffic light: .. code-block:: python color = input("what is the color of the trafic light? ") if color == 'green': print("push the gas pedal!") elif color == 'orange': print("brake if you can ...") else: print('slam the brake!') **2.3a** What is the output if the user runs the code and enters 'orange'? **2.3b** What is the output if the user runs the code and enters 'green'? **2.3c** What is the output if the user runs the code and enters 'red'? **2.3d** (advanced, can be skipped) Does the code make a distinction between 'red' and an unknown color like 'blue'? Can you modify the code so the code warns the user of an 'unknown color'? **Exercise 2.4** the side of a square Here are two code fragments to calculate the side of a square. They are almost identical: .. code-block:: python # fragment 1 import math area = float(input("what is the area of the square? ")) if area >= 0: side = math.sqrt(area) print('the side of this square =', side) # fragment 2 import math area = float(input("what is the area of the square? ")) if area >= 0: side = math.sqrt(area) print('the side of this square =', side) **2.4a** Will the code fragments below produce the same output when the user enters 16.0 or not? Why (not)? **2.4b** Will the code fragments below produce the same output when the user enters a negative number or not? Why (not)? Conditional Repetitions ~~~~~~~~~~~~~~~~~~~~~~~ **Exercise 2.5** the 'conversation' .. code-block:: python print('bla bla bla bla bla ...') answer = input('would you like to continue our conversation? ') while answer == 'yes': print('bla bla bla bla bla ...') answer = input('would you like to continue our conversation? ') print('I enjoyed that!') **2.5a.** What would be the output if the user would enter 'yes', 'yes', 'no'? **2.5b.** What would be the output if the user would enter 'yes', 'sure', 'no'? **Exercise 2.6** pouring tea .. code-block:: python print('I will pour you a nice cup-of-tea.') print('just say when ...') print('pouring ...') word = input() while word != 'when': print('pouring ...') word = input() print("You're welcome!") **2.6a.** What would be the output if the user would only press return (i.e. enter '')? **2.6b.** What would be the output if the user would enter '', '', 'stop', 'when'? **Exercise 2.7** the count-down timer The following code fragment counts a number down (like an egg-timer). .. code-block:: python nr_ticks = int(input('how many ticks? ')) while nr_ticks > 0: print(nr_ticks, 'ticks left') nr_ticks = nr_ticks - 1 print(nr_ticks, 'ticks left') print('done!') **2.7a** What will be the output when the user enters 5? **2.7b** What will be the output when the user enters 0? **2.7c** What will be the output when the user enters a negative integer e.g. -1? Comparisons and Boolean expressions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Programming decisions and repetitions requires understanding of conditions and boolean expressions. This section helps you to get a better understanding quickly. **Exercise 2.8** Predict the result (True or False) of the following Boolean expressions. You may assume that x is 1. :: a. True and (3 > 4) b. not (x > 0) and (x > 0) c. (x > 0) or (x < 0) d. (x > 1) or (x < 0) e. (x != 0) or (x == 0) f. (x >= 0) or (x < 0) Check your answers with a program or the IDLE console. If you didn't get it right, explain for yourself why you were wrong. **Exercise 2.9** Predict the result of the following Boolean expressions, assuming x is 4 and y is 5: :: a. x >= y >= 0 b. x <= y >= 0 c. x != y == 5 d. (x != 0) or (x == 0) Check your answers with a program or the IDLE console. If you didn't get it right, try to explain why. **Exercise 2.10** **2.10a.** Write a Boolean expression that evaluates to True if variable *num* is between 1 and 100. **2.10b.** Write a Boolean expression that evaluates to True if variable *num* is between 1 and 100 or *num* is negative. Check your answers with a little program that takes *num* as user input. Test at least with these input values for *num*: -1, 0, 1, 100 and 101. The answers should be: :: -1: (a) False, (b) True 0: (a) False, (b) False 1: (a) True, (b) True 100: (a) True, (b) True 101: (a) False, (b) False. **Exercise 2.11** Are these conditions equivalent? (Equivalent means that they are always both True or both False, no matter what the value of x is.) - x >= 1 and x < 10 - 1 <= x < 10 Check your answer by writing a little program that evaluates both expressions for user input of x. Test with these input values: 0, 1, 5, 9 and 10 and any other value that you think you need to prove your answer. **Exercise 2.12** Suppose, when you run the following program, you enter input 2, 3, 6 from the console. What will be the output? .. code-block:: python x = int(input("Enter x: ")) y = int(input("Enter y: ")) z = int(input("Enter z: ")) print("(x < y and y < z) is", x < y and y < z) print("(x < y or y < z) is", x < y or y < z) print("not (x < y) is", not (x < y)) print("(x < y < z) is", x < y < z) print("not(x < y < z) is", not (x < y < z)) Check your answers by running the program. If you didn't get it right, try to understand why. **Exercise 2.13** Write a Boolean expression that evaluates to true if age is greater than 13 and less than 18. Test your expression with a little program with the following user input: 12, 13, 14 and 17, 18, 19. **Exercise 2.14** **2.14a.** Write a Boolean expression that evaluates to True if weight is greater than 50 kg **or** height is greater than 160 cm. **2.14b.** Write a Boolean expression that evaluates to True if weight is greater than 50 kg **and** height is greater than 160 cm. **2.14c.** Write a Boolean expression that evaluates to True if either weight is greater than 50 **or** height is greater than 160, but **not both** (in common english this is called either-or). Test your 'either-or' piece of code in a little test program. Here is correct sample output: :: weight is 48 and height is 150 either weight greater than 50 or heigth greater than 160: False weight is 55 and height is 159 either weight greater than 50 or heigth greater than 160: True weight is 49 and height is 162 either weight greater than 50 or heigth greater than 160: True weight is 58 and height is 165 either weight greater than 50 or heigth greater than 160: False If you did not get it correct, explain why not and correct it. Programming Exercises --------------------- Decisions ~~~~~~~~~ **Exercise 2.15 The a,b,c formula revisited** The solution for exercise 1.5a was not ideal: if :math:`b^2 - 4ac < 0` then the calculation of **math.sqrt()** causes the program to crash (e.g. try it with a = 1, b = 2, c = 3). Let's correct this unwanted behavior. **2.15a.** Improve the program, so that if :math:`b^2 - 4ac < 0` it no longer crashes, but outputs that there is no solution to the equation. Here are two sample runs: :: please enter a: 1 please enter b: 2 please enter c: 3 The equation has no solutions. and :: please enter a: 1 please enter b: 3 please enter c: 1 The equation has solutions: x1 = -2.62 x2 = -0.38 Hint: this problem can be solved in two ways, either with two **if** statements, or with one **if-else** statement. **2.15b.** additional challenge: if you want some more challenge, can you also distinguish the case where :math:`b^2 - 4ac = 0` and output that there is only one solution, and printing the unique solution in that case? **Exercise 2.16 Logging in** **2.16a.** Write a program that asks the user to input a username and a password. It then gives feedback on whether the combination of username/password is correct or not. For simplicity you may assume there is only one user with username 'Superman' and password 'Kryptonite'. **2.16b.** Additional challenge: make the check on the username independent of case, for example, 'SUPERMAN', 'superman', 'SuPeRmAn' are all equivalent usernames. **Exercise 2.17 Addition Learning Program** **2.17a.** Write a program that generates two random integers under 100 and prompts the user to enter the sum of these two integers. The program then reports if the answer is correct or not. Here is code that draws a random number between 1 and 100: .. code-block:: python import random number = random.randint(1, 100) Here are two sample runs: :: 84 + 13 = ? please enter answer: 97 correct! and :: 57 + 22 = ? please enter answer: 66 you need more practise! **2.17b.** Challenge: Extend the program of 2.17a, so the user can continue practising until he or she wants to stop. Here is a sample run: do you want an exercise? yes 36 + 26 = 62 correct! do you want another exercise? yes 75 + 5 = 81 you need more practise! do you want another exercise? no Hint: you need a **while** statement to solve this exercise. **2.17c.** Additional Challenge: change the program of 2.17a or 2.17b to have the question and answer from the user on the same line. Here is a sample run: :: 84 + 13 = 97 correct! Hint: you need to convert the numbers to string with the **str( )** function. **Exercise 2.18 Number Sorting Program** **2.18a.** Write a program that prompts the user to enter two integers and displays them in increasing order, **without** using the built-in **sort( )** function. Here are two sample runs: :: number 1: 4 number 2: 5 correct order: 4 5 and :: number 1: 7 number 2: 3 correct order: 3 7 **2.18b.** Write a program that prompts the user to enter three integers and displays them in increasing order. Here are two sample runs: :: number 1: 7 number 2: 13 number 3: 11 correct order: 7 11 13 and :: number 1: 13 number 2: 7 number 3: 11 correct order: 7 11 13 **Exercise 2.19 Scissors Rock Paper Game** **2.19a.** Write a program that plays the popular scissor-rock-paper game (dutch: steen-papier-schaar). (Scissors can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates a number 0, 1, or 2 representing scissor, 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. Here is code to draw a random number 0, 1 or 2: .. code-block:: python import random number = random.randint(0,2) Here are two sample runs: :: scissors (0), rock (1), paper (2). what do you play? 1 The computer is scissors. You are rock. You won. and: :: scissors (0), rock (1), paper (2). what do you play? 2 The computer is paper. You are paper too. It is a draw. **2.19b.** If you like a real challenge, try to write the program for the famous Rock-Paper-Scissors-Lizard-Spock Game invented by Sam Kass and used in the series 'The Big Bang Theory'. In the extension Lizzard is 3 and Spock is 4. A random number is drawn by **random.randint(0,4)**. For an extensive explanation of the game see this url: http://bigbangtheory.wikia.com/wiki/Rock_Paper_Scissors_Lizard_Spock. Repetitions (while) ~~~~~~~~~~~~~~~~~~~ **Exercise 2.20 Turtle Circles** **2.20a.** Write a program that produces turtle output like in Figure 4. The radius of the smallest and largest circles are 10 and 100. Of course you use a loop for this! .. figure:: ./images/06_screen_shot_ex_2.13a.png :width: 375px :align: center :height: 271px :alt: alternate text :figclass: align-center **2.20b.** Write a program that produces turtle zigzag output like in Figure 6. The user can enter the number of zigzags before drawing. Figure 5 show the output for nr_zigzags of 10. .. figure:: ./images/07_screen_shot_ex_2.13b.png :width: 520px :align: center :height: 221px :alt: alternate text :figclass: align-center **Exercise 2.21 Number Guessing Game** **2.21a.** Write a program that asks the user for a number (between 1 and 100) until he/she guesses the secret number. The program should give feedback about whether the number is too low or too high. You may choose a fixed 'secret' number (e.g. secret = 77). Here is sample output: :: make a guess between 1 and 100: 66 66 is too low make a guess between 1 and 100: 88 88 is too high make a guess between 1 and 100: 77 77 is correct! Test it thoroughly before continuing with b. **2.21b.** Make the program of 2.21a. more interesting by choosing a random secret number. Here is code how to do that: .. code-block:: python import random secret = random.randint(1, 100) Test it thoroughly before continuing with c. **2.21c.** Expand the program of 2.21b. (or 2.21a. if you did not succeed with 2.21b.) to allow multiple games. Every game should have a new (random) secret number. Here is a sample run: :: do you want to guess a secret number? yes make a guess between 1 and 100: 50 50 is too low make a guess between 1 and 100: 75 75 is too low make a guess between 1 and 100: 78 78 is correct! do you want to guess another secret number? yes make a guess between 1 and 100: 35 35 is too low make a guess between 1 and 100: 85 85 is too high make a guess between 1 and 100: 78 78 is too low make a guess between 1 and 100: 80 80 is correct! do you want to guess another secret number? no thank you for playing **Exercise 2.22 Counting Numbers** Write a program that reads an unspecified number of integers (the input ends when the user enters 0). The program then displays: - how many positive values have been entered - how many negative values have been entered - the total value of the input values - the average value of the input values. Display the average as a floating-point number. (Hint: remember to ignore the 0 at the end.) Here are two sample runs: :: Enter an integer (0 to stop): 1 Enter an integer (0 to stop): 2 Enter an integer (0 to stop): -1 Enter an integer (0 to stop): 3 Enter an integer (0 to stop): 0 The number of positives is 3 The number of negatives is 1 The total is 5 The average is 1.25 and: :: Enter an integer (0 to stop): 0 You didn't enter any numbers. **Exercise 2.23 Turtle Remote Control** Write a program that asks the user for an actionand then lets the turtle perform that action. The program should continue until the user tells it to stop. The actions are: - 'f': the turtle moves 30 pixels forward - 'l': the turtle turns 45 degrees to the left - 'r': the turtle turns 45 degrees to the right - 'u': the turtle lifts the pen from the canvas - 'd': the turtle puts the pen down on the canvas - 'q': the program quits - any other action 'X': the program prints "I don't know action X" Here is a sample run :: turtle action: f turtle action: l turtle action: f turtle action: l turtle action: f turtle action: r turtle action: f turtle action: u turtle action: r turtle action: r turtle action: r turtle action: r turtle action: f turtle action: f turtle action: f turtle action: d turtle action: f turtle action: b i don't know action b turtle action: q which should produces this picture: .. figure:: ./images/08_screen_shot_ex_2.16.png :width: 427px :align: center :height: 347px :alt: alternate text :figclass: align-center © Copyright 2021, dr. P. Lambooij last updated: |today|