CS21 Lab 2: More first Programs

Due Saturday, February 5, by 11:59pm

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 vim, at the bottom left 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/02 directory! Files outside that directory will not be graded.

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

Goals

The goals for this lab assignment are:

  • write some more python programs

  • get comfortable with using input() and print()

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

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

1. Python Math Operators

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

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Integer division (//)

  • Mod (%)

  • Exponentiation (**)

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

$ python3 pythonmath.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 pythonmath.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

Note that you can use print() with no arguments to print a blank line.

Also note that to print int or float values and the strings such as " - " on the same line, you must first convert int and float values to strings (e.g., str(x)), then use string concatenation (+) to combine the strings together to create a single resulting string for print to print. For example, if the current value of the variable x is 6, then print("the value is " + str(x)) prints:

the value is 6
a vim shortcut

In vim ESC-mode use the yy command to yank (copy) the line that the cursor is on, move the cursor to where you want to put (paste) the copied line, and use p to put (paste) it on the line below the cursor.

You can also copy multiple lines using <num>yy and still use p to put (paste) all of the yanked (copied) lines. For example, 5yy copies the 5 lines starting with the one on which the cursor is.

The vim shortcut might be useful in this program when writing many print statements that are very similar---type in one print statement, then copy and paste it to another location in your file, and edit the pasted copy vs. writing another very similar print statement from scratch.

2. Compliment Helper

Write a program, in the compliment.py file, that generates a compliment that you can give to someone. This program is similar to a Mad Lib.

Here are two examples. User input is shown in bold.

$ python3 compliment.py
I'm going to help you compliment your friend
Their name: Vic
Noun: cat
Adjective: orange
Verb with an ing at the end: sleeping

Vic
You are a wonderful cat
Your orange approach to sleeping is inspiring!
$ python3 compliment.py
I'm going to help you compliment your friend
Their name: Sarita
Noun: tree
Adjective: fun
Verb with an ing at the end: eating

Sarita
You are a wonderful tree
Your fun approach to eating is inspiring!

Note that the template for the compliment is the following:

NAME
Your are a wonderful NOUN
Your ADJECTIVE approach to ING_VERB is inspiring!

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

3. Convert Fahrenheit to Celsius

In the file, fahr2cel.py, implement a program that prompts the user to enter a temperature in Fahrenheit, converts it to Celsius, and prints out the result.

The formula for converting Fahrenheit to Celsius is:

\( ^{\circ}C = \left( ^{\circ}F - 32 \right) \times \frac{5}{9}\)

Here are two examples. User input is shown in bold.

$ python3 fahr2cel.py
This program converts degrees Fahrenheit to Celsius
Enter the temperature in degrees F: 36

36.0 converted to Celsius is 2.2222222222222223
$ python3 fahr2cel.py
This program converts degrees Fahrenheit to Celsius
Enter the temperature in degrees F: 0

0.0 converted to Celsius is -17.77777777777778

3.1. Optional Rounding

As an optional challenge, you can use Python’s built-in round() function to round your results to the nearest 100ths of a degree. 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 pi to two decimal places:

pi = 3.141592

pi_rounded = round(pi, 2)

print("pi rounded to two decimal places is: " + str(pi_rounded))

Which produces:

pi rounded to two decimal places is: 3.14

4. Wind Chill Calculator

This time of year it often feels much colder than the outside temperature indicates. To dress warm enough for a walk from your dorm to campus, it is good to look at the wind chill, the temperature that it actually feels outside, and dress according to the wind chill temperature.

In the file, windchill.py, implement a program that prompts the user to enter a temperature in Fahrenheit, and a wind speed, and converts it to Celsius, and prints out the result.

This is the formula for computing windchill given temperature (Temp) in Fahrenheit and a wind velocity (or wind speed) (Vel) in miles per hour:

\( \mathrm{Wind\ Chill} = 35.74 + (0.6215 \times \mathrm{Temp}) - (35.75 \times \mathrm{Vel}^{0.16}) + (0.4275 \times \mathrm{Temp} \times \mathrm{Vel}^{0.16})\)

Your program should print out the windchill in both Fahrenheit and Celsius. You can convert your Fahrenheit windchill value to Celsius using the same calculation as in the previous program. You can also check your calculation by comparing it to the National Weather Service Wind Chill Calculator. Your values should be about the same as these.

Wind chills cannot be calculated for temperatures above 50 degrees Fahrenheit, or for wind velocities under 3 MPH. Your program does not need to check for and handle invalid temperature and velocity values. You can assume a user enters valid temperature and velocities, and if they don’t, it is fine that the wind chill value your program computes doesn’t make sense.

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

$ python3 windchill.py

This program computes wind chill in Fahrenheit (and Celsius)
  Enter the current temperature (in F): 20.4
  Enter the wind velocity (in miles/hr): 4.2

When the temp is 20.4 and wind speed is: 4.2
 the wind chill in F is  14.413045200762866
 the wind chill in C is  -9.77053044402063
$ python3 windchill.py

This program computes wind chill in Fahrenheit (and Celsius)
  Enter the current temperature (in F): 20.4
  Enter the wind velocity (in miles/hr): 35.6

When the temp is 20.4 and wind speed is: 35.6
 the wind chill in F is  0.5487597741684898
 the wind chill in C is  -17.47291123657306
$ python3 windchill.py

This program computes wind chill in Fahrenheit (and Celsius)
  Enter the current temperature (in F): -2
  Enter the wind velocity (in miles/hr): 20.5

When the F temp is -2.0 and wind speed is: 20.5
 the wind chill in F is  -24.853041772089398
 the wind chill in C is  -31.585023206716333

As an extra challenge you can try rounding the resulting windchill values to two places after the decimal point (see Section 3.1).

Line Continuation (\) in Python

Each line of in your program files should not be longer than 80 characters. 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 terminal 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-02.txt file in your cs21/labs/02 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.

When Remotely logged in

When you are ssh’ed into the CS labs, first quit any applications you are running, like vim, then simply type exit at the prompt in your terminal window to disconnect.

When Physically logged in

When you are in a CS lab logged into a CS machine. 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!