0

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"
1
  • Some minor comments, have you thought about cases. Additionally to prevent having to type the name in the if construction you can consider looping over namelist and printing the element if it matches the input. Commented Jan 27, 2016 at 9:17

2 Answers 2

1

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())
Sign up to request clarification or add additional context in comments.

5 Comments

Isn't namelist still global?
Yes, but that's less objectionable because it's not being modified.
Agreed, I would also be tempted to just pass the input function rather than making the call. Calling nameinput() in 2 different parts is icky.
There is a syntax there. You forgot brackets 'namelist =["Peter", "James"]'
I would say to remove the name parameter from checkname() and just do a standard while True: with return to end it. And then rename checkname to getname. nameinput() doesn't seem like it's helping much, either, as it just wraps a single function call.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.