CS21 Lab 1: First Programs
Due Saturday, January 28, by 11.59 PM
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()
andinput()
-
Get comfortable with python data types:
int
,float
,str
-
Use type casting with
input()
to get numeric data
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)
1. A first program (Optional Warmup)
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()
Here are two examples of the running program. User input is shown in bold.
$ python3 intro.py What is your name? Riya Hello Riya Nice to meet you!
$ python3 intro.py What is your name? Betty Holberton Hello Betty Holberton Nice to meet you!
Curious to know who Betty Holberton was? She was one of the original six American female computer scientists to program the first electric digital computer, ENIAC. |
A note on printing strings
Printing Strings in Python
Here’s an example of printing two words separated by a single blank space:
Hi there! You can also use
will result in the output Hi there! Welcome to CS21! |
2. Script your own SuperHero movie
In this program, we will generate our very own SuperHero plot lines. Your task is to write a program in superhero.py
, that generates a one sentence plot-line for the next blockbuster superhero movie.
Your program should prompt the user for several words, and then combine them with the superhero template (shown below) to print out a statement. This program is similar to a Mad Lib.
The basic template follows the tale of a superhero and their sidekick, and should look like this:
TITLE: The Tale of NOUN and NOUN NOUN the mighty and NOUN the VERB use their secret power - NOUN to defeat the evil NOUN and save humanity!
Each of the bolded words 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 superhero.py Enter the superhero's name: Calvin Enter the sidekick's name: Hobbes Describe the sidekick: ferocious Enter their secret power: sillyness Enter the villain's name: Snow Goons ---------------------------------------- TITLE: The Tale of Calvin and Hobbes Calvin the mighty and Hobbes the ferocious use their secret power - sillyness to defeat the evil Snow Goons and save humanity!
$ python3 superhero.py Enter the superhero's name: Patrick Enter the sidekick's name: Squidward Describe the sidekick: grumpy Enter their secret power: terrible trombone skills Enter the villain's name: Giant Brown Bubble ---------------------------------------- TITLE: The Tale of Patrick and Squidward Patrick the mighty and Squidward the grumpy use their secret power - terrible trombone skills to defeat the evil Giant Brown Bubble and save humanity!
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 For example:
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. |
3. Python Math Operators
To familiarize yourself with Python’s math operators, complete the program called simple_math.py
that shows the result of addition, multiplication and exponentiation. The operators for each are shown below:
-
Addition (
+
) -
Multiplication (
*
) -
Exponentiation (
**
) -
Division (
/
) -
Integer division (
//
) -
Mod (
%
)
Complete the program started in simple_math.py
to 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.
Two sample runs are shown below. User input is shown in bold.
3.1. Sample Output
$ python3 simple_math.py This program tests some python math operators. Enter the first positive integer value: 10 Enter the second positive integer value: 6 10 + 6 = 16 10 * 6 = 60 10 ** 6 = 1000000 10 / 6 = 1.6666666666666667 10 // 6 = 1 10 % 6 = 4
$ python3 simple_math.py This program tests some python math operators. Enter the first positive integer value: 3 Enter the second positive integer value: 5 3 + 5 = 8 3 * 5 = 15 3 ** 5 = 243 3 / 5 = 0.6 3 // 5 = 0 3 % 5 = 3
4. Computation’s Impact on Climate Change
Computers and smart devices contribute significantly to green house gas emissions. You can read more about the the staggering impact of computation on climate change here. A significant research effort in computer science is Green Computing, where researchers try to measure and lower our carbon footprint, advance the use of renewable sources of energy, and re-think the design and lifecycle of computer-farms, personal computers and smart devices. |
A carbon tax is often used to quantify and regulate the use of carbon emissions to move away from fossil-fuels and incentivize the use of renewable energy. Let’s write a program carbon_tax.py
that calculates the cost of generating energy for a typical datacenter. Datacenters are used by large tech companies (Google, Amazon, Facebook, etc) to house football-field sized buildings filled with computers! We are going to consider three major sources energy used today for most datacenters: coal, natural gas and renewable energy.
4.1. Calculating Carbon Tax
Your program carbon_tax.py
will take as input the energy_use_per_day
in a typical datacenter, and the percentage of energy dependence on coal and natural gas. We will then calculate carbon tax based on a datacenter’s reliance on non-renewables vs renewables.
We will make the following formulae and assumptions in our calculations:
-
Typical
energy_use_per_day
at a datacenter is a positive integer value that lies between 500 - 800 Gigawatt-hours (GWh). We will then calculate the percentage of dependence on non-renewables as follows:percent_non_renewable = percent_coal + percent_natural_gas
-
We will now use the following formula to calculate the carbon tax per Gigawatt-hour for the percentage of coal and natural gas use. Based on recent estimates coal is taxed at $0.06 and natural gas at $0.03 per Gigawatt-hour.
tax_GWh = percent_coal * 0.06 + percent_natural_gas * 0.03
-
percent_coal
andpercent_natural_gas
take as input floating point values. -
You can create two variables to store the carbon tax associated with coal and natural gas.
-
-
The formula above calculates the tax dollar amount per GigaWatt-hour. To calculate the carbon tax per day, we multiply the
tax_GWh
by the energy use per day:tax_day = tax_GWh * energy_use_per_day
-
We will also calculate the tax per week, by multiplying the
tax_day
by 7 days of the week:tax_week = tax_day * 7
4.2. Sample Output
Here are two examples of the running program. User input is shown in bold.
$ python3 carbon_tax.py Enter the datacenter energy use per day in GWh: 550 Enter the percentage reliance on coal: 20 Enter the percentage reliance on natural gas: 40 ---------------------------------------- Energy dependence on non-renewables: 60 Carbon tax per GigaWatt-hour, (tax_GWh): $2.4 Carbon tax per day, (tax_day): $1320.0 Carbon tax per week, (tax_week): $9240.0
$ python3 carbon_tax.py Enter the datacenter energy use per day in GWh: 800 Enter the percentage reliance on coal: 10.5 Enter the percentage reliance on natural gas: 12.2 ---------------------------------------- Energy dependence on non-renewables: 22.7 Carbon tax per GigaWatt-hour, (tax_GWh): $0.996 Carbon tax per day, (tax_day): $796.8 Carbon tax per week, (tax_week): $5577.599999999999
4.3. 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:
1
2
3
4
5
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).
$ python3 carbon_tax.py Enter the datacenter energy use per day in GWh: 800 Enter the percentage reliance on coal: 10.5 Enter the percentage reliance on natural gas: 12.2 ---------------------------------------- Energy dependence on non-renewables: 22.7 Carbon tax per GigaWatt-hour, (tax/gwh): $1.0 Carbon tax per day, (tax/day): $796.8 Carbon tax per week, (tax/week): $5577.6
Notice that if, after rounding, the hundredths place is a 0, Python might not print it. This is fine. |
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 ( or ) 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 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!