Reputation: 53
I'm really new to Python and I'm mainly just messing around. I'm trying to put together a function that validates a user input (in my case, to check wether the user writes either James or Peter. This is probably a very newbie question, but I was just wondering if my code is a good way to accomplish this function. Thanks for any help.
namelist = "Peter", "James"
def nameinput():
global name
name = raw_input("Write a name. ")
def checkname(x):
while name not in namelist:
print "Try again"
nameinput()
else:
print "Good,", name
checkname(nameinput())
if name == "Peter":
print "This is a text for Peter"
elif name == "James":
print "This is a text for James"
Upvotes: 0
Views: 67
Reputation: 599540
No; there is no reason to use global variables here. Pass data around to the functions that need it.
def nameinput():
return raw_input("Write a name. ")
def checkname(name):
namelist = ["Peter", "James"]
while name not in namelist:
print "Try again"
name = nameinput()
else:
print "Good,", name
return name
name = checkname(nameinput())
Upvotes: 1
Reputation: 641
Using global variables is generally frowned upon (it can really do stupid stuff if you don't always know what you are doing), so don't start doing so that early.
You could easily avoid that by returning the name from nameinput.
Also, you already have the name list. Do the following in the end:
if name in namelist:
print("This is a text for " + name)
Upvotes: 0