1.1. Exercises

Questions on Scoping

toy = "ball"

def playtime():
    toy = "truck"
    return toy 

toy
toy = "ball"

def playtime():
    toy = "truck"
    return toy 

playtime()
def playtime():
    toy = "truck"
    return toy 

toy

Side Effects

toy = "ball"

def playtime():
    toy = "truck"
    print(toy) 

playtime()

toy = "ball"

def playtime():
    toy = "truck"
    return toy 

playtime()

Writing Functions Without Side Effects

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.

The function kg_to_lb() is used to convert a list of elements with kg units into a list of elements with lbs units. Unfortunate this function includes a side effect that edits one of the global variables.

Tasks:

  • Write a new function named better_kg_to_lb that no longer contains a side effect.
  • Test your new function on the weight_kg list and save the results in an object named weight_lb_again.
Hint 1
  • Are you putting weight_lb inside the function now?
  • Are you returning weight_lb?
Fully worked solution: