In this block, we covered the following chapters:
In this assignment, you will be asked to show what you have learned from the topics above!
In [ ]:
# average code
Suppose the cover price of a book is 24.95 EUR, but bookstores get a 40 percent discount. Shipping costs 3 EUR for the first copy and 75 cents for each additional copy. Write a program that can calculate the total costs for any number of copies for both bookstores and other customers. Use variables with clear names for your calculations and print the result using a full sentence.
In [ ]:
# book price code
There is one operator (like the ones for multiplication and subtraction) that we did not discuss yet, namely the modulus operator %. Could you figure by yourself what it does when you place it between two numbers (e.g. 113 % 9)? (PS: It's OK to get help online...) You don't need this operator all that often, but when you do, it comes in really handy!
In [ ]:
# try out the modulus operator!
Can you use the modulus operator you just learned about to solve the following task? Write a code block that classifies a given amount of money into smaller monetary units. Set the amount variable to 11.56. You code should output a report listing the monetary equivalent in dollars, quarters, dimes, nickels, and pennies. Your program should report the maximum number of dollars, then the number of quarters, dimes, nickels, and pennies, in this order, to result in the minimum number of coins. Here are the steps in developing the program:
In [ ]:
# cashier code
What is the difference between using + and , in a print statement? Illustrate by using both in each of the following:
print() fuction with multiple strings
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Write a program to have a little conversation with someone. First ask them for their name and their age, and then say something about your own age compared to theirs. Try to generate the following conversation:
Hello there! What is your name?-- Emily.
Nice to meet you, Emily. How old are you?-- 23
I'm 25 years old, so I'm 2 years older than you.
Also account for situations where the other person is older or the same age. You will need to use if-statements!
In [ ]:
name = input("Hello there! What is your name? ")
# finish this code
| Topic | Explanation |
|---|---|
quotes |
A string is delimited by single quotes ('...') or double quotes ("...") |
special characters |
Certain special characters can be used, such as "\n" (for newline) and "\t" (for a tab) |
printing special characters |
To print the special characters, they must be preceded by a backslash (\) |
continue on next line |
A backslash (\) at the end of a line is used to continue a string on the next line |
multi-line strings |
A multi-line print statement should be enclosed by three double or three single quotes ("""...""" of '''...''') |
Please run the code snippet below and observe what happens:
In [ ]:
print('hello\n')
print('To print a newline use \\n')
print('She said: \'hello\'')
print('\tThis is indented')
print('This is a very, very, very, very, very, very \
long print statement')
print('''
This is a multi-line print statement
First line
Second line
''')
Now write a Python script that prints the following figure using only one line of code! (so don't use triple quotes)
| | |
@ @
*
|"""|
In [ ]:
# your code here
| Topic | Explanation |
|---|---|
| a = b + c | if b and c are strings: concatenate b and c to form a new string a |
| a = b * c | if b is an integer and c is a string: c is repeated b times to form a new string a |
| a[0] | the first character of string a |
| len(a) | the number of characters in string a |
| min(a) | the smallest element in string a (alphabetically first) |
| max(a) | the largest element in string a (alphabetically last) |
Please run the code snippet below and observe what happens:
In [ ]:
b = 'the'
c = 'cat'
d = ' is on the mat'
a = b + ' ' + c + d
print(a)
a = b * 5
print(a)
print('The first character of', c, 'is' , c[0])
print('The word c has,', len(c) ,'characters')
Now write a program that asks users for their favorite color. Create the following output (assuming "red" is the chosen color). Use "+" and "*". It should work with any color name though.
red red red red red red red red red red
red red
red red
red red red red red red red red red red
In [ ]:
color = input('what is your favorite color? ')
print(color)
print(color)
print(color)
print(color)
In [ ]:
dir(str)
To see the explanation for a method of this class, you can use help(str.method). For example:
In [ ]:
help(str.upper)
In [ ]:
text = """But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born
and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the
truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is
pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are
extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is
pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure.
To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage
from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying
consequences, or one who avoids a pain that produces no resultant pleasure? On the other hand, we denounce with
righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment,
so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs
to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil
and pain."""
# your code here
Have a good look at the internal representation of the string below. Use a combination of string methods (you will need at least 3 different ones and some will have to be used multiple times) in the correct order to remove punctuation and redundant whitespaces, and print each word in lowercase characters on a new line. The result should look like:
the
quick
brown
fox
jumps
etc.
In [ ]:
text = """ The quick, brown fox jumps over a lazy dog.\tDJs flock by when MTV ax quiz prog.
Junk MTV quiz graced by fox whelps.\tBawds jog, flick quartz, vex nymphs.
Waltz, bad nymph, for quick jigs vex!\tFox nymphs grab quick-jived waltz.
Brick quiz whangs jumpy veldt fox. """
print(text)
print()
print(repr(text))
In [ ]:
text = # your code here
print(text)
Write a program that asks a user for a password and checks some simple requirements of a password. If necessary, print out the following warnings (use if-statements):
In [ ]:
# your code here
You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.
In [ ]:
# your code here
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
In [ ]:
# your code here
The required postage for an international parcel delivery service is calculated based on item weight and country of destination:
| Tariff zone | 0 - 2 kg | 2 - 5 kg | 5 - 10 kg | 10 - 20 kg | 20 - 30 kg |
|---|---|---|---|---|---|
| EUR 1 | € 13.00 | € 19.50 | € 25.00 | € 34.00 | € 45.00 |
| EUR 2 | € 18.50 | € 25.00 | € 31.00 | € 40.00 | € 55.00 |
| World | € 24.30 | € 34.30 | € 58.30 | € 105.30 | - |
Ask a user for the weight and zone. Use (nested) if-statements to find the required postage based on these variables. Assign the result to a variable postage and print the result using a full sentence:
The price of sending a [...] kg parcel to the [...] zone is € [...].
In [ ]:
# your code here