CS21 Lab 1: First Programs

Due Saturday, September 10, by 11:59pm

In this lab you will write a few basic python programs. For each program, we provide specifications and some sample output. Edit the files after running update21 and then run handin21 to submit your solution. Complete a short questionnaire once you are done. Full details are below.

Programming Tips

As you write programs, use good programming practices:

  • Use a comment at the top of the file to describe the purpose of the program (see example).

  • All programs should have a main() function (see example).

  • Use variable names that describe the contents of the variables.

  • Write your programs incrementally and test them as you go. This is really crucial to success: don’t write lots of code and then test it all at once! Write a little code, make sure it works, then add some more and test it again.

  • Don’t assume that if your program passes the sample tests we provide that it is completely correct. Come up with your own test cases and verify that the program is producing the right output on them.

  • Avoid writing any lines of code that exceed 80 columns.

    • Always work in a terminal window that is 80 characters wide (resize it to be this wide)

    • In vscode, at the bottom right in the window, there is an indication of both the line and the column of the cursor.

Are your files in the correct place?

Make sure all programs are saved to your cs21/labs/01 directory! Files outside that directory will not be graded.

$ update21
$ cd ~/cs21/labs/01
$ pwd
/home/username/cs21/labs/01
$ ls
Questions-01.txt
(should see your program files here)

Goals

The goals for this lab assignment are:

  • Write your first python programs!

  • Practice using an editor

  • Use variable assignment to store values

  • Get comfortable with print() and input()

  • Get comfortable with python data types: int, float, str

  • Use type casting with input() to get numeric data

1. A first program (Optional Warmup)

The file intro.py is initially empty. Practice using an editor and type in the program below. Note that since the point is to start getting used to typing Python code, you should actually type this, rather than using copy/paste. This part will not be graded; it is an optional (but recommended) warmup to help make sure you understand the workflow before you start trying to come up with your own code.

After saving your file, run the program and fix any errors.

Here is the program to type:

"""
  This is a sample python program

  Author: <Put your name here>
  Date: <Put today's date here>
"""

#define the main function
def main():
    name = input("What is your name? ")
    print("Hello")
    print(name)
    print("Nice to meet you")

# run the body of the main function defined above
main()

Here are two examples of the running program. User input is shown in bold.

$ python3 intro.py

What is your name? Emily
Hello
Emily
Nice to meet you
$ python3 intro.py

What is your name? Ada Lovelace
Hello
Ada Lovelace
Nice to meet you

2. Nonsense Cookery

There are many interesting forms of computational poetry; for this part of your lab, you will write a program to generate nonsense recipes inspired by those of Edward Lear: here are some examples.

Write a program, in the recipe.py file, that generates a simple recipe based on user input. It should prompt the user for several words, and then combine them with a template to print out a statement (this program is similar to a Mad Lib).

The basic template should look like this:

  TO MAKE RECIPE_NAME

Take INGREDIENT_1 and place it in VESSEL;
add INGREDIENT_2 and COMBINE.

Each of the bolded statements represents a string you’ll need to get from the user.

2.1. Sample Output

Here are two examples of running the program; user input is shown in bold.

$ python3 recipe.py
Enter the name of the recipe: Noodle Soup
Enter the first ingredient: broth
Enter the second ingredient: noodles
Enter a noun for putting things in: pot
Enter a verb for combining things: simmer
----------------------------------------

  TO MAKE Noodle Soup

Take broth and place it in pot;
add noodles and simmer.
$ python3 recipe.py
Enter the name of the recipe: CS21
Enter the first ingredient: a live python
Enter the second ingredient: 3/4 C. theory (coarsly chopped)
Enter a noun for putting things in: your brain
Enter a verb for combining things: stir gently for 14 weeks
----------------------------------------

  TO MAKE CS21

Take a live python and place it in your brain;
add 3/4 C. theory (coarsly chopped) and stir gently for 14 weeks.

A note on printing strings

Printing Strings in Python

Remember that you can concatenate (+) strings together to print them out on a single line. E.g.

print("hi" + "there")

will result in the output

hithere

Note that this does not add a space between the two parts; if you want the words separated, you have to add the space manually, e.g.:

print("hi " + "there")

(note the extra space after hi before the quotation mark) will result in the output

hi there

Also note that you can use print() with no arguments to print a blank line, e.g.:

print("hi " + "there")
print()
print("cs21!")

will result in the output

hi there

cs21!

2.2. (Optional) More interesting recipes

The template we used for the previous program is a bit simplistic; it works, but you’re very limited in the type of nonsense-recipe you can make with it.

For an (optional) extra challenge, create another program called recipe_extra.py that works similarly to the one above, but involves a more interesting template. Exactly how you want this program to work is up to you; how many different words do you want to get from the user, and what sort of prompts will you use? What sort of template will you use to combine those words into a "recipe"? Be creative, and try out several different options!

3. Python Math Operators

To familiarize yourself with python’s math operators, write a program called python_math.py that asks the user for two integer operands and shows the results of applying each of the following operators:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Integer division (//)

  • Mod (%)

  • Exponentiation (**)

3.1. Sample Output

Here are two examples of the running program. User input is shown in bold.

$ python3 python_math.py

This program tests some python mathematical operators
Enter a positive integer value: 12
Enter another (small) positive integer value: 5

12 + 5 = 17
12 - 5 = 7
12 * 5 = 60
12 / 5 = 2.4
12 // 5 = 2
12 % 5 = 2
12 ** 5 = 248832
$ python3 python_math.py

This program tests some python mathematical operators
Enter a positive integer value: 13
Enter another (small) positive integer value: 2

13 + 2 = 15
13 - 2 = 11
13 * 2 = 26
13 / 2 = 6.5
13 // 2 = 6
13 % 2 = 1
13 ** 2 = 169

A note on strings and numbers

Converting between Strings and Numbers in Python

Remember that user input starts out as a string, so you’ll need to convert it to an appropriate numeric type before you can do math with it. E.g.:

val_s = input("give me a number! ")
val = int(val_s)

Here, val_s is a string, and val is an integer, meaning if you try to apply operators (e.g. +, -, *, etc.) to these two variables, different things will happen. Applying the + operator to val will try to do numeric addition (which requires that both operands be numbers); applying the + operator to val_s will try to do string append (which requires that both operands be strings).

Note that this latter fact means that in order to print int or float values and strings such as " - " on the same line (as you’ll need to for this program), you must first convert int and float values to strings (e.g., str(val)), then use string concatenation (+) to combine the strings together to create a single resulting string for print to print. For example:

num = 6
print("value = " + str(num))

produces the following output:

value = 6

4. Split the Dinner Bill

In the file share_table.py, implement a program that helps the user divide up a bill between several friends sharing a meal at a restaurant. For this assignment, we’ll assume that the bill can be split evenly.

You’ll need to prompt the user for the base cost, the percentage to tip, and the number of people splitting things. Then calculate the actual tip amount, add it to the base cost, and devide the result by the number of people.

You should assume that the number of people and tip percentage are integers, and that the base cost is a floating point number.

You do not have to worry about having an even number of pennies (i.e. exactly two decimal places). If you want to attempt this as an extra challenge, see the optional section on rounding below.

4.1. Sample Output

Here are two examples of the running program. User input is shown in bold.

$ python3 share_table.py
Welcome to the share-a-table app!

Enter the amount on the bill: $27
Enter the tip percentage: 20
Enter the number of people splitting the bill: 2
----------------------------------------
Subtotal: $27.0
Tip: $5.4
Total: $32.4
Each person should contribute: $16.2
$ python3 share_table.py
Welcome to the share-a-table app!

Enter the amount on the bill: $43.71
Enter the tip percentage: 25
Enter the number of people splitting the bill: 5
----------------------------------------
Subtotal: $43.71
Tip: $10.9275
Total: $54.6375
Each person should contribute: $10.9275

4.2. (Optional) Rounding

As an optional challenge, you can use Python’s built-in round() function to round your results to the nearest cent (i.e. 2 digints after the decimal place). To use it, add a call to round with two parameters: the number to round and the number of digits beyond the decimal point to which you want to round.

For example, if you wanted to round the square root of 2 to two decimal places:

# raising a number to the power of 1/2 is the same as taking the square root
sqrt2 = 2.0 ** 0.5

sqrt2_rounded = round(sqrt2, 2)

print("square root of 2 is: " + str(sqrt2))
print("square root of 2 to two decimal places is: " + str(sqrt2_rounded))

Which produces:

square root of 2 is: 1.4142135623730951
square root of 2 to two decimal places is: 1.41

A Note on Line Breaks

Line Continuation (\) in Python

Each line of in your program files should not be longer than 80 characters. This is because 80 characters is the historical "standard" width of terminals, and also because when we print out your programs to grade it will display only 80 characters of width.

Occasionally, you will find that you have a very long Python statement that exceeds 80 characters long. In this case you can use the Python line continuation character \ part way through the long line, and then continue the long python statement on the next line.

For example:

    # this print stmt is too long and visually wraps around in a bad way
    print("This is a very long string " + str(result) + " for which I should  use line continuation instead!")

    # here is the fix to get rid of the line wrapping by using the line
    # continuation character (\) to tell python3 that the print stmt
    # continues on the next line:
    print("This is a very long string " + str(result) \
          + " for which I should  use line continuation instead!")

Working in a window 80 characters wide will help you detect when you have a line that is too long and needs to be continued.

5. Answer the Questionnaire

Each lab will have a short questionnaire at the end. Please edit the Questions-01.txt file in your cs21/labs/01 directory and answer the questions in that file.

Once you’re done with that, you should run handin21 again.

Submitting lab assignments

Remember to run handin21 to turn in your lab files! You may run handin21 as many times as you want. Each time it will turn in any new work. We recommend running handin21 after you complete each program or after you complete significant work on any one program.

Logging out

When you’re done working in the lab, you should log out of the computer you’re using.

First quit any applications you are running, like the browser and the terminal. Then click on the logout icon (logout icon or other logout icon) and choose "log out".

If you plan to leave the lab for just a few minutes, you do not need to log out. It is, however, a good idea to lock your machine while you are gone. You can lock your screen by clicking on the lock xlock icon. PLEASE do not leave a session locked for a long period of time. Power may go out, someone might reboot the machine, etc. You don’t want to lose any work!