2016-01-16 91 views
0
def check(x): 
    global username 
    while True: 
     if x.isalpha(): 
      break 
     else: 
      x = input("Please type your name with letters only!: ") 
      continue 

username = input("? ") 
check(username) 
print (username) 

我有这个代码的问题,如果第一个用户输入不是alpha,程序将再次询问用户的输入,直到用户只使用字母输入正确的输入。但是,当我在(用户名)变量中打印值后,即使输入错误,他也会得到第一个用户的输入,并且他已经在函数check()中更改了它。我试图使用许多解决方案,但它没有奏效。我认为这是一个与全局变量有关的问题,尽管我已经将(用户名)变量设置为全局变量。如果有人对此问题有任何解决方法,请帮助我。更改参数(x)函数内的全局变量的值:

+2

在功能末尾输入'username = x' – tdelaney

+0

谢谢您的解答和快速回复。如果我不想为(用户名)变量使用其他变量的函数,该怎么办?例如,我想在(SureName)变量上应用相同的函数。 –

+0

可能的重复[如何通过引用传递变量?](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Barmar

回答

0

是的,因为一旦你进入循环,你将变量x设置为输入...但是x永远不会被重新访问。修订:

def check(): 
    global username 
    while True: 
     if username.isalpha(): 
      break 
     else: 
      username = input("Please type your name with letters only!: ") 
username = input("? ") 
check() 
print (username) 

另外一个稍差令人费解的例子,没有必要在这里全局:

def get_username(): 
    username = input("? ") 
    while not username.isalpha(): 
     username = input("Please type your name with letters only!: ") 
    return username 
print (get_username()) 

,除非这是专门为全局的做法,我会避免他们不惜一切代价。你应该总是使用你的变量的最小必要范围,这是很好的卫生。响应您的评论

更广义的输入功能:

def get_input(inputName): 
    '''Takes the name of the input value and requests it from the user, only 
     allowing alpha characters.''' 
    user_input = input("Please enter your {} ".format(inputName)) 
    while not user_input.isalpha(): 
     user_input = input("Please type your {} with letters only!: ". 
      format(inputName)) 
    return user_input 
username = get_input("Username") 
surname = get_input("Last Name") 
print(username, surname) 
+0

感谢您的解决方案并快速回复。如果我不想为(用户名)变量使用其他变量的函数,该怎么办?例如,我想在(SureName)变量上应用相同的函数。 –

+0

谢谢。最后的解决方案是我正在寻找的解决方案。我只需要了解它是如何工作的。 –

+0

'get_input()'接受你想要的东西的名字,例如“用户名”或“姓氏”,然后询问用户输入。虽然输入不是全部的字母,但它会一直询问,直到它得到一个全是字母的输入。然后它返回输入的值。这里不需要使用全局变量。我也改变了input()到raw_input(),这就是你想要的。 – ktbiz

0

的问题是你通过“用户名”的价值,但对待它就像你被引用传递它。

这是我的代码。 :)我希望它有帮助。

def check(x): 
    while x.isalpha() is not True: 
     x = raw_input("Please type your name with letters only!: ") 
    return x 

username = raw_input("Please type your name: ") 
username = check(username) 
print ("Your name is: " + username) 

,如果你确实需要使用全局变量,你不需要把它传递给函数(我该使用Python 2.7,但它应该与Python 3工作写)。

def check(): 
    global username 
    while username.isalpha() is not True: 
     username = raw_input("Please type your name with letters only!: ") 

username = raw_input("Please type your name: ") 
check() 
print ("Your name is: " + username) 
+0

谢谢你的代码正在工作。但我不得不改变raw_input输入。我不知道为什么python 3不认识它。 –