Scope exercises

From WLCS

Exercise A

Fix the following buggy code:

# obtain last name from user
def getLastName():
    last_name=raw_input("What's your last name?")

# create a full name from the first and last names
def combineName():
    full_name=first_name+" "+last_name
    print_name()
    
#Print user's name
def print_name():
    print "User's full name:"+full_name
    
first_name=raw_input("What's your first name?")
getLastName()
combineName()
  1. What is the scope of the following variables
    1. last_name
    2. first_name
    3. full_name?
  2. Ensure last_name is transferred from getLastName() to the default scope
  3. What argument needs to be passed to print_name()?
  4. Add a new function that asks "Are you (j)junior, (s)senior or (n) neither?", and determines the correct suffix ("Jr.", "Sr.")
  5. Modify the combineName function so the suffix is added to full_name

Exercise B

Create a new program:

  • Define two variables, 'x' and 'screen_width'
  • Set screen_width to 800
  • Ask the user for a value for 'x'
  • Write a function that performs screen wrapping(as in 'Robot'):
    If the input is greater than screen width, set it to 0
    If the input is less than 0 then set it to the screen width
  • Add code to print 'x' before and after the function is called
  • Test the code with several sample values - make sure it works.
  • Extend the wrapping function so that it also works with the y-coordinate
    • Don't create a second function. Instead work out how to return two variables.