[Tutor] Help with function scoping

Richard Mcewan richmcewan at icloud.com
Wed Mar 22 17:17:43 EDT 2017


Hi

I wonder if you can help. 

I'm confused about how functions should work. Below is some code I write to check my understanding. 

I'm expecting two functions to be defined. Then called. One returns a random number. The other user input (guessing the number). 

I expect the return values to act like variables that I can use in a while loop. 

The programme asks for the user input then crashes. The error report says 'NameError:The name 'userGuess' is not defined. 

My understanding is wrong somewhere. I thought functions would allow me to return values I could use elsewhere without having to define them initially. I.e. Encapsulation. 

I've looked for other examples but get the same issue. I expect a function to return a variable I can use elsewhere. Not sure how to do. In the case below I'm not sure how I can use the work of the function elsewhere. 

Advice welcome. 

Richard 

Using Pythonista App on iOS with Python 2.7 on iPhone 5s

# coding: utf-8
import random

#guess number game

#computer generates random number
def generateNumber():
	computerGuess = int(random.randrange(0,101))
	return computerGuess

#get user
def getUser():
	userGuess = int(input('Guess a number'))
	return userGuess
	
#call for computer and user
generateNumber()
getUser()

#loop to check guess and report
while userGuess != computerGuess:
	if userGuess < computerGuess:
		print('Too low')
		getUser()
	elif userGuess > computerGuess:
		print('Too high')
		getUser()
	elif userGuess > computerGuess:
		print('Correct!')

#Add counter of guess later


Sent from my iPhone


More information about the Tutor mailing list