10  Morning Exercises: Python fundamentals

10.0.1 Exercise 0

  1. Try to run the code below. Why is there no output?
x = 6
apple = "apple"

Answer: Only the output of the last command is printed and the last command is a variable assignment which does not produce any printed output.

  1. Change the code cell in such a way that the variable names and values are printed as output. You can type the variable names in the print statements, but do not type the value.
x = 6
apple = "apple"
print("the value of x is", x)
print("the value of apple is", apple)
the value of x is 6
the value of apple is apple

10.0.2 Exercise 1

  1. Calculate: One plus five and divide the sum by nine amd assign the result of the calculation to a variable.
  2. Test if the result is larger than one. (tip: output of the cell should be True or False)
  3. Round off the result to one decimal. Use the function round. (tip: use ? round or you internet search engine for information about how to use the function)
s = 1+5/9
s > 1
True
round(s, 1)
1.6

10.0.3 Exercise 2

Predict the results of each of the following comparisons first, then run the cell below: (double click this cell to edit)

5 == 5 answer: True, 5 is equal to 5
not 3 > 2 answer: False, not inverts True to False
True == 'True' answer: False, The first True is of type bool and does not equal the second ‘True’ of type string

print(5 == 5)
print(not 3 > 2)
print(True == 'True')
True
False
False

10.0.4 Exercise 3: variables and operators

Evaluate the statements below. What do you think will be the output of python? Do you agree with python?

  • 1 + 1 answer: 2, 1 and 1 are added and the result is printed as output.
  • 1 + True answer: 2, in Python True`` is equal to1`
  • 1 + "one" answer: error, an integer cannot be added to a string
print(1 + 1)
2
print(1 + True)
2
print(1 + "one")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Note, that the boolean variables True and False are turned into numbers when used in calculations. True becomes 1 and False becomes 0.

10.0.5 Exercise 4

Meet Ann, Bob, Chloe, and Dan. 1. Create a list with their names. Save the list as “name”.

  1. How old are Ann, Bob, Chloe, and Dan? You decide! Design a numeric list with their respective ages. Save it as “age”.

  2. What is their average age? (Use the function sum to sum up their cumulative ages, you can use len(age) to get the number of elements in a list)

name = ['Ann', 'Bob', 'Chloe', 'Dan']
age = [25, 28, 36, 30]
print('average age is', sum(age)/len(age))
average age is 29.75

10.0.6 Exercise 5

  1. Return only the first number in the list age.
  2. Return the 2nd and 4th name in your list name.
  3. Return only ages under 30 from your list age.
  4. Return the age of “Chloe” from the list age.
age[0]
25
[name[1], name[3]]
['Bob', 'Dan']
new_age=[]
for a in age:
    if a < 30:
        new_age.append(a)

new_age

# without the bonus:
# for a in age: 
#     if a < 30: 
#         print(a)
[25, 28]
age[name.index("Chloe")]
36

Note, we can only fetch Claire’s age from age since the two lists are sorted accordingly. Dictionaries, see next Section, will give us a better way of mapping from one value to another.

10.0.7 Exercise 6

  • Create a new dictionary that contains the keys: ‘name’, ‘age’ and ‘country’ and their respective values (you can make up the values yourself)..
  • Print the values of the dictionary to the screen
  • Reassign the value of key ‘age’ to 24
  • Print the values of the dictionary to the screen again to see if the value has changed.
my_dict = {'name': 'Jill', 'age': 39, 'country': 'Netherlands'}
my_dict.values()
dict_values(['Jill', 39, 'Netherlands'])
my_dict['age'] = 24
my_dict.values()
dict_values(['Jill', 24, 'Netherlands'])

10.0.8 Exercise 7

Create an if statement that tests whether a number is even or odd, and saves the classification in a variable called number_class.
Hint, you can use the % operator (aka modulo operator). If necessary, you can try the operator to see what it does in the cell below or search the web.

number = 5

if number % 2 == 0:
    number_class = "even"
else:
    number_class = "odd"
    
print(number_class)
odd

10.0.9 Exercise 8

Turn the if statement from the last exercise into a function. Let the user provide the value for number, and return the number_class.

def even_or_odd(number):
    if number % 2 == 0:
        number_class = "even"
    else:
        number_class = "odd"
    return number_class
# Run this code to test your function above
number = 5
print(number, "is", even_or_odd(number))
5 is odd

10.0.10 Exercise 9

Use the function above to determine whether the numbers between 1 and 10 are even or odd.
Hint: the range function might be helpful.

for number in range(1,10,1):
    print(number, "is", even_or_odd(number))
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd