CS21 Lab 1: First Programs

Due Saturday, September 14, before midnight

Goals

The goals for this lab assignment are:

  • Practice using a text editor such as Visual Studio Code.

  • Write your first python programs!

  • 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

Warmup: A first program

The file intro.py is initially empty. Practice using an editor and type in the program below.

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()

Sample output

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

$ python3 intro.py

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

What is your name? Shafi Goldwasser
Hello
Shafi Goldwasser
Nice to meet you!

A note on printing strings

Printing Strings in Python

Here’s an example of printing two words separated by a single blank space:

print("Hi " + "there!")

The extra space after Hi and BEFORE the quotation will result in the following output:

Hi there!

You can also use print() with no arguments to print a blank line, e.g.:

print("Hi " + "there!")
print()
print("Welcome to CS21!")

will result in the output

Hi there!

Welcome to CS21!

Favorite Place

Write a program called place.py that asks the user for their favorite place to visit and their favorite activity in that place. Your program should then print a short response as shown below.

Sample output

Two examples of the running program are shown below. User input is shown in bold.

Autograder test 1
$ python3 place.py
Where is your favorite place to visit? Pittsburgh
What do you like doing there? Eating pierogies

Eating pierogies in Pittsburgh sounds like fun!
Autograder test 2
$ python3 place.py
Where is your favorite place to visit? CS21 lab
What do you like doing there? Learning how to solve complex problems

Learning how to solve complex problems in CS21 lab sounds like fun!

Requirements

Your program should meet the following requirements:

  1. Ask the user for their favorite place to visit and what they like doing there.

  2. Print a short response that includes their favorite place and activity.

Your output should match the examples shown above when given the same inputs. Your solution should be contained within a main function that you call at the end of your program

Python Debugging

Often a program won’t work as intended the first time we try to run it. We must review and revise the program in a process called debugging to fix syntax or logic errors in our program. The provided program fixme.py should complete the following steps:

  1. Prompt the user for an integer n

  2. Compute the value 3n and store it in the variable answer

  3. Print the string 3*n = followed by the answer

However when we run the program, we get the following output:

$ python3 fixme.py
  File "fixme.py", line 22
    val = input("Enter an integer n: )
                ^
SyntaxError: unterminated string literal (detected at line 22)

Look closely at the program and the error output and try to fix this first error. Looking at a working example program may help. Unfortunately, there are three more errors in this program. After fixing the first, continue your debugging process to fix the other three. At some point, python may not generate any error messages, but it also doesn’t generate any output at all. Something is missing at the end of your program. Can you add it to fix the program? Compare the bottom of your non-working program to a working example in-class program if you need a hint.

The broken fixme.py as provided is shown below. You should fix the errors in this program.
def main():

    val = input("Enter an integer n: )
    n = int(val)
    answer = 3n
    print("3*n = " + answer )

Sample output

When all errors are fixed, the program should run as follows, where user input is in bold:

Autograder test 1
$ python3 fixme.py
Enter an integer n: 5
3*n = 15
Autograder test 2
$ python3 fixme.py
Enter an integer n: 0
3*n = 0

Requirements

Your program should meet the following requirements:

  1. Run without errors.

  2. Ask the user to enter a number and display the result of multiplying that number by 3.

Your output should match the examples shown above when given the same inputs. Your solution should be contained within a main function that you call at the end of your program

Python Math Operators

To familiarize yourself with Python’s math operators, complete the program called math_demo.py that shows the result of various math operations on integer inputs. The operators for each are shown below:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Floor division (//) - sometimes called "Integer division" or "Whole division"

Complete the program in the empty math_demo.py file provided. The program should print the result of math operations shown above. To do so, your program, should prompt the user to type in the two numbers num1 and num2. Both num1 and num2 should be chosen to be small positive integer values.

Sample Output

Two sample runs are shown below. User input is shown in bold.

Autograder test 1
$ python3 math_demo.py
This program tests some python math operators.
Enter the first positive integer value: 1
Enter the second positive integer value: 2

1 + 2 = 3
1 - 2 = -1
1 * 2 = 2
1 / 2 = 0.5
1 // 2 = 0
Autograder test 2
$ python3 math_demo.py
This program tests some python math operators.
Enter the first positive integer value: 4
Enter the second positive integer value: 3

4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.3333333333333333
4 // 3 = 1

Requirements

Your program should meet the following requirements:

  1. Ask the user for two integer values.

  2. Show the result of combining these two integers using addition, subtraction, multiplication, division, and floor division.

Your output should match the examples shown above when given the same inputs. Your solution should be contained within a main function that you call at the end of your program

Trip Cost Calculator

A fictional ride share company Swyft charges a base fare of $2.00 plus $0.80 per mile and $0.15 per minute. Write a program called trip.py that asks the user for the number of miles and the number of minutes of the trip. Your program should then calculate and print the total cost of the trip. You may assume the minutes and miles are positive integers.

Sample Output

Three sample runs are shown below. User input is shown in bold.

Note: you are not required to format decimals to round to the nearest penny. We expect your output to be the same as our output shown below because you haven’t learned how to display this properly yet.

Autograder test 1
$ python3 trip.py
This program estimates the cost of a ride share trip.
Enter the number of miles in the trip: 10
Enter the number of minutes in the trip: 17

The estimated cost of the trip is $12.55
Autograder test 2
$ python3 trip.py
This program estimates the cost of a ride share trip.
Enter the number of miles in the trip: 11
Enter the number of minutes in the trip: 12

The estimated cost of the trip is $12.600000000000001
Autograder test 3
$ python3 trip.py
This program estimates the cost of a ride share trip.
Enter the number of miles in the trip: 6
Enter the number of minutes in the trip: 10

The estimated cost of the trip is $8.3

Requirements

Your program should meet the following requirements:

  1. Ask the user for the number of miles and the number of minutes for the trip.

  2. Compute the cost of the trip using the rate specified in the description above.

Your output should match the examples shown above when given the same inputs. Your solution should be contained within a main function that you call at the end of your program

Optional Rounding

As an optional challenge, you can use Python’s built-in round() function to round your results to the nearest penny. To use it, you can call round with two parameters: the number to round and the number of digits you want to round to (two for pennies).

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

Note that converting the result of round to a string with str() is necessary for concatenation (adding the result to a string).

Notice that after rounding to two decimal places, if the hundredths place is a 0, Python won’t print that last 0. We haven’t seen how to fix that yet so for this lab, that is the expected output.
Your lab should still pass all of the tests of the autograder even if you have implemented the optional rounding.

The CS21 Autograder

This year, we are piloting a new tool grade21 which will look at your lab work so far and give you feedback on how you are doing. This tool is not perfect, but it should give you a good idea of how you are doing on the lab assignments. Your real lab grade will be assessed by the CS21 grading staff and will be based on meeting the requirements of the lab assignments as outlined above.

To run the autograder, type grade21 01. This will perform a series of checks on your lab work and give you feedback which autograder tests pass and which ones fail. When you start coding, many of the tests will not pass. As you complete the lab, more and more tests should pass. When you are actively working on a program, only review the results for that program.

As the autograder is a new tool and completely automated, it may not be perfect. It also typically expects the output of your program to exactly match the output of lab examples. Something as small as a spacing, a typo in an input prompt, or extra/missing blank lines may cause the autograder to say a program is not passing, even thought it meets the requirements of the lab and will be graded as correct by the staff.

Running the autograder is completely optional.

The autograder may write some .log or .json files in your lab directory. You can safely ignore these files. handin21 will not submit them, but may complain about an unknown extension. You can quash these warnings by performing the following command in your cs21 folder one time

[01]$ cd     #  go to your home directory
[~]$ cd cs21 #  go to your cs21 directory
[cs21]$ rm .gitignore #remove the .gitignore file, don't forget the dot, but don't include extra spaces
rm: remove regular file '.gitignore'? y #type y and hit enter
[cs21]$ update21 #update the cs21 directory to get a new .gitignore file
...
[cs21]$ handin21 #submit the updated changes

Answer the Questionnaire

After each lab, please complete the short Google Forms questionnaire. Please select the right lab number (Lab 01) from the dropdown menu on the first question.

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, including your vscode editor, 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!