Thoughts and notes for Thu May 14, 2009. Tomorrow we have a homework exam. You need to work on the eight posted problems, prepare them for tomorrow. The exam is closed-book and you will get two problems randomly selected from the eight posted. Let's discuss and solve these problems now. As I said you can already solve the first six problems. Let's start with them. What do we know? Let's be very concise when we review that: a) we know how to start IDLE b) we know how to save and run a Python program in IDLE c) we know numeric expressions d) we understand the basic facts about variables and assignment statements, for example: a = 1 b = a + 1 The first sets a to 1, the second one sets b to 2. e) we know functions int(...), and raw_input(...) both have one argument (input, ingredient) and both produce a result. int("23") produces 23, thus converting the string to an integer, and raw_input receives a string argument with which it prompts the user, after which it waits for the user to enter characters. When the user hits Enter the entire line typed by the user is collected and returned by raw_input at the point of its invocation in the program. There are other functions that are useful, like abs(...), max(...[, ...]), min(...[, ...]) and so on. abs drops the sign of its numerical argument, while max and min can receive any number of numeric arguments, and will select the max (or the min) and return that in the program. Here are some examples: a) 1 + 1 evaluates to 2 (easy, but we need to warm up) b) abs(-2) evaluates to 2 c) abs(3 - 5) + 1 evaluates to 3 d) abs(4) is 4 e) max(3, 4, 5) returns 5 (or evaluates to 5) f) abs(3 - 5)/ 2 + (3 + 5)/2 evaluates to 5 (which, by the way, is max(3, 5)). g) "2" + "3" evaluates to "23" (which is a string not an integer) h) int("2") evaluates to 2 (an integer) i) int("2") + int("3") evaluates to 2 + 3 which evaluates to 5 j) "2" + 3 is not allowed k) raw_input("Please enter a number: ") evaluates to the string entered by the user (which may not be a number) Let's work a separate exercise for this last situation. Assume that the user, when prompted, will type the following characters on the keyboard: 2, 3 and enter. Then the following expression: "abc" + raw_input("Type here: ") will evaluate to "abc23" (a string). You can store what raw_input returns. Use an assignment statement to assign the value to a variable. Variables are names of locations where you can store values that you want (or need) to use later. Names of variables are alphanumeric (by and large) and can't start with digits. An assignment statement has an = that separates an expression on the right hand side and a variable on the left. The assignment statement evaluates the expression and stores its resulting value into the specified variable that appears on the left of the = sign. You see then that the = sign is more like an arrow indicating that the value that we calculate on the right hand side needs to be placed into the location named by the variable that appears on the left. The variable then can be used in subsequent expressions, so an assignment statement is ideal for storing an intermediary result, or input (that is collected from the user and needs to be referred later). The book uses raw_input as a break point at the end of a program run by double-clicking it on the desktop. Because raw_input waits for user input it can be used (as the book does) as a show stopper. It keeps the window open. The user of course hits Enter when done and raw_input collects the nothing that the user has essentially entered and the program ends, taking away the window with it. So here's the basic use of raw_input: a = raw_input("Please enter a number: ") print "You have entered", a This simple, short program has two statements. The first statement places in variable a the input that raw_input collects from the user: the user is prompted with the string "Please enter a number: " and then the user types something and hits Enter. Whatever the user has entered is collected, as a string, and deposited in the variable a. print later prints it, along with additional info that tries to explicate the output to the user. Note that print can take any number of arguments, as long as you separate them with commas. So how do you write a program that asks the user for her name and age and then prints a message that tells the user how old she will be next year? We need a plan, a basic plan. Given what I said above (that's all we know, for the time being) the situation is like in the threads problem: that's what you know about them, no go find a sequence of steps that will ensure you can measure EXACTLY 45 minutes. You see the similarity? Here's the plan for our problem: 1. ask the user for her name and collect it, store it in variable name 2. ask the user for her age and collect it, then store it in a variable age 3. print the user's name and the age next year This is a good, basic plan. Let's execute it: name = raw_input("Name please: ") age = raw_input("And your age: ") print "Well,", name, "next year you will be", (age + 1), "years old." This is ALMOST perfect. Most of the times your programs will be *almost* perfect. Get used to it and to place the finishing touches with patience and determination on your programs. In this case age + 1 won't work since age is a string (a bit hard to see at first, right? But still, relatively clear, after a moment of thought, no?) So we make this change: name = raw_input("Name please: ") age = raw_input("And your age: ") print "Well,", name, "next year you will be", (int(age) + 1), "years old." Final notes on this, before we get started with the problems: a) if the user enters a non-number the program assumes no responsibility and just crashes. That's fine at this stage. b) you can never be sure the program is correct until you type it in and try it out. But you should always make a careful, honest effort to write the best code you can on your exams. Yes, you can make typos, or have small errors, and those won't affect your grade on the exam but on the whole you can (and so, you should always try) to think about the programs you write, because this type of exercise will help you think straight, and you will be able to write better programs faster with time, if you prepare and practice this type of exercise. A plan before you start typing in the computer is like cheking the map before getting into the car to drive. Grades on exams: you will get 100 - a where a is the minimal amount of effort I have to put into correcting your program. It's like pricing an unfinished house: people can't live in it yet, but you can sell it to a developer. The developer will give you a price equal to the difference between what they expect to sell the house when finished and the amount of money they need to put into it to bring it to that level. The grade on the exam is calculated in the same way. So if your program is not finished I basically count the characters I need to type to make it work. The grade is one hundred (maximum score) minus a number of points proportional to how much one needs to type to make your program work perfectly. The homework exams can be re-taken any number of times but you need to make an appointment with me in my office, and they will be closed-book written exams and since problems are selected randomly you might not get the same problems on a re-take. Don't wait too long to re-take them, if it gets really crowded in the last few days I may not be able to offer any re-takes. You can also take such an exam earlier or later if you're not there on a Friday. Just let me know. You can also test out easily this way, since the grade is a collection of 6 exams. And now let's work out the problems for the Homework One exam: Problem One. Plan: a) ask the user for the first number, convert it to an integer and store it in a variable (say n1) b) ask the user for the second number, convert it to an integer and store it in a variable (say n2) c) print n1 + n2, n1 - n2, n1 * n2, (n1 + n2) / 2, abs(n1 - n2), max(n1, n2) and min(n1, n2) Note: double(...) is another function that converts a string to a number. This is useful, say, when the numbers entered add up to an odd number, like 3 and 4: their average needs to be reported as 3.5 so it's better to use double(...) here instead of int(...) Problem Two. If you go to Google and type 1 meter in miles you get: 1 meter = 0.000621371192 miles Likewise we have: 1 meter = 3.2808399 feet and 1 meter = 39.3700787 inches Plan: read the input (remember it's a string) and convert it to a double. Then multiply it by the constants above. Problem Three. Circumference of a circle is 2 times pi (3.141592) times the radius. Area of a circle is: pi times the square of the radius. There's a pow(..., ...) function in Python that can be used to calculate both the square and the square root. Area of a sphere: 4 times pi times the square of the radius Volume of a sphere: 4 times pi times the cube of the radius divided by 3 Plan: a) ask the user for the radius, convert it and store it in a variable b) print the formulas mentioned above Problem Four. The area of a rectangle is the product between its sides. Pythagora's Theorem is that the diagonal in a rectangle is the square root of the sum of its squared sides. Plan: a) ask for the height, collect it, convert it and store it in a variable named height b) ask for the width, collect it, convert it and store it in a variable named width c) print height times width and sqyare root of (height * height + width * width); pow(..., 0.5) is the square root. Problem Five. The key here is to remember how integer division works. So, if you have 135 cents you can determine the number of whole quarters in that as 135 / 25 which is 5. The part that can't be expressed in whole quarters is 135 % 25 which is 10. So we try with dimes and nickels, in order. Plan: The plan is already given, plus the hint. Problem Six. Here you need to determine the formula. Plan: ask for and collect the amount of fuel, the car fuel efficiency, and the fuel price per gallon. Then apply your formula to print the answers. Remember: if you don't know how to do it you won't be able to teach another to do it. So, start by working out an example, and examining yourself as you solve the problem. Let's say 5.2 gallons of fuel in your tank, the fuel efficiency of your car is 22.6 miles per gallon, and the price is $2.12/gallon. How far can you get with those 5.2 gallons and what's the price you pay for fuel every 100 miles? Problem Seven. Here you need to know how to extract a substring. So we'll explain that in class. Here we just give an example: a = "nectarine" b = a[4:6] print b What does the code above mean? We'll explain in class that characters in a string have indices and that a[4:6] is a substring that contains the fifth and sixth characters (but not seventh) in the string a. The rest is still something you need to apply your creativity on. Plan: we'll discuss this in lab. Problem Eight. It's easy to create the string. It's also easy to calculate where the n-th month name starts if all months are of the same length. So once we have that we can extract the n-th month name easily, and print it. But you have to put this together all by yourselves. Code will also be posted here as soon as we work these things out in class/lab. Plan: to be discussed in lab. --