Difference between revisions of "CSC111 Lab 3 2015"
(→Submission) |
|||
(47 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 21:22, 9 February 2015 (EST) | --[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 21:22, 9 February 2015 (EST) | ||
---- | ---- | ||
+ | <br /> | ||
+ | <bluebox> | ||
+ | The lab today deals with several concepts covered in Chapter 3 of Zelle. You have two programs to submit to Moodle, one for Challenge 1, and another one for Challenge 4. The deadline for the submission is Friday 2/13 at 11:00 a.m. | ||
+ | </bluebox> | ||
+ | <br /> | ||
+ | __TOC__ | ||
+ | <br /> | ||
+ | <br /> | ||
+ | =Understanding how '''Floats''' take over Expressions= | ||
+ | <br /> | ||
+ | In this section I am asking you to play and get an understanding of important functions, and also how floating point numbers (numbers with a decimal point) ''take over'' expressions, when they are present in them. | ||
+ | |||
+ | Open the Python shell and type the expressions below. Try to predict the output of the interpreter when you are about to press the ENTER key. | ||
+ | |||
+ | >>> a = 3 | ||
+ | >>> x = 1.5 | ||
+ | >>> type( a ) | ||
+ | |||
+ | >>> type( x ) | ||
+ | |||
+ | >>> type( a * x ) | ||
+ | |||
+ | >>> type( a * 100 ) | ||
+ | |||
+ | >>> type( 1 ) | ||
+ | |||
+ | >>> type( 1.0 ) | ||
+ | |||
+ | >>> type( "1" ) | ||
+ | |||
+ | >>> a / 3 | ||
+ | |||
+ | >>> a // 3 | ||
+ | |||
+ | >>> type( a/3 ) | ||
+ | |||
+ | >>> type( 5/4 ) | ||
+ | |||
+ | >>> type( 5//4 ) | ||
+ | |||
+ | >>> type( int( 1.5 ) ) | ||
+ | |||
+ | >>> int( 1.5 ) | ||
+ | |||
+ | >>> round( 1.6 ) | ||
+ | |||
+ | >>> round( 1.4 ) | ||
+ | |||
+ | >>> round( -1.8 ) | ||
+ | |||
+ | >>> type( round( 1.4 ) ) | ||
+ | |||
+ | >>> round( -1.8 ) | ||
+ | |||
+ | >>> abs( -4 ) | ||
+ | |||
+ | >>> abs( 10 ) | ||
+ | |||
+ | >>> type( abs( -19.3 ) ) | ||
+ | |||
+ | >>> type( abs( -4 ) ) | ||
+ | |||
+ | |||
+ | * Note how once something is a float, if forces whatever it gets combined with to yield a result that is float, except for the '''int()''' function, of course. | ||
+ | <br /> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | ==Challenge #0: (we always start at 0 in Computer Science!)== | ||
+ | |} | ||
+ | [[Image:QuestionMark1.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Write a small program (either in the Python Shell, or in the Edit window), that asks the user to enter a number between 0 and 100, and that prints out 0 if the number is between 0 and 25 (25 not included), 1 if the number is between 25 and 50 (50 not included), 2 if the number is between 50 and 75 (75 not inclulded), and 3 if the number is between 75 and 100 (100 not included). | ||
+ | |||
+ | * Here is an example of the type of exchange I had with | ||
+ | |||
+ | >>> | ||
+ | >>> x = eval( input( "Enter a number: " ) ) | ||
+ | Enter a number: 75.7 | ||
+ | >>> result = <font color="magenta">... ''write an expression here that takes x and computes the expected result''</font> | ||
+ | >>> result | ||
+ | 3 | ||
+ | >>> x = 1 | ||
+ | >>> result = <font color="magenta">... ''use the same expression you wrote above...''</font> | ||
+ | >>> result | ||
+ | 0 | ||
+ | >>> x = 24.99999 | ||
+ | >>> result = <font color="magenta">... ''use the same expression you wrote above...''</font> | ||
+ | >>> result | ||
+ | 0 | ||
+ | >>> x = 25.00000001 | ||
+ | >>> result = <font color="magenta">... ''use the same expression you wrote above...''</font> | ||
+ | >>> result | ||
+ | 1 | ||
+ | >>> | ||
+ | |||
+ | <br /> | ||
+ | |||
=Teller Machine Program= | =Teller Machine Program= | ||
[[Image:ATM.jpg|right|200px]] | [[Image:ATM.jpg|right|200px]] | ||
Line 129: | Line 228: | ||
[[Image:USCoins.jpg|right|200px]] | [[Image:USCoins.jpg|right|200px]] | ||
− | Amount to withdraw = 84 | + | Amount to withdraw = 84 cent(s) |
Please lift keyboard and find: | Please lift keyboard and find: | ||
Line 138: | Line 237: | ||
<br /> | <br /> | ||
+ | <br /> | ||
+ | ==<font color="magenta">Moodle Submission</font>== | ||
+ | <br /> | ||
+ | * Modify your program for Challenge 1, and rename it '''Lab3_1.py'''. It should now prompt the user for a number of pennies, and then, once it has received that number, it will print the number of coins that make up that quantity. We assume that the user may not be fully well behaved and might enter negative numbers, or numbers with a decimal point. For example, if the user enters -84, your program will treat this number as +84. If the user enters 84.5, your program will treat it as 84. | ||
+ | * Submit your program to the LAB 3 PB 1 section on Moodle. Note that the Moodle test program will strip all words from your output and will look only at the numbers, so you do not need to worry about the exact phrasing of your output. | ||
+ | <br /> | ||
+ | |||
+ | =Formatted Output= | ||
+ | <br /> | ||
+ | ==Strings == | ||
+ | <br /> | ||
+ | <tanbox> | ||
+ | In this section you will work on formatting strings, ints, and floats using the {...} formatting command. | ||
+ | </tanbox> | ||
+ | <br /> | ||
+ | * Try this statement out: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | name = "Snow White" | ||
+ | print( "Hello {0:1}! How are you?".format( name ) ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Then modify the {0:1} part and try these different combinations: {0:5}, {0:10}, {0:15}, {0:20}. For each one, make sure you understand why the output changes (or not). | ||
+ | * Then try these different formats: {0:>1}, {0:>5}, {0:>10}, {0:>15}, {0:>20}. Notice the right-justification of the string Snow White in this second set of outputs. | ||
+ | <br /> | ||
+ | * Now try this piece of code: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | print( ) | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "Hello {0:10}!".format( friend ) ) | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | == Printing 2 strings at once== | ||
+ | <br /> | ||
+ | * Change the print() statement so that you now print two different strings, each with its own {...} format: | ||
+ | ::<source lang="python"> | ||
+ | print( ) | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "{0:1} wants to take {1:1} to the Valentine's ball." . format( friend, "Snow White" ) ) | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | * Now switch the 0 and the 1 in the two {...} expressions, as illustrated in the line below: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | |||
+ | print( "{1:1} wants to take {0:1} to the Valentine's ball." . format( friend, "Snow White" ) ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Notice how the first number in the {...} expressions is used to figure out which string to pick in the <tt>format(...)</tt> block. | ||
+ | <br /> | ||
+ | ==Printing a String and an Int == | ||
+ | <br /> | ||
+ | * Try this formatting command: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | name = "Valentine's Day" | ||
+ | day = 15 | ||
+ | print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) | ||
+ | name = "My birthday" | ||
+ | day = 6 | ||
+ | print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Here's another statement to try: | ||
+ | <br /> | ||
+ | <source lang="Python"> | ||
+ | name = "Snow White" | ||
+ | length = len( name ) | ||
+ | print( "the string {0:1} contains {1:1} characters" . format( name, length ) ) ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | |||
+ | ==Challenge #2:== | ||
+ | |} | ||
+ | [[Image:QuestionMark3.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Modify the for-loop you used before so that your program now outputs '''friend''' and '''len( friend )''', as shown below. | ||
+ | <br/> | ||
+ | ::<source lang="text"> | ||
+ | Bashful 7 | ||
+ | Doc 3 | ||
+ | Dopey 5 | ||
+ | Happy 5 | ||
+ | Sleepy 6 | ||
+ | Sneezy 6 | ||
+ | Grumpy 6 | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Once you get this output, format it into a nice looking table using the {...} formatting command. | ||
+ | <br /> | ||
+ | ::<source lang="text"> | ||
+ | +------------+-----+ | ||
+ | | Bashful | 7 | | ||
+ | | Doc | 3 | | ||
+ | | Dopey | 5 | | ||
+ | | Happy | 5 | | ||
+ | | Sleepy | 6 | | ||
+ | | Sneezy | 6 | | ||
+ | | Grumpy | 6 | | ||
+ | +------------+-----+ | ||
+ | </source> | ||
+ | <br /> | ||
+ | ==Printing Floats== | ||
+ | <br /> | ||
+ | * Copy/paste this block of code below in your program. Then run it. Verify that the output makes sense. | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | print( "Printing PI" ) | ||
+ | pi = 3.14159 | ||
+ | print( "-------------------------" ) | ||
+ | print( "Pi={0:1.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:2.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:3.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:4.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:5.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:6.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:7.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:8.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.0f}!".format( pi ) ) | ||
+ | print( "-------------------------" ) | ||
+ | print( "Pi={0:9.1f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.2f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.3f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.4f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.5f}!".format( pi ) ) | ||
+ | print( "-------------------------" ) | ||
+ | print( "Pi={0:<9.1f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.2f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.3f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.4f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.5f}!".format( pi ) ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | ==Temperature Conversion== | ||
+ | <br /> | ||
+ | * Remember that we saw that a temperature in Celsius is computed as the temperature in Fahrenheit - 32, the difference multiplied by 5/9? | ||
+ | * Write a for-loop that displays two columns of numbers, the column on the left showing degrees Fahrenheit, and the column on the right showing Celsius. | ||
+ | <br /> | ||
+ | ::<source lang="text"> | ||
+ | 20 -6.666666666666667 | ||
+ | 22 -5.555555555555555 | ||
+ | 24 -4.444444444444445 | ||
+ | 26 -3.3333333333333335 | ||
+ | 28 -2.2222222222222223 | ||
+ | 30 -1.1111111111111112 | ||
+ | 32 0.0 | ||
+ | 34 1.1111111111111112 | ||
+ | 36 2.2222222222222223 | ||
+ | 38 3.3333333333333335 | ||
+ | 40 4.444444444444445 | ||
+ | </source> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | <br /> | ||
+ | ==Challenge #3:== | ||
+ | |} | ||
+ | [[Image:QuestionMark4.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Use the {...} formatting command to make your output look nice: | ||
+ | <br /> | ||
+ | ::<source lang="text"> | ||
+ | 20.00F = -6.67C | ||
+ | 22.00F = -5.56C | ||
+ | 24.00F = -4.44C | ||
+ | 26.00F = -3.33C | ||
+ | 28.00F = -2.22C | ||
+ | 30.00F = -1.11C | ||
+ | 32.00F = 0.00C | ||
+ | 34.00F = 1.11C | ||
+ | 36.00F = 2.22C | ||
+ | 38.00F = 3.33C | ||
+ | 40.00F = 4.44C | ||
+ | </source> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | |||
+ | ==Challenge #4:== | ||
+ | |} | ||
+ | [[Image:QuestionMark5.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Add some bars and a legend, too! | ||
+ | <br /> | ||
+ | ::<source lang="text"> | ||
+ | +-------------+-------------+ | ||
+ | | Fahrenheit | Celsius | | ||
+ | +-------------+-------------+ | ||
+ | | 20.00F | -6.67C | | ||
+ | | 22.00F | -5.56C | | ||
+ | | 24.00F | -4.44C | | ||
+ | | 26.00F | -3.33C | | ||
+ | | 28.00F | -2.22C | | ||
+ | | 30.00F | -1.11C | | ||
+ | | 32.00F | 0.00C | | ||
+ | | 34.00F | 1.11C | | ||
+ | | 36.00F | 2.22C | | ||
+ | | 38.00F | 3.33C | | ||
+ | | 40.00F | 4.44C | | ||
+ | +-------------+-------------+ | ||
+ | </source> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | ==<font color="magenta">Moodle Submission</font>== | ||
+ | <br /> | ||
+ | * Rename your program '''Lab3_4.py''' and submit it to Moodle, to the LAB 3 PB 4 section. Note that your output must match '''exactly''' the one shown above, with the right number of spaces, the same number of decimals, and the same number of lines. Your program '''must''' use a loop to generate the output, and must use formatting {...} commands. | ||
+ | <br /> | ||
+ | |||
+ | =Accumulating Quantities= | ||
+ | <br /> | ||
+ | <tanbox>The idea for this section is that some quantities can be computed not all at once, but instead, one piece at a time. Computers are extremely fast and ready for this type of ''accumulation'' of data. In this section we look at several ways to do this with various types of data. We will see later on in the semester, that some of the operations we are performing here can be done more easily some other way. That's ok. Programming is also the art of solving problems, and not necessarily to find the most elegant or fastest solutions (although it is good to be aware of them!) | ||
+ | </tanbox> | ||
+ | <br /> | ||
+ | ==Sum of a list of numbers== | ||
+ | <br /> | ||
+ | * Add this piece of code to your program (or create a new one): | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | sumAll = 0 | ||
+ | for n in [100, 10, -30, -2, 20, 5 ]: | ||
+ | sumAll = sumAll + n | ||
+ | |||
+ | print( "sum = ", sumAll ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Run the code. Add the numbers by hand to make sure your program outputs the correct information. | ||
+ | * Add this print statement inside the for-loop, right after the "sumAll = ..." statement: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | print( "n = {0:3} sum = {1:3}" . format( n, sumAll ) ) | ||
+ | </source> | ||
+ | * Run your code. Observe how the loop allows the variable '''sumAll''' to grow with the addition of every new number in the list. | ||
+ | <br /> | ||
+ | <tanbox> | ||
+ | Note that the rule for accumulating quantities with a loop is always the same: | ||
+ | # first you initialize a variable to represent some null quantity | ||
+ | # then you loop, and in the loop you increase the variable with a new quantity given by the loop. | ||
+ | # at the end of the loop, your variable will contain an accumulation of all the values your loop touched, or created. | ||
+ | </tanbox> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | |||
+ | ==Challenge #5:== | ||
+ | |} | ||
+ | [[Image:QuestionMark6.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Replace the list of numbers '''[100, 10, -30, -2, 20, 5 ]''' by the '''range()''' function and make your program compute the sum of all the even numbers between 0 and 100, included. | ||
+ | * Verify that your program outputs 2550 as the result! You do not need to make your program output all the intermediate values of '''sumAll'''. | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | |||
+ | ==Count the Items in a List== | ||
+ | <br /> | ||
+ | * Try this piece of code now: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | count = 0 | ||
+ | for n in [ 100, 10, -30, -2, 20, 5 ]: | ||
+ | count = count + 1 | ||
+ | |||
+ | print( "there are", count, "items in the list" ) | ||
+ | </source> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | * See how this code is different from the loop in the previous section. Here we add 1 to the counter every time we go through the loop. In other words, we add 1 for every item we find in the list. So, in effect, we are ''counting'' the items in the list. | ||
+ | * Run your code and see what it outputs. | ||
+ | * Add print statement '''inside''' the loop, below the '''count = count + 1''' line, and make the print statement print '''n''' and '''count'''. Don't worry about the formatting. | ||
+ | * Run your code. Do you see the program ''counting'' the items it finds in the list of numbers? | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | |||
+ | ==Challenge #6:== | ||
+ | |} | ||
+ | [[Image:QuestionMark8.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Write a program that uses a for-loop that scans a list of numbers: [1, 2, 2, 1, 2, 3, 3, 2, 1, 0] | ||
+ | * Make your program compute the '''average''' of the numbers in the list. The average is the sum of all numbers divided by the number of items. | ||
+ | * Your program should output the average at the end, as a floating-point number. | ||
+ | * Run your program. Verify that you get the correct result (sum = 17 average = 1.70). | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | |||
+ | ==Accumulating Strings== | ||
+ | <br /> | ||
+ | * Here's a new program to try: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | line = "" | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy" ]: | ||
+ | line = line + friend + ", " | ||
+ | |||
+ | print( "line =", line ) | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | |||
+ | <br /> | ||
+ | {| style="width:100%; background:silver" | ||
+ | |- | ||
+ | | | ||
+ | |||
+ | ==Challenge #7: (Challenging!)== | ||
+ | |} | ||
+ | [[Image:QuestionMark9.jpg|right|120px]] | ||
+ | <br /> | ||
+ | * Write a program that contains a single loop, of the form <font color="magenta"><tt>for n in ( 2, 3, 5, 3, 2 )</tt></font>, and that accumulates a string, which, when it is fully computed, is equal to "**---*****---**". | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <showafterdate after="20150213 11:00" before="20150601 00:00"> | ||
+ | =Solution Program= | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # lab3Solutions.py | ||
+ | # D. Thiebaut | ||
+ | # Solution programs for CSC111 Lab #3 | ||
+ | # | ||
+ | # All the solutions are group into one large main program. | ||
+ | |||
+ | def main(): | ||
+ | |||
+ | # Challenge 0 | ||
+ | for x in [ 0, 1, 24.99, 25, 25.001, 30, 51, 79, 99]: | ||
+ | result = int( x/25 ) | ||
+ | print( "x = ", x, " result = ", result ) | ||
+ | |||
+ | # Teller Machine | ||
+ | # Takes some amount of $ and breaks it down in 20, 10, 5, and 1 | ||
+ | # dollar bills. | ||
+ | |||
+ | # set the amount | ||
+ | amount = 97 | ||
+ | |||
+ | # break it down | ||
+ | no20s = amount // 20 | ||
+ | leftOver = amount % 20 | ||
+ | no10s = leftOver // 10 | ||
+ | leftOver = leftOver % 10 | ||
+ | no5s = leftOver // 5 | ||
+ | leftOver = leftOver % 5 | ||
+ | no1s = leftOver | ||
+ | |||
+ | # printout the number of bills | ||
+ | print() | ||
+ | print( "You want to withdraw ${0:1}".format( amount) ) | ||
+ | print( "Lift the keyboard and find:" ) | ||
+ | print( "{0:4} $20-bill(s)". format( no20s ) ) | ||
+ | print( "{0:4} $10-bill(s)". format( no10s ) ) | ||
+ | print( "{0:4} $5-bill(s)". format( no5s ) ) | ||
+ | print( "{0:4} $1-bill(s)". format( no1s ) ) | ||
+ | |||
+ | |||
+ | # ========================================================== | ||
+ | # Teller Machine with a different set of denominations | ||
+ | # set the amount | ||
+ | amount = 197 | ||
+ | |||
+ | # break it down | ||
+ | no100s = amount // 100 | ||
+ | leftOver = amount % 100 | ||
+ | no50s = leftOver // 50 | ||
+ | leftOver = leftOver % 50 | ||
+ | no10s = leftOver // 10 | ||
+ | leftOver = leftOver % 10 | ||
+ | no1s = leftOver | ||
+ | |||
+ | # printout the number of bills | ||
+ | print() | ||
+ | print( "You want to withdraw ${0:1}".format( amount) ) | ||
+ | print( "Lift the keyboard and find:" ) | ||
+ | print( "{0:4} $100-bill(s)". format( no20s ) ) | ||
+ | print( "{0:4} $50-bill(s)". format( no10s ) ) | ||
+ | print( "{0:4} $10-bill(s)". format( no5s ) ) | ||
+ | print( "{0:4} $1-bill(s)". format( no1s ) ) | ||
+ | |||
+ | # simple output | ||
+ | print() | ||
+ | name = "Snow White" | ||
+ | print( "Hello {0:1}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:5}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:10}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:15}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:20}! How are you?".format( name ) ) | ||
+ | |||
+ | print( "Hello {0:>1}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:>5}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:>10}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:>15}! How are you?".format( name ) ) | ||
+ | print( "Hello {0:>20}! How are you?".format( name ) ) | ||
+ | |||
+ | # Formatted output, Version 1 | ||
+ | print( ) | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", | ||
+ | "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "Hello {0:10}!".format( friend ) ) | ||
+ | |||
+ | # Swapping first and second strings | ||
+ | print( ) | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "{1:1} wants to take {0:1} to the Valentine's ball." | ||
+ | . format( friend, "Snow White" ) ) | ||
+ | |||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "{0:1} wants to take {1:1} to the Valentine's ball." | ||
+ | . format( friend, "Snow White" ) ) | ||
+ | |||
+ | # Unformatted dwarf names and length of names | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", | ||
+ | "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( friend, len(friend) ) | ||
+ | |||
+ | # Formatted output, Version 2 | ||
+ | bar = "+-" + 10*'-' + "-+-" + 3*'-' + "-+" | ||
+ | print( bar ) | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", | ||
+ | "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | print( "| {0:10} | {1:3} |".format( friend, len(friend) ) ) | ||
+ | print( bar ) | ||
+ | |||
+ | # print string and int | ||
+ | name = "Valentine's Day" | ||
+ | day = 15 | ||
+ | print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) | ||
+ | name = "My birthday" | ||
+ | day = 6 | ||
+ | print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) | ||
+ | |||
+ | # printing floats | ||
+ | print() | ||
+ | print( "Printing PI" ) | ||
+ | pi = 3.14159 | ||
+ | print( "Pi={0:1.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:2.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:3.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:4.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:5.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:6.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:7.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:8.0f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.0f}!".format( pi ) ) | ||
+ | print( "-------------------------" ) | ||
+ | print( "Pi={0:9.1f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.2f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.3f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.4f}!".format( pi ) ) | ||
+ | print( "Pi={0:9.5f}!".format( pi ) ) | ||
+ | print( "-------------------------" ) | ||
+ | print( "Pi={0:<9.1f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.2f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.3f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.4f}!".format( pi ) ) | ||
+ | print( "Pi={0:<9.5f}!".format( pi ) ) | ||
+ | |||
+ | |||
+ | # Print table of temperatures | ||
+ | print() | ||
+ | for Fahr in range( 20, 41, 2 ): | ||
+ | print( Fahr, (Fahr-32.0)*5.0/9 ) | ||
+ | |||
+ | print() | ||
+ | for Fahr in range( 20, 41, 2 ): | ||
+ | print( "{0:10.2f}F = {1:10.2f}C".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) | ||
+ | |||
+ | |||
+ | # Print table of temperatures with bars around | ||
+ | bar = "+-" + 10*'-' + "--+-" + 10*'-' + "--+" | ||
+ | print( bar ) | ||
+ | print( "| {0:>10} | {1:>10} |".format( "Fahrenheit", "Celsius" ) ) | ||
+ | print( bar ) | ||
+ | for Fahr in range( 20, 41, 2 ): | ||
+ | print( "| {0:10.2f}F | {1:10.2f}C |".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) | ||
+ | print( bar ) | ||
+ | |||
+ | def main2(): | ||
+ | # compute the sum a list of numbers | ||
+ | # (note that there's a much simpler way to do this in Python, which | ||
+ | # we'll see later during the semester.) | ||
+ | print() | ||
+ | sumAll = 0 | ||
+ | for n in [100, 10, -30, -2, 20, 5 ]: | ||
+ | sumAll = sumAll + n | ||
+ | print( "n = {0:3} sum = {1:3}" . format( n, sumAll ) ) | ||
+ | print( "sum = ", sumAll ) | ||
+ | |||
+ | # add-up the even numbers between 0 and 100. | ||
+ | print() | ||
+ | sumAll = 0 | ||
+ | for n in range( 0, 101, 2 ): | ||
+ | sumAll = sumAll + n | ||
+ | print( "the sum of all the even numbers from 0 to 100, included, is", | ||
+ | sumAll ) | ||
+ | |||
+ | # count how many items are in the list | ||
+ | print() | ||
+ | count = 0 | ||
+ | for n in [ 100, 10, -30, -2, 20, 5 ]: | ||
+ | count = count + 1 | ||
+ | print( "n = {0:3} count = {1:3}" . format( n, count ) ) | ||
+ | print( "there are", count, "items in the list" ) | ||
+ | |||
+ | |||
+ | # compute the sum and average of a list of numbers | ||
+ | print() | ||
+ | sumAll = 0 | ||
+ | count = 0 | ||
+ | for n in [1, 2, 2, 1, 2, 3, 3, 2, 1, 0]: | ||
+ | sumAll = sumAll + n | ||
+ | count = count + 1 | ||
+ | |||
+ | print( "sum = {0:1} average = {1:1.2f}" . format( sumAll, sumAll*1.0/count ) ) | ||
+ | |||
+ | # compute the factorial of a number | ||
+ | # factorial( 10 ) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 | ||
+ | print() | ||
+ | n = 20 | ||
+ | fact = 1 | ||
+ | for i in range( 1, n+1 ): | ||
+ | print( "computing fact * i = {0:1} * {1:1} = {2:1}" | ||
+ | .format( fact, i, fact*i ) ) | ||
+ | fact = fact * i | ||
+ | print( "factorial({0:1}) = {1:1}".format( n, fact ) ) | ||
+ | |||
+ | # create a string with all the names of the 7 dwarves | ||
+ | print() | ||
+ | line = "" | ||
+ | for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: | ||
+ | line = line + friend + ", " | ||
+ | |||
+ | print( "line =", line ) | ||
+ | |||
+ | # Challenge | ||
+ | print() | ||
+ | line = "" | ||
+ | char1 = "*" | ||
+ | char2 = "-" | ||
+ | for n in ( 2, 3, 5, 3, 2 ): | ||
+ | line = line + n*char1 | ||
+ | char1, char2 = char2, char1 | ||
+ | |||
+ | print( "line = ", line ) | ||
+ | main2() | ||
+ | |||
+ | </source> | ||
+ | </showafterdate> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <!-- ================================================================ --> | ||
+ | <onlydft> | ||
+ | =VPL Module for Challenge 1= | ||
+ | ==vpl_run.sh= | ||
+ | <source lang="bash"> | ||
+ | #! /bin/bash | ||
+ | |||
+ | cat > vpl_execution <<EOF | ||
+ | #! /bin/bash | ||
+ | |||
+ | #python=/usr/local/bin/python3.4 | ||
+ | python=/usr/bin/python3.3 | ||
+ | |||
+ | prog=Lab3_1.py | ||
+ | \$python \$prog | ||
+ | |||
+ | EOF | ||
+ | |||
+ | chmod +x vpl_execution | ||
+ | </source> | ||
+ | ==vpl_evaluate.sh== | ||
+ | <source lang="bash"> | ||
+ | #! /bin/bash | ||
+ | # D. Thiebaut | ||
+ | |||
+ | cat > vpl_execution <<EEOOFF | ||
+ | #! /bin/bash | ||
+ | #set -x | ||
+ | |||
+ | # --- program tested (no extension) --- | ||
+ | prog=Lab3_1.py | ||
+ | solutionProg=Lab3_1sol.py | ||
+ | |||
+ | # --- Python ---- | ||
+ | #python=/usr/local/bin/python3.4 | ||
+ | python=/usr/bin/python3.3 | ||
+ | |||
+ | # ================================================= | ||
+ | # Pick 3 random inputs to test program with | ||
+ | TEMP1=\$RANDOM | ||
+ | let "TEMP1 %= 30" | ||
+ | let "TEMP1 = TEMP1 + 6" | ||
+ | TEMP2=\$RANDOM | ||
+ | let "TEMP2 %= 30" | ||
+ | let "TEMP2 = 0 - TEMP2" | ||
+ | TEMP3=\$RANDOM | ||
+ | let "TEMP3 %= 30" | ||
+ | let "TEMP3 = TEMP3 + 2" | ||
+ | TEMP3=\${TEMP3}.5 | ||
+ | |||
+ | |||
+ | |||
+ | # ================================================= | ||
+ | # function that prints the difference between user and expected output | ||
+ | incorrectOutput() { | ||
+ | echo "Comment :=>>- Your output is incorrect." | ||
+ | #--- display test file --- | ||
+ | echo "<|--" | ||
+ | echo "Your program tested with \$TEMP" | ||
+ | echo "--|>" | ||
+ | |||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "Comment :=>>- Your output:" | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "<|--" | ||
+ | cat userOut.org | ||
+ | echo "--|>" | ||
+ | echo "" | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "Comment :=>>- Expected output: " | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "<|--" | ||
+ | cat expectedOut.org | ||
+ | echo "--|>" | ||
+ | |||
+ | } | ||
+ | |||
+ | # function that tells user of program crash or infinite loop, and what the test was. | ||
+ | timeoutOutput() { | ||
+ | if [ "\$1" ]; then # if there's a parameter | ||
+ | i=\$1 | ||
+ | echo "Comment :=>>- Your program has timed out or crashed." | ||
+ | |||
+ | #--- display test file --- | ||
+ | echo "Comment :=>>- Your program tested with:" | ||
+ | echo "<|--" | ||
+ | cat data\${i}.txt | ||
+ | echo "--|>" | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | # function that removes non-digits, extra spaces, and extra blank lines from text file. | ||
+ | cleanup () { | ||
+ | if [ "\$1" ]; then # if there's a parameter | ||
+ | |||
+ | #--- remove non numbers and non minus--- | ||
+ | cat \$1 | sed 's/[^0-9*.0-9\ ]*//g' > dummy.out | ||
+ | mv dummy.out \$1 | ||
+ | |||
+ | #--- remove multiple spaces --- | ||
+ | cat \$1 | sed 's/ */ /g' > dummy.out | ||
+ | mv dummy.out \$1 | ||
+ | |||
+ | #--- remove blank lines --- | ||
+ | cat \$1 | sed '/^\s*\$/d' > dummy.out | ||
+ | mv dummy.out \$1 | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | for TEMP in \$TEMP1 \$TEMP2 \$TEMP3 ; do | ||
+ | |||
+ | echo \$TEMP > input | ||
+ | |||
+ | # ================================================= | ||
+ | # generate user output and exptect output | ||
+ | \$python \$prog < input > userOut | ||
+ | \$python \$solutionProg < input > expectedOut | ||
+ | |||
+ | cp userOut userOut.org | ||
+ | cp expectedOut expectedOut.org | ||
+ | |||
+ | cleanup userOut | ||
+ | cleanup expectedOut | ||
+ | |||
+ | #--- compute difference --- | ||
+ | diff -y -w --ignore-all-space userOut expectedOut > diff.out | ||
+ | |||
+ | #--- reject if different --- | ||
+ | if ((\$? > 0)); then | ||
+ | incorrectOutput | ||
+ | grade=65 | ||
+ | # --------------------- REWARD IF CORRECT OUTPUT ----------------- | ||
+ | else | ||
+ | #--- good output --- | ||
+ | echo "Comment :=>>- Congrats, your output is correct." | ||
+ | echo "Comment :=>> --------------------------------." | ||
+ | echo "<|--" | ||
+ | echo "Your program tested with \$TEMP" | ||
+ | echo "" | ||
+ | cat userOut | ||
+ | echo "--|>" | ||
+ | grade=100 | ||
+ | fi | ||
+ | |||
+ | done | ||
+ | |||
+ | # ================================================= | ||
+ | # Report grade | ||
+ | if (( grade > 100 )); then | ||
+ | grade=100 | ||
+ | fi | ||
+ | echo "Grade :=>> \$grade" | ||
+ | |||
+ | |||
+ | exit | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | EEOOFF | ||
+ | |||
+ | chmod +x vpl_execution | ||
+ | |||
+ | </source> | ||
+ | ==Lab3_1sol.py== | ||
+ | <source lang="python"> | ||
+ | n = abs( int( eval( input( "> " ) ) ) ) | ||
+ | |||
+ | print( "You have entered:", n, "cent(s)" ) | ||
+ | no25s = n//25 | ||
+ | n = n%25 | ||
+ | no10s = n//10 | ||
+ | n = n%10 | ||
+ | no5s = n//5 | ||
+ | no1s = n%5 | ||
+ | print( no25s, "quater(s)" ) | ||
+ | print( no10s, "dime(s)" ) | ||
+ | print( no5s, "nickel(s)" ) | ||
+ | print( no1s, "cent(s)" ) | ||
+ | </source> | ||
+ | |||
+ | =VPL Module for Challenge 4= | ||
+ | ==vpl_run.sh= | ||
+ | <source lang="bash"> | ||
+ | #! /bin/bash | ||
+ | |||
+ | cat > vpl_execution <<EOF | ||
+ | #! /bin/bash | ||
+ | |||
+ | #python=/usr/local/bin/python3.4 | ||
+ | python=/usr/bin/python3.3 | ||
+ | |||
+ | prog=Lab3_4.py | ||
+ | \$python \$prog | ||
+ | |||
+ | EOF | ||
+ | |||
+ | chmod +x vpl_execution | ||
+ | </source> | ||
+ | ==vpl_evaluate.sh== | ||
+ | <source lang="bash"> | ||
+ | #! /bin/bash | ||
+ | # D. Thiebaut | ||
+ | |||
+ | cat > vpl_execution <<EEOOFF | ||
+ | #! /bin/bash | ||
+ | #set -x | ||
+ | |||
+ | # --- program tested (no extension) --- | ||
+ | prog=Lab3_4.py | ||
+ | solutionProg=Lab3_4sol.py | ||
+ | |||
+ | # --- Python ---- | ||
+ | #python=/usr/local/bin/python3.4 | ||
+ | python=/usr/bin/python3.3 | ||
+ | |||
+ | # ================================================= | ||
+ | # Pick 3 random inputs to test program with | ||
+ | TEMP1=\$RANDOM | ||
+ | let "TEMP1 %= 30" | ||
+ | let "TEMP1 = TEMP1 + 6" | ||
+ | TEMP2=\$RANDOM | ||
+ | let "TEMP2 %= 30" | ||
+ | let "TEMP2 = 0 - TEMP2" | ||
+ | TEMP3=\$RANDOM | ||
+ | let "TEMP3 %= 30" | ||
+ | let "TEMP3 = TEMP3 + 2" | ||
+ | TEMP3=\${TEMP3}.5 | ||
+ | |||
+ | # ================================================= | ||
+ | # function that looks for forbidden patterns in the program | ||
+ | testForPatterns() { | ||
+ | pattern=" -3.33C " | ||
+ | |||
+ | #echo "testForPattern" | ||
+ | |||
+ | # look for pattern after having removed comments | ||
+ | cat \$prog | sed 's:#.*$::g' > user.temp | ||
+ | grep "\$pattern" user.temp &> grepLines.out | ||
+ | |||
+ | if [ -s grepLines.out ] ; then | ||
+ | echo "Comment :=>> Your program must generate the output with a loop!" | ||
+ | echo "Comment :=>> You cannot just print the table all ready made!" | ||
+ | echo "<|--" | ||
+ | cat grepLines.out | ||
+ | echo "--|>" | ||
+ | echo "Grade :=>> 20" | ||
+ | exit | ||
+ | fi | ||
+ | |||
+ | pattern1="print" | ||
+ | pattern2="\{" | ||
+ | grep "\$pattern1" user.temp | grep "\$pattern2" &> grepLines.out | ||
+ | if [ -s grepLines.out ] ; then | ||
+ | nothing="happens" | ||
+ | else | ||
+ | echo "Comment :=>> You need to use formatting commands {...}" | ||
+ | echo "Comment :=>> in your program." | ||
+ | echo "Grade :=>> 20" | ||
+ | exit | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | # ================================================= | ||
+ | # function that prints the difference between user and expected output | ||
+ | incorrectOutput() { | ||
+ | echo "Comment :=>>- Your output is incorrect." | ||
+ | #--- display test file --- | ||
+ | #echo "<|--" | ||
+ | #echo "Your program tested with \$TEMP" | ||
+ | #echo "--|>" | ||
+ | |||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "Comment :=>>- Your output:" | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "<|--" | ||
+ | cat userOut.org | ||
+ | echo "--|>" | ||
+ | echo "" | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "Comment :=>>- Expected output: " | ||
+ | echo "Comment :=>> ---------------" | ||
+ | echo "<|--" | ||
+ | cat expectedOut.org | ||
+ | echo "--|>" | ||
+ | |||
+ | } | ||
+ | |||
+ | # function that tells user of program crash or infinite loop, and what the test was. | ||
+ | timeoutOutput() { | ||
+ | if [ "\$1" ]; then # if there's a parameter | ||
+ | i=\$1 | ||
+ | echo "Comment :=>>- Your program has timed out or crashed." | ||
+ | |||
+ | #--- display test file --- | ||
+ | echo "Comment :=>>- Your program tested with:" | ||
+ | echo "<|--" | ||
+ | cat data\${i}.txt | ||
+ | echo "--|>" | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | # function that removes non-digits, extra spaces, and extra blank lines from text file. | ||
+ | cleanup () { | ||
+ | if [ "\$1" ]; then # if there's a parameter | ||
+ | |||
+ | #--- remove non numbers and non minus--- | ||
+ | #cat \$1 | sed 's/[^0-9*.0-9\ ]*//g' > dummy.out | ||
+ | #mv dummy.out \$1 | ||
+ | |||
+ | #--- remove multiple spaces --- | ||
+ | #cat \$1 | sed 's/ */ /g' > dummy.out | ||
+ | #mv dummy.out \$1 | ||
+ | |||
+ | #--- remove blank lines --- | ||
+ | cat \$1 | sed '/^\s*\$/d' > dummy.out | ||
+ | mv dummy.out \$1 | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | for TEMP in \$TEMP1 ; do | ||
+ | |||
+ | #echo \$TEMP > input | ||
+ | |||
+ | # ================================================= | ||
+ | # generate user output and exptect output | ||
+ | \$python \$prog > userOut | ||
+ | \$python \$solutionProg > expectedOut | ||
+ | |||
+ | testForPatterns | ||
+ | |||
+ | |||
+ | cp userOut userOut.org | ||
+ | cp expectedOut expectedOut.org | ||
+ | |||
+ | cleanup userOut | ||
+ | cleanup expectedOut | ||
+ | |||
+ | #--- compute difference --- | ||
+ | diff -y -w --ignore-all-space userOut expectedOut > diff.out | ||
+ | |||
+ | #--- reject if different --- | ||
+ | if ((\$? > 0)); then | ||
+ | incorrectOutput | ||
+ | grade=65 | ||
+ | # --------------------- REWARD IF CORRECT OUTPUT ----------------- | ||
+ | else | ||
+ | #--- good output --- | ||
+ | echo "Comment :=>>- Congrats, your output is correct." | ||
+ | echo "Comment :=>> --------------------------------." | ||
+ | echo "<|--" | ||
+ | #echo "Your program tested with \$TEMP" | ||
+ | echo "" | ||
+ | cat userOut | ||
+ | echo "--|>" | ||
+ | grade=100 | ||
+ | fi | ||
+ | |||
+ | done | ||
+ | |||
+ | # ================================================= | ||
+ | # Report grade | ||
+ | if (( grade > 100 )); then | ||
+ | grade=100 | ||
+ | fi | ||
+ | echo "Grade :=>> \$grade" | ||
+ | |||
+ | |||
+ | exit | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | EEOOFF | ||
+ | |||
+ | chmod +x vpl_execution | ||
+ | |||
+ | |||
+ | </source> | ||
+ | ==Lab3_4sol.py== | ||
+ | <source lang="python"> | ||
+ | def main(): | ||
+ | # Print table of temperatures with bars around | ||
+ | bar = "+-" + 10*'-' + "--+-" + 10*'-' + "--+" | ||
+ | print( bar ) | ||
+ | print( "| {0:>10} | {1:>10} |".format( "Fahrenheit", "Celsius" ) ) | ||
+ | print( bar ) | ||
+ | for Fahr in range( 20, 41, 2 ): | ||
+ | print( "| {0:10.2f}F | {1:10.2f}C |".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) | ||
+ | print( bar ) | ||
+ | |||
+ | main() | ||
+ | </source> | ||
+ | </onlydft> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | [[Category:Labs]][[Category:CSC111]][[Category:Python]] |
Latest revision as of 00:02, 11 February 2015
--D. Thiebaut (talk) 21:22, 9 February 2015 (EST)
The lab today deals with several concepts covered in Chapter 3 of Zelle. You have two programs to submit to Moodle, one for Challenge 1, and another one for Challenge 4. The deadline for the submission is Friday 2/13 at 11:00 a.m.
Contents
- 1 Understanding how Floats take over Expressions
- 2 Teller Machine Program
- 2.1 Reviewing the Division Operators, // and %
- 2.2 Beginning Program
- 2.3 Define original amount
- 2.4 Compute the number of $20s to give out
- 2.5 Computing the Left-Over Amount
- 2.6 Computing the Remaining Quantities
- 2.7 Flexibility and Adaptability
- 2.8 Challenge #1: A Change Machine
- 2.9 Moodle Submission
- 3 Formatted Output
- 4 Accumulating Quantities
- 5 Solution Program
Understanding how Floats take over Expressions
In this section I am asking you to play and get an understanding of important functions, and also how floating point numbers (numbers with a decimal point) take over expressions, when they are present in them.
Open the Python shell and type the expressions below. Try to predict the output of the interpreter when you are about to press the ENTER key.
>>> a = 3 >>> x = 1.5 >>> type( a ) >>> type( x ) >>> type( a * x ) >>> type( a * 100 ) >>> type( 1 ) >>> type( 1.0 ) >>> type( "1" ) >>> a / 3 >>> a // 3 >>> type( a/3 ) >>> type( 5/4 ) >>> type( 5//4 ) >>> type( int( 1.5 ) ) >>> int( 1.5 ) >>> round( 1.6 ) >>> round( 1.4 ) >>> round( -1.8 ) >>> type( round( 1.4 ) ) >>> round( -1.8 ) >>> abs( -4 ) >>> abs( 10 ) >>> type( abs( -19.3 ) ) >>> type( abs( -4 ) )
- Note how once something is a float, if forces whatever it gets combined with to yield a result that is float, except for the int() function, of course.
Challenge #0: (we always start at 0 in Computer Science!) |
- Write a small program (either in the Python Shell, or in the Edit window), that asks the user to enter a number between 0 and 100, and that prints out 0 if the number is between 0 and 25 (25 not included), 1 if the number is between 25 and 50 (50 not included), 2 if the number is between 50 and 75 (75 not inclulded), and 3 if the number is between 75 and 100 (100 not included).
- Here is an example of the type of exchange I had with
>>> >>> x = eval( input( "Enter a number: " ) ) Enter a number: 75.7 >>> result = ... write an expression here that takes x and computes the expected result >>> result 3 >>> x = 1 >>> result = ... use the same expression you wrote above... >>> result 0 >>> x = 24.99999 >>> result = ... use the same expression you wrote above... >>> result 0 >>> x = 25.00000001 >>> result = ... use the same expression you wrote above... >>> result 1 >>>
Teller Machine Program
This section will get you to write a program similar (though not necessarily the same) to the program we wrote in class on Monday. The program takes an integer (without a decimal part) amount of dollars and figures out how to break it down into the least number of 20-, 10-, 5-, and 1-bills.
Reviewing the Division Operators, // and %
Use the Python shell, and try to predict the result of the following operations.
>>> 21 // 5 >>> 21 % 5 >>> 9 // 2 >>> 9 % 2 >>> 13 // 3 >>> 13 % 3 >>> 139 // 20 >>> 139 % 20
Beginning Program
- Write a program that contains
- a short header with the program name (lab3.py, for example),
- your name,
- the date, and
- A short description of the program.
- Create 3 different comment lines that will create an outline of your program.
# lab3.py # yourName # date # blah blah blah blah blah blah... # # get the initial amount # compute number of bills # output number of bills to give out
- Save and Run the program, just to make sure you do not have a syntax error.
Define original amount
- Under the #get the initial amount comment, create a variable called amount and initialize it with a value of your choice. Pick a value that is not a multiple of 5.
- Add a print() statement under the #output number of bills comment, and make it print the amount the user wants to withdraw.
- Verify that your program works.
Compute the number of $20s to give out
- Using the right operator (//, /, or %), make your program compute the number of $20 and store that value in a new variable, called no20s. Add this code under the # compute number of bills.
- Make your program output the no20s variable in the output section.
- Verify that your program works.
Computing the Left-Over Amount
- Go back to the computation of the number of $20s, and compute the amount of money left over once the $20s are taken out of the amount. You have several ways of doing this. You can do it using the % modulo operator, or using multiplication and subtraction. Whichever method you use is fine for today.
- Make your program output the left-over amount, just to make sure that value is computed correctly.
- Verify that your program works fine.
Computing the Remaining Quantities
- Now that you have the structure for your program, add enough Python code to make your code display
- The total amount
- The number of $20-bills
- The number of $10-bills
- The number of $5-bills
- The number of $1-bills
- Verify that your program works. Below is a typical output you should try to emulate:
Amount to withdraw = 97 Please lift keyboard and find: 4 $20-bill(s) 1 $10-bill(s) 1 $5-bill(s) 2 $1-bill(s)
Flexibility and Adaptability
Imagine that your program will be used in an area where the bills do not come in 20, 10, 5 or 1 denominations, but in 100, 50, 10, and 1.
Figure out a way to make the least amount of change to your program so that it now outputs the correct break down for any amount, but in $100-, $50-, $10- and $1-bills.
Make sure your program works! Below is the output of the program if the amount is set to $97:
Amount to withdraw = $ 97 Please lift keyboard and find: 0 $ 100 bill(s) 1 $ 50 bill(s) 4 $ 10 bill(s) 7 $ 1 bill(s)
Challenge #1: A Change Machine |
- Using a similar approach, write a program that, given some number of pennies, will output the correct number of quarters, dimes, nickels, and pennies. You should initialize the amount of pennies with an integer, like this:
pennies = 84
- Here is an example of what your program should output for 84 pennies:
Amount to withdraw = 84 cent(s) Please lift keyboard and find: 3 quarter(s) 0 dime(s) 1 nickel(s) 4 cent(s)
Moodle Submission
- Modify your program for Challenge 1, and rename it Lab3_1.py. It should now prompt the user for a number of pennies, and then, once it has received that number, it will print the number of coins that make up that quantity. We assume that the user may not be fully well behaved and might enter negative numbers, or numbers with a decimal point. For example, if the user enters -84, your program will treat this number as +84. If the user enters 84.5, your program will treat it as 84.
- Submit your program to the LAB 3 PB 1 section on Moodle. Note that the Moodle test program will strip all words from your output and will look only at the numbers, so you do not need to worry about the exact phrasing of your output.
Formatted Output
Strings
In this section you will work on formatting strings, ints, and floats using the {...} formatting command.
- Try this statement out:
name = "Snow White" print( "Hello {0:1}! How are you?".format( name ) )
- Then modify the {0:1} part and try these different combinations: {0:5}, {0:10}, {0:15}, {0:20}. For each one, make sure you understand why the output changes (or not).
- Then try these different formats: {0:>1}, {0:>5}, {0:>10}, {0:>15}, {0:>20}. Notice the right-justification of the string Snow White in this second set of outputs.
- Now try this piece of code:
print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "Hello {0:10}!".format( friend ) )
Printing 2 strings at once
- Change the print() statement so that you now print two different strings, each with its own {...} format:
print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{0:1} wants to take {1:1} to the Valentine's ball." . format( friend, "Snow White" ) )
- Now switch the 0 and the 1 in the two {...} expressions, as illustrated in the line below:
print( "{1:1} wants to take {0:1} to the Valentine's ball." . format( friend, "Snow White" ) )
- Notice how the first number in the {...} expressions is used to figure out which string to pick in the format(...) block.
Printing a String and an Int
- Try this formatting command:
name = "Valentine's Day" day = 15 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) name = "My birthday" day = 6 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) )
- Here's another statement to try:
name = "Snow White"
length = len( name )
print( "the string {0:1} contains {1:1} characters" . format( name, length ) ) )
Challenge #2: |
- Modify the for-loop you used before so that your program now outputs friend and len( friend ), as shown below.
Bashful 7 Doc 3 Dopey 5 Happy 5 Sleepy 6 Sneezy 6 Grumpy 6
- Once you get this output, format it into a nice looking table using the {...} formatting command.
+------------+-----+ | Bashful | 7 | | Doc | 3 | | Dopey | 5 | | Happy | 5 | | Sleepy | 6 | | Sneezy | 6 | | Grumpy | 6 | +------------+-----+
Printing Floats
- Copy/paste this block of code below in your program. Then run it. Verify that the output makes sense.
print( "Printing PI" ) pi = 3.14159 print( "-------------------------" ) print( "Pi={0:1.0f}!".format( pi ) ) print( "Pi={0:2.0f}!".format( pi ) ) print( "Pi={0:3.0f}!".format( pi ) ) print( "Pi={0:4.0f}!".format( pi ) ) print( "Pi={0:5.0f}!".format( pi ) ) print( "Pi={0:6.0f}!".format( pi ) ) print( "Pi={0:7.0f}!".format( pi ) ) print( "Pi={0:8.0f}!".format( pi ) ) print( "Pi={0:9.0f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:9.1f}!".format( pi ) ) print( "Pi={0:9.2f}!".format( pi ) ) print( "Pi={0:9.3f}!".format( pi ) ) print( "Pi={0:9.4f}!".format( pi ) ) print( "Pi={0:9.5f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:<9.1f}!".format( pi ) ) print( "Pi={0:<9.2f}!".format( pi ) ) print( "Pi={0:<9.3f}!".format( pi ) ) print( "Pi={0:<9.4f}!".format( pi ) ) print( "Pi={0:<9.5f}!".format( pi ) )
Temperature Conversion
- Remember that we saw that a temperature in Celsius is computed as the temperature in Fahrenheit - 32, the difference multiplied by 5/9?
- Write a for-loop that displays two columns of numbers, the column on the left showing degrees Fahrenheit, and the column on the right showing Celsius.
20 -6.666666666666667 22 -5.555555555555555 24 -4.444444444444445 26 -3.3333333333333335 28 -2.2222222222222223 30 -1.1111111111111112 32 0.0 34 1.1111111111111112 36 2.2222222222222223 38 3.3333333333333335 40 4.444444444444445
Challenge #3: |
- Use the {...} formatting command to make your output look nice:
20.00F = -6.67C 22.00F = -5.56C 24.00F = -4.44C 26.00F = -3.33C 28.00F = -2.22C 30.00F = -1.11C 32.00F = 0.00C 34.00F = 1.11C 36.00F = 2.22C 38.00F = 3.33C 40.00F = 4.44C
Challenge #4: |
- Add some bars and a legend, too!
+-------------+-------------+ | Fahrenheit | Celsius | +-------------+-------------+ | 20.00F | -6.67C | | 22.00F | -5.56C | | 24.00F | -4.44C | | 26.00F | -3.33C | | 28.00F | -2.22C | | 30.00F | -1.11C | | 32.00F | 0.00C | | 34.00F | 1.11C | | 36.00F | 2.22C | | 38.00F | 3.33C | | 40.00F | 4.44C | +-------------+-------------+
Moodle Submission
- Rename your program Lab3_4.py and submit it to Moodle, to the LAB 3 PB 4 section. Note that your output must match exactly the one shown above, with the right number of spaces, the same number of decimals, and the same number of lines. Your program must use a loop to generate the output, and must use formatting {...} commands.
Accumulating Quantities
Sum of a list of numbers
- Add this piece of code to your program (or create a new one):
sumAll = 0 for n in [100, 10, -30, -2, 20, 5 ]: sumAll = sumAll + n print( "sum = ", sumAll )
- Run the code. Add the numbers by hand to make sure your program outputs the correct information.
- Add this print statement inside the for-loop, right after the "sumAll = ..." statement:
print( "n = {0:3} sum = {1:3}" . format( n, sumAll ) )
- Run your code. Observe how the loop allows the variable sumAll to grow with the addition of every new number in the list.
Note that the rule for accumulating quantities with a loop is always the same:
- first you initialize a variable to represent some null quantity
- then you loop, and in the loop you increase the variable with a new quantity given by the loop.
- at the end of the loop, your variable will contain an accumulation of all the values your loop touched, or created.
Challenge #5: |
- Replace the list of numbers [100, 10, -30, -2, 20, 5 ] by the range() function and make your program compute the sum of all the even numbers between 0 and 100, included.
- Verify that your program outputs 2550 as the result! You do not need to make your program output all the intermediate values of sumAll.
Count the Items in a List
- Try this piece of code now:
count = 0 for n in [ 100, 10, -30, -2, 20, 5 ]: count = count + 1 print( "there are", count, "items in the list" )
- See how this code is different from the loop in the previous section. Here we add 1 to the counter every time we go through the loop. In other words, we add 1 for every item we find in the list. So, in effect, we are counting the items in the list.
- Run your code and see what it outputs.
- Add print statement inside the loop, below the count = count + 1 line, and make the print statement print n and count. Don't worry about the formatting.
- Run your code. Do you see the program counting the items it finds in the list of numbers?
Challenge #6: |
- Write a program that uses a for-loop that scans a list of numbers: [1, 2, 2, 1, 2, 3, 3, 2, 1, 0]
- Make your program compute the average of the numbers in the list. The average is the sum of all numbers divided by the number of items.
- Your program should output the average at the end, as a floating-point number.
- Run your program. Verify that you get the correct result (sum = 17 average = 1.70).
Accumulating Strings
- Here's a new program to try:
line = "" for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy" ]: line = line + friend + ", " print( "line =", line )
Challenge #7: (Challenging!) |
- Write a program that contains a single loop, of the form for n in ( 2, 3, 5, 3, 2 ), and that accumulates a string, which, when it is fully computed, is equal to "**---*****---**".
<showafterdate after="20150213 11:00" before="20150601 00:00">
Solution Program
# lab3Solutions.py # D. Thiebaut # Solution programs for CSC111 Lab #3 # # All the solutions are group into one large main program. def main(): # Challenge 0 for x in [ 0, 1, 24.99, 25, 25.001, 30, 51, 79, 99]: result = int( x/25 ) print( "x = ", x, " result = ", result ) # Teller Machine # Takes some amount of $ and breaks it down in 20, 10, 5, and 1 # dollar bills. # set the amount amount = 97 # break it down no20s = amount // 20 leftOver = amount % 20 no10s = leftOver // 10 leftOver = leftOver % 10 no5s = leftOver // 5 leftOver = leftOver % 5 no1s = leftOver # printout the number of bills print() print( "You want to withdraw ${0:1}".format( amount) ) print( "Lift the keyboard and find:" ) print( "{0:4} $20-bill(s)". format( no20s ) ) print( "{0:4} $10-bill(s)". format( no10s ) ) print( "{0:4} $5-bill(s)". format( no5s ) ) print( "{0:4} $1-bill(s)". format( no1s ) ) # ========================================================== # Teller Machine with a different set of denominations # set the amount amount = 197 # break it down no100s = amount // 100 leftOver = amount % 100 no50s = leftOver // 50 leftOver = leftOver % 50 no10s = leftOver // 10 leftOver = leftOver % 10 no1s = leftOver # printout the number of bills print() print( "You want to withdraw ${0:1}".format( amount) ) print( "Lift the keyboard and find:" ) print( "{0:4} $100-bill(s)". format( no20s ) ) print( "{0:4} $50-bill(s)". format( no10s ) ) print( "{0:4} $10-bill(s)". format( no5s ) ) print( "{0:4} $1-bill(s)". format( no1s ) ) # simple output print() name = "Snow White" print( "Hello {0:1}! How are you?".format( name ) ) print( "Hello {0:5}! How are you?".format( name ) ) print( "Hello {0:10}! How are you?".format( name ) ) print( "Hello {0:15}! How are you?".format( name ) ) print( "Hello {0:20}! How are you?".format( name ) ) print( "Hello {0:>1}! How are you?".format( name ) ) print( "Hello {0:>5}! How are you?".format( name ) ) print( "Hello {0:>10}! How are you?".format( name ) ) print( "Hello {0:>15}! How are you?".format( name ) ) print( "Hello {0:>20}! How are you?".format( name ) ) # Formatted output, Version 1 print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "Hello {0:10}!".format( friend ) ) # Swapping first and second strings print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{1:1} wants to take {0:1} to the Valentine's ball." . format( friend, "Snow White" ) ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{0:1} wants to take {1:1} to the Valentine's ball." . format( friend, "Snow White" ) ) # Unformatted dwarf names and length of names for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( friend, len(friend) ) # Formatted output, Version 2 bar = "+-" + 10*'-' + "-+-" + 3*'-' + "-+" print( bar ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "| {0:10} | {1:3} |".format( friend, len(friend) ) ) print( bar ) # print string and int name = "Valentine's Day" day = 15 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) name = "My birthday" day = 6 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) # printing floats print() print( "Printing PI" ) pi = 3.14159 print( "Pi={0:1.0f}!".format( pi ) ) print( "Pi={0:2.0f}!".format( pi ) ) print( "Pi={0:3.0f}!".format( pi ) ) print( "Pi={0:4.0f}!".format( pi ) ) print( "Pi={0:5.0f}!".format( pi ) ) print( "Pi={0:6.0f}!".format( pi ) ) print( "Pi={0:7.0f}!".format( pi ) ) print( "Pi={0:8.0f}!".format( pi ) ) print( "Pi={0:9.0f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:9.1f}!".format( pi ) ) print( "Pi={0:9.2f}!".format( pi ) ) print( "Pi={0:9.3f}!".format( pi ) ) print( "Pi={0:9.4f}!".format( pi ) ) print( "Pi={0:9.5f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:<9.1f}!".format( pi ) ) print( "Pi={0:<9.2f}!".format( pi ) ) print( "Pi={0:<9.3f}!".format( pi ) ) print( "Pi={0:<9.4f}!".format( pi ) ) print( "Pi={0:<9.5f}!".format( pi ) ) # Print table of temperatures print() for Fahr in range( 20, 41, 2 ): print( Fahr, (Fahr-32.0)*5.0/9 ) print() for Fahr in range( 20, 41, 2 ): print( "{0:10.2f}F = {1:10.2f}C".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) # Print table of temperatures with bars around bar = "+-" + 10*'-' + "--+-" + 10*'-' + "--+" print( bar ) print( "| {0:>10} | {1:>10} |".format( "Fahrenheit", "Celsius" ) ) print( bar ) for Fahr in range( 20, 41, 2 ): print( "| {0:10.2f}F | {1:10.2f}C |".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) print( bar ) def main2(): # compute the sum a list of numbers # (note that there's a much simpler way to do this in Python, which # we'll see later during the semester.) print() sumAll = 0 for n in [100, 10, -30, -2, 20, 5 ]: sumAll = sumAll + n print( "n = {0:3} sum = {1:3}" . format( n, sumAll ) ) print( "sum = ", sumAll ) # add-up the even numbers between 0 and 100. print() sumAll = 0 for n in range( 0, 101, 2 ): sumAll = sumAll + n print( "the sum of all the even numbers from 0 to 100, included, is", sumAll ) # count how many items are in the list print() count = 0 for n in [ 100, 10, -30, -2, 20, 5 ]: count = count + 1 print( "n = {0:3} count = {1:3}" . format( n, count ) ) print( "there are", count, "items in the list" ) # compute the sum and average of a list of numbers print() sumAll = 0 count = 0 for n in [1, 2, 2, 1, 2, 3, 3, 2, 1, 0]: sumAll = sumAll + n count = count + 1 print( "sum = {0:1} average = {1:1.2f}" . format( sumAll, sumAll*1.0/count ) ) # compute the factorial of a number # factorial( 10 ) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 print() n = 20 fact = 1 for i in range( 1, n+1 ): print( "computing fact * i = {0:1} * {1:1} = {2:1}" .format( fact, i, fact*i ) ) fact = fact * i print( "factorial({0:1}) = {1:1}".format( n, fact ) ) # create a string with all the names of the 7 dwarves print() line = "" for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: line = line + friend + ", " print( "line =", line ) # Challenge print() line = "" char1 = "*" char2 = "-" for n in ( 2, 3, 5, 3, 2 ): line = line + n*char1 char1, char2 = char2, char1 print( "line = ", line ) main2()
</showafterdate>