CS21 Lab 2: Numbers, Strings, and For Loops
Due Sunday, Feb 15, before 11:59pm
Goals
The goals for this lab assignment are:
-
manipulate Python numeric and string data types
-
learn to iterate over data using
forloops -
practice string operations:
+,*,len() -
practice using the
rangefunction -
practice using accumulators
Work through the following sections and ask if you have questions!
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.
-
Function Comments
All functions should include a comment explaining their purpose, parameters, return value, and describe any side effects. Please see our function example page if you are confused about writing function comments.
1. Triangles!
Write a program called triangle.py that computes some functions
of a right triangle given the value of its opposite side (a) and its
adjacent side (b).
/|
/ |
/ |
c / | a
/ _|
/ | |
-------
b
Your program should prompts the user for the values of a and b, and then compute:
-
The hypotenuse (c) of the triangle, which can be calculated based on this formula:
\[c^{2} = a^{2} + b^{2}\] -
The sine of the angle with
aas the opposite side andbas the adjacent side is:\[sine = \frac{a}{c}\] -
The cosine of the angle with
aas the opposite side andbas the adjacent side is:\[cosine = \frac{b}{c}\] -
The tangent of the angle with
aas the opposite side andbas the adjacent side is:\[tangent = \frac{a}{b}\]
You may assume that the user will input two positive float values for
a and b. And you do not need to handle the case of computing tangent
when b is zero (it is fine if your program ends with an error in
computing the tangent value if b is zero).
You can test correctness of your solution by trying out some values you remember from when you learned about angles and triangles in math (our example output shows a few examples you can use to test yours too). You can use an on-line calculator to compute square root values to see if your program’s solution matches what you compute by hand.
1.1. Sample output
Two examples of the running program are shown below. User input is shown in bold. The first is an example that is helpful in testing the hypotenuse calculation, and the second is an example that is helpful in testing correctness of other functions (an example of an isosoles triangle that has 45 degree angle). Neither of these tests alone are sufficient for testing correctness, and you should test with other values.
|
You are not required to print out a picture of the triangle like we do in our solution; it is optional (and it is just done with several print statements, each of which prints one line of output). However, the prompts and other output in your program should be similar to ours. |
$ python3 triangle.py
This program computes some functions of a right triangle
given the values of its two sides, a and b.
/|
/ |
/ |
c / | a
/ _|
/ | |
-------
b
Enter a value for the opposite side (a): 3
Enter a value for the adjacent side (b): 4
A right triangle with sides a = 3.0 and b = 4.0
has a hypotenuse c = 5.0
has a sin 0.6
has a cos 0.8
has a tan 0.75
$ python3 triangle.py
This program computes some functions of a right triangle
given the values of its two sides, a and b.
/|
/ |
/ |
c / | a
/ _|
/ | |
-------
b
Enter a value for the opposite side (a): 1
Enter a value for the adjacent side (b): 1
A right triangle with sides a = 1.0 and b = 1.0
has a hypotenuse c = 1.4142135623730951
has a sin 0.7071067811865475
has a cos 0.7071067811865475
has a tan 1.0
1.2. Requirements
Your program should meet the following requirements:
-
Print out a message about what the program does and then ask the user to enter two input values, a and b.
-
Calculate the values and print each out with a phrase indicating what the value is (similar to our sample output).
In addition:
-
Your output should match the examples shown above when given the same inputs (with the exception of printing out the triangle figure, which is optional).
-
Your solution should be contained within a
mainfunction that you call at the end of your program.
1.3. Tips
-
To import the
sqrtfunction (and all other functions from the math library), add this to the top of your program before the main function:
from math import *
2. Zeno’s Paradox
Zeno’s Dichotomy Paradox is an argument that motion is impossible because in order to cover any distance, one must first cover half the distance, but before one can do that, they must cover one quarter of the distance, but before they can do that, they must first cover one eighth of the distance, and so on forever.
We can think of Zeno’s Paradox as being represented by the following series:
This expands to an infinite sum of terms, each term created from a different value of \(i\) starting from \(1\) and going to \(\infty\):
Write a program that computes the sum of this series. Since your program
cannot add an infinite number of values together, it will instead compute the
sum of the first n terms of this series, given the value of n from
the user.
You may assume that the user will input a valid positive integer for the number of terms.
2.1. Sample output
Here are two example runs of a User input is shown in bold.
$ python zeno.py
This program computes the sum of the first n terms
of the series based on Zeno's Dichotomy paradox
Enter a value for n: 2
The sum of the first 2 terms is 0.75
$ python zeno.py
This program computes the sum of the first n terms
of the series based on Zeno's Dichotomy paradox
Enter a value for n: 10
The sum of the first 10 terms is 0.9990234375
2.2. Requirements
Your program should meet the following requirements:
-
Print out a short message about what the program does, and ask the to enter a value for n, the number of terms to sum.
-
Compute the sum of the first n terms of the series.
-
Print out a message with the result.
-
You must use the accumulator pattern to solve this problem.
In addition:
-
Your output should match the examples shown above when given the same inputs.
-
Your solution should be contained within a
mainfunction that you call at the end of your program.
3. Fun with Strings
Write a program called funstr.py that prompts the user for two things:
-
A string
-
A small positive integer value
Given these inputs, your program will use these values to create new strings and print out four different patterns based on them.
3.1. Sample output
Four examples of the running program are shown below. User input is shown in bold.
$ python funstr.py
This program prints out some patterns of a given string.
Please enter a string: hello
Please enter a small positive integer value: 5
1. each letter repeated 5 times:
hhhhheeeeellllllllllooooo
2. the string reversed:
olleh
3. a word tower:
h
he
hel
hell
hello
4. a different word tower:
.....h
....he
...hel
..hell
.hello
$ python funstr.py
This program prints out some patterns of a given string.
Please enter a string: hello there
Please enter a small positive integer value: 3
1. each letter repeated 3 times:
hhheeellllllooo ttthhheeerrreee
2. the string reversed:
ereht olleh
3. a word tower:
h
he
hel
hell
hello
hello
hello t
hello th
hello the
hello ther
hello there
4. a different word tower:
...........h
..........he
.........hel
........hell
.......hello
......hello
.....hello t
....hello th
...hello the
..hello ther
.hello there
$ python funstr.py
This program prints out some patterns of a given string.
Please enter a string: strings are fun!
Please enter a small positive integer value: 4
1. each letter repeated 4 times:
ssssttttrrrriiiinnnnggggssss aaaarrrreeee ffffuuuunnnn!!!!
2. the string reversed:
!nuf era sgnirts
3. a word tower:
s
st
str
stri
strin
string
strings
strings
strings a
strings ar
strings are
strings are
strings are f
strings are fu
strings are fun
strings are fun!
4. a different word tower:
................s
...............st
..............str
.............stri
............strin
...........string
..........strings
.........strings
........strings a
.......strings ar
......strings are
.....strings are
....strings are f
...strings are fu
..strings are fun
.strings are fun!
3.2. Requirements
Your program should meet the following requirements:
-
Print a message saying what the program does.
-
Prompt the user to enter a string and a small positive integer. value (
n). You can assume the user enters a valid integer value for each point. -
Print out 4 different patterns based the user’s input, namely:
-
Create a new string that consists of each letter from the input string repeated
ntimes and print it out. -
Create a new string that is the reverse of the input string and print it out.
-
Print out a word tower using the characters in the string (see the example output for what your word tower should look like).
-
Print out a different word tower using the characters in the string and the
.character (see the example output for what this different word tower should look like).
-
-
For each of the four patterns, print out the number of the pattern and a short description of what the pattern is, followed by the pattern (like in the example output).
-
You must use the accumulator pattern.
In addition:
-
Your output should match the examples shown above when given the same inputs
-
Your solution should be contained within a
mainfunction that you call at the end of your program.
3.3. Tips
-
Implement and test each one incrementally. Each pattern is increasing order of complexity, so start with the first one. However, if you get stuck on one skip ahead and try another one come back to the one you are stuck on. You may want to look at your
inclass/w02-loops/loop.pyfor a sample program with multiple loops. -
Look at the sample output often to make sure you are implementing the correct pattern (note how the value n and the length of the string are used in different patterns by looking how each pattern differs across the three example runs).
-
Look at in-class sting operator and string accumulator example code to help you. Try running the in-class code again, and you can modify it to see how it changes too.
-
Try implementing and testing partial (simplified) version of each one and then change them to implement the full pattern. For example, for pattern 3, you could just print the full string for the correct number of lines. Once that works, then modify what you print to print out an increasing number of characters each line.
-
There may be more than one way to implement a given pattern, but all require using a for loop.
-
Keep in mind that everything on one line has to be printed out before moving on to print the next line (you can’t go back and add to a previously printed line of output).
-
For pattern 4, note that what you did to solve pattern 3 is part of what you need to do to solve 4. A suggestion for solving pattern 4 incrementally is the following:
-
First try writing code to print out just the decreasing pattern of dots. Think about how many are printed the first line (what does the number of dots depend on), the second line, the third line, and so on, and come up with a general formula based on which line is printed.
-
Once you have the decreasing pattern of dots and your increasing word tower from pattern 3, put them together in such a way to figure out out the dot pattern and the word pattern for each line. You may need to adjust the way you computed the dot pattern alone to combine the two (there is more than one way to solve this, and one might lend itself to combining the two patterns more easily than another).
-
4. Extra Challenge
Do not attempt this until after you have fully completed the required parts
of this assignment, and run handin21 to submit them.
This is not worth extra credit points, but is an extra challenge to try out if you’d like.
First, copy your funstr.py to a file named extra.py:
$ cp funstr.py extra.py
Open extra.py in the code editor, delete most of the main code
except the parts that reads in the string.
code extra.py
Then try adding one or both of the pyramid patterns from the string entered by the user shown in the example output
There are no Hints on extra challenge problems, but it may be helpful to
remember that space is a valid character that can be part of a string. You can
represent a string consisting of a single space character as double quotes with
space between them: " " (just like a string with a single a character would
be represented as "a").
4.1. Example Output
Here is output from two runs of a extra challenge program:
$ python ./extra.py
This program prints out some patterns of a given string.
Please enter a string: banana
word pyramid (extra challenge):
bb
baab
bannab
banaanab
banannanab
bananaananab
a different word pyramid (extra extra challenge):
b
bab
banab
bananab
banananab
bananananab
$ python ./extra.py
This program prints out some patterns of a given string.
Please enter a string: Python Strings Rock!
word pyramid (extra challenge):
PP
PyyP
PyttyP
PythhtyP
PythoohtyP
PythonnohtyP
Python nohtyP
Python SS nohtyP
Python SttS nohtyP
Python StrrtS nohtyP
Python StriirtS nohtyP
Python StrinnirtS nohtyP
Python StringgnirtS nohtyP
Python StringssgnirtS nohtyP
Python Strings sgnirtS nohtyP
Python Strings RR sgnirtS nohtyP
Python Strings RooR sgnirtS nohtyP
Python Strings RoccoR sgnirtS nohtyP
Python Strings RockkcoR sgnirtS nohtyP
Python Strings Rock!!kcoR sgnirtS nohtyP
a different word pyramid (extra extra challenge):
P
PyP
PytyP
PythtyP
PythohtyP
PythonohtyP
Python nohtyP
Python S nohtyP
Python StS nohtyP
Python StrtS nohtyP
Python StrirtS nohtyP
Python StrinirtS nohtyP
Python StringnirtS nohtyP
Python StringsgnirtS nohtyP
Python Strings sgnirtS nohtyP
Python Strings R sgnirtS nohtyP
Python Strings RoR sgnirtS nohtyP
Python Strings RocoR sgnirtS nohtyP
Python Strings RockcoR sgnirtS nohtyP
Python Strings Rock!kcoR sgnirtS nohtyP
5. Answer the Questionnaire
After each lab, please complete the short Google Forms questionnaire. Please select the right lab number (Lab 02) 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
(
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!