Scope exercises

From WLCS
Revision as of 22:02, 27 February 2011 by Admin (talk | contribs) (Created page with "''Variable scope'' --Exercise A-- Copy the following code: <syntaxhighlight lang="Python"> # obtain last name from user def getLastName(): last_name=raw_input("What's your ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Variable scope

--Exercise A-- Copy the following 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 'x'
  • Write a function that performs the screen wrapping you created 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
  • Extend the wrapping function so that it also works with the y-coordinate
  • How can we return two variables (x and y co-ordinates)?