================== Programming Basics ================== Introduction ------------ The 0HV120 exercises are companion material to the 0HV120 Reader and lectures. They are meant to support students in acquiring (their first) experience in programming in Python. Mastering the programming exercises in this manual should prepare students to successfully complete the course. Please pay attention to the *italic* words e.g. *statement* or *function* as they denote programming terms (that will be explained in the lectures and Reader). These exercises support the topics covered in week 1 (roughly speaking, chapter 1 and 2 of the Reader). The exercises are mostly grouped around a particular subject (like programming calculations). Feel free to skip some exercises if you feel you have mastered that particular subject. Before you start these exercises, make sure you have installed Python/IDLE and mastered the exercises in the section 'Appendix: Installation & Getting Started'. Simple Calculations ------------------- **Exercise 1.1 Converting ounces into grams** You want to use an old English (Victorian) recipe for cooking. **1.1a.** Write a program that converts ounces into grams. One ounce is 28.3495231 grams. Here is a sample run: :: please enter the number of ounces: 36 36 ounces is 1020.5828316 grams **1.1b.** Numbers with many decimals are hard to read. Round off your answer to an integer result (no decimals). Here is a sample run: :: please enter the number of ounces: 36 36 ounces is 1021 grams **Exercise 1.2 Converting Fahrenheit to Celcius** Imagine you want to know the weather in America where they measure temperature in Fahrenheit instead of Celsius. **1.2a.** Write a program that reads degrees Fahrenheit from the console and converts it to Celsius and displays the result. The formula for the conversion is as follows: celsius = (5 / 9) * (fahrenheit - 32) Here is a sample run: :: please enter degrees Fahrenheit: 78 78 Fahrenheit is 25.555555555555557 Celsius **1.2b.** Change the output to round the number to 1 decimal. Here is a sample run: :: Enter a degree in Fahrenheit: 55 55 Fahrenheit is 12.8 Celsius **Exercise 1.3 Calculating averages** In many (psychological) experiments you will have to process your results with some statistics. Averaging is one of the simplest statistical analyses. **1.3a.** Write a program that asks for the age of two people and displays their average age. Here is a sample run: :: please enter age 1: 19 please enter age 2: 22 The average age is: 20.5 Remark: the program crashes if you make a typing mistake, e.g. a letter in one of the numbers. Don't worry about that for now, you will learn how to handle situations like that more elegantly later. **1.3b.** Do the same for six people, rounding the result to 2 decimals. Here is a sample run: :: please enter age 1: 19 please enter age 2: 22 please enter age 3: 18 please enter age 4: 25 please enter age 5: 21 please enter age 6: 20 The average age is: 20.83 Remark: You will learn more efficient ways of programming when dealing with many similar variables. **Exercise 1.4 Finding the minimum and maximum in a sequence of numbers** Python has many mathematical operations built-in as *functions* like **abs(x)** (absolute value of x) and **pow(x, y)** (x to the power y). A comprehensive list of all built-in functions can be found here: https://docs.python.org/3/library/functions.html. Write a program that outputs the minimum and maximum values of 5 numbers entered by the user, using the built-in **min( ... )** and **max( ... )** functions. Here is a sample run: :: enter number 1: 6 enter number 2: 9.0 enter number 3: -14 enter number 4: 8.99 enter number 5: 3.14 the lowest number is -14.0 the highest number is 9.0 **Exercise 1.5 Programming mathematical formulas** In many occasions in science and engineering you want to perform calculation of formulas using a computer, so a useful skill is the ability to convert a mathematical formula into a piece of code. In addition to built-in Python functions (like **min()** and **max()**) many more standard mathematical operations can be used by importing module math with **import math**. When you type **help("math")** in the IDLE console you can see all the functions that are supported by this module: https://docs.python.org/3/library/math.html. **1.5a.** Write a program that calculates your savings :math:`P_n` after :math:`n` years, when your starting amount was :math:`P_0` and the yearly interest :math:`r` was constant: .. math:: P_n = P_0\big(1+\frac{r}{100}\big)^n Here is a sample run: :: enter the initial amount P0: 10000 enter the annual interest rate r: 1.5 enter the number of years n: 10 You will have 11605.41 in 10.0 years. **1.5b.** Write a program that calculates the solution of :math:`ax^{2}+bx+c=0` using the well-known abc formula: .. math:: D = b^2 - 4ac .. math:: x_1 = \frac{{ - b - \sqrt {D} }}{{2a}} .. math:: x_2 = \frac{{ - b + \sqrt {D} }}{{2a}} Here is a sample run with the numbers rounded to 2 decimals: :: enter a: 2 enter b: -4 enter c: -3 D = 40 solution: x1 = -0.58 x2 = 2.58 Remark: The program crashes when :math:`D < 0`. Don't worry about that for now, you will learn how to handle situations like that later. **1.5c.** (Challenge, you may skip if you don't know the math) Write a program that calculates the well-known (Gaussian) normal distribution: .. math:: Z = \big(\frac{{x - m}}{s}\big)^2 .. math:: P(x) = \frac{1}{s \sqrt{2\pi}} e^{-Z} where :math:`\pi \approx 3.141592653589793`. Round-off :math:`P(x)` to 6 decimals. Here is a sample run: :: enter x: 2.5 enter m: 1.2 enter s: 0.5 Z = 6.76 P(2.5) = 0.000925 Hint: use **math.exp()**. Strings Manipulations --------------------- **Exercise 1.6 Layout of strings in 'columns'** When displaying multiple output lines to a console it is useful to align the data in columns. As explained in the reader, ljust or rjust can be used for that. **1.6a** list of first and second names Write a program that asks for the first name and second name of three people and then displays them in proper columns. Here is a sample run: :: enter first name 1: Jan enter last name 1: Jansen enter first name 2: John enter last name 2: Johnson enter first name 3: Johan enter last name 3: Johanson First Last Jan Jansen John Johnson Johan Johanson For simplicity, you may assume that all first names are at most 11 characters long (see also 1.6c). **1.6b** aligned rhyme words. In the dutch tradition of Sinterklaas (https://en.wikipedia.org/wiki/Sinterklaas) people give each other gifts with poems. Some people will use lists of rhyme words to help with their creativity. Write a program that first asks for four rhyme words and then displays them with aligned word endings (which makes the list more readable). Here is a sample run: :: rhyme word 1: koek rhyme word 2: broek rhyme word 3: bezoek rhyme word 4: zoek rhyme words: koek broek bezoek zoek **1.6c** (Challenge) Try to solve exercise 1.6a for first names of **any** length. **Exercise 1.7 extracting numbers from strings** Use *slicing* to extract the numbers from the following strings: **1.7a.** string_a = '3500 ballons where popped in the world-record attempt.' **1.7b.** string_b = 'X-DSPAM-Confidence: 0.8475' **1.7c.** string_c = 'The economy has grown by 3.57% over the past year.' Test if your code is correct in a little program. **1.7d.** challenge: can you also do it if you don't know beforehand how many characters the numbers will have? Hint: you can use **.find( )** and **.rfind( )** to determine the start/end of the numbers. **Exercise 1.8 string manipulations** Try to predict the answers in this exercise. Look in the reader to get help. Run the code to check your answer. If you get it wrong, think about why. This is a fast way to learn Python. **1.8a.** Predict the value of *length* after execution of this code: .. code-block:: python start = "the apple doesn't fall" end = "far from the tree" result = start + end length = len(result) **1.8b.** Predict the value of *index* after execution of this code: .. code-block:: python sentence = "Python is a great programming language." index = sentence.find("g") **1.8c.** Predict the value of *slice* after execution of this code: .. code-block:: python sentence = "Oh wow, I love studying!" slice = sentence[6: 10] **1.8d.** Predict the value of *result* after execution of this code: .. code-block:: python sentence = "This exercise is a little bit more advanced." result = len(sentence) * sentence.find("little") **Exercise 1.9 The Echoing Well (dutch: Echoput)** Write a program that asks the user how many echos the well returns and the word to be echoed. Hint: you can do this with simple string manipulation. No **for** or **while** needed. Here is a sample run :: How many echos do you want? 4 What is the word? Geronimo Geronimo ... Geronimo ... Geronimo ... Geronimo ... Miscellaneous exercises ----------------------- **Exercise 1.10 Draw four circles** Write a program that prompts the user to enter a radius and draws four circles in the center of the screen that touch each other like shown below in a sample run with radius 50: .. figure:: ./images/04_screen_shot_ex_1.9.png :width: 242px :align: center :height: 261px :alt: alternate text :figclass: align-center **Exercise 1.11 Draw a square with varying size and color** Write a program that prompts the user to enter a width and a color and draws a square with the correct width and color. Here is a sample run with color 'green' and width 100: .. figure:: ./images/05_screen_shot_ex_1.10.png :width: 191px :align: center :height: 192px :alt: alternate text :figclass: align-center © Copyright 2021, dr. P. Lambooij last updated: |today|