2.1. Exercises

Questions on Scoping

def name_initials(first_name, last_name, year_of_birth = None):
    if year_of_birth is not None: 
        initials = first_name[0].upper() + middle_name[0].upper() + str(year_of_birth)
    else:
        initials = first_name[0].upper() + last_name[0].upper()
    return initials

Default Arguments

Given the function below:

def employee_wage(employee_id, position, experience = 3):
    if position == "doctor": 
        wage = 150000
    elif position == "teacher":
        wage = 60000
    elif position == "lawyer":
        wage = 100000
    elif position == "server":
        wage = 50000
    else: 
        wage = 70000
    return wage * (1 + (0.1 * experience)) 
menu_item_id = 42
menu_item_name = "Green Curry"
spice_level = "Medium"
meat = "Tofu"
rice = True

thai_food(menu_item_id, menu_item_name, spice_level, meat, rice)

Default Argument Practice

Instructions:
Running a coding exercise for the first time could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.

Make sure you remove the hash (#) symbol in the coding portions of this question. We have commented them so that the line won’t execute and you can test your code after each step.

Weight and mass are 2 very different measurements, although they are used interchangeably in everyday conversations. Mass is defined by NASA as the amount of matter in an object, whereas, weight is defined as the vertical force exerted by a mass as a result of gravity (with units of Newtons). The function earth_weight() converts an object’s mass to Weight by multiplying it by the gravitational force acting on it. On Earth, the gravitational force is measured as 9.8 m/s2.

We want to make a more versatile function by having the ability to calculate the Weight of any object on any particular planet and not just Earth. Redefine the function earth_weight() to take an argument with a default gravitational force of 9.8.

Tasks:

  • Create a new function named mass_to_weight and give it an additional argument named g, which has a default value of 9.8.
  • Test your new function by converting the mass of 76 kg to weight on Earth and save the results in an object named earth_weight.
  • Test your function again but this time, calculate the weight of the 76 kg object on the moon using a gravitational force of 1.62 m/s2 and save your function call to an object named moon_weight.
Hint 1
  • Are you putting g=9.8 inside the function named mass_to_weight?
  • Are you calling mass_to_weight(76) and saving it in an object named earth_weight?
  • Are you calling mass_to_weight(76, 1.62) and saving it in an object named moon_weight?
Fully worked solution: