简体   繁体   中英

Validating an input with a function in Python

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"

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())

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM