Assignment 1: Calculation, Strings, Boolean Expressions and Conditions

Due: Friday the 2nd of November 2018 at 23:59

  • Please name your notebook with the following naming convention: ASSIGNMENT_1_FIRSTNAME_LASTNAME.ipynb
  • Please submit your assignment using this google form
  • If you have questions about this topic, please refer to the forum on the Canvas site.

In this block, we covered the following chapters:

  • Chapter 1 - Getting Started with Variables and Values
  • Chapter 2 - Basic Data Types (Integers and Floats)
  • Chapter 3 - Strings
  • Chapter 4 - Boolean Expressions and Conditions

In this assignment, you will be asked to show what you have learned from the topics above!

Exercise 1: Calculation

1a. Average

Define three variables var1, var2 and var3. Calculate the average of these variables and assign it to the variable average. Print the outcome of your program as follows (use casting or an f-string):

The average of [...], [...] and [...] is: [...]


In [ ]:
# average code

1b. Book prices

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

1c. The modulus operator

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:

  1. Convert the amount (11.56) into cents (1156).
  2. First get the amount of cents that you would get after subtracting the maximum amount of dollars (100 cents) using the modulus operator (56 cents).
  3. Then subtract the remainder (56 cents) from the total amount of cents (1156 cents) and divide this by 100 to find the number of dollars.
  4. Use the modulus operator again to find out the remainder after subtracting the maximum amount of quarters (6 cents).
  5. Subtract this remainder (6 cents) from the previous remainder (56 cents) and divide this by 25 to find out the number of quarters.
  6. Follow the same steps for the dimes, nickels and pennies.
  7. Display the result for your cashier! (the amount of dollars, quarters, dimes, nickels and pennies that (s)he would have to give back)`

In [ ]:
# cashier code

Exercise 2: Printing and user input

2a. Difference between "," and "+"

What is the difference between using + and , in a print statement? Illustrate by using both in each of the following:

  • calling the print() fuction with multiple strings
  • printing combinations of strings and integers
  • concatenating multiple strings and assign to one single variable
  • concatenating strings and integers and assign to one single variable

In [ ]:


In [ ]:


In [ ]:


In [ ]:

2b. Small Talk

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

Exercise 3: String Art

3a. Drawing figures

We start with some repetition of the theory about strings:

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

3b. Colors

We start again with some repetition of the theory:

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)

Exercise 4: String methods

Remember that you can see all methods of the class str by using dir(). You can ignore all methods that start with one or two underscores.


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)

4a. Counting vowels

Count how many of each vowel (a,e,i,o,u) there are in the text string in the next cell, and use the appropriate string method to print the count for each vowel with a single formatted string. Remember that vowels can be both lower and uppercase.


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

4b. Printing the lexicon

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)

4c. Passwords

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

  1. Your password should contain at least 6 characters.
  2. Your password should contain no more than 12 characters.
  3. Your password only contains alphabetic characters! Please also use digits and/or special characters.
  4. Your password only contains digits! Please also use alphabetic and/or special characters.
  5. Your password should contain at least one special character.
  6. Your password contains only lowercase letters! Please also use uppercase letters.
  7. Your password contains only uppercase letters! Please also use lowercase letters.

In [ ]:
# your code here

Exercise 5: Boolean Logic and Conditions

5a. Speeding

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

5b. Alarm clock

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

5c. Parcel delivery

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