2016-01-13 29 views
1

我正在为游戏或其他东西或其他代码编写一个模拟注册页面,在代码结尾处我想确认用户输入的数据是否正确。我通过键入来做到这一点。如何从一开始循环一个程序

#User sign up page. 

#Getting the user's information. 
username = input ("Plese enter your first name here: ") 
userage = input ("Please enter your age here: ") 
userphoneno = input ("Please enter your home or mobile number here: ") 

#Showing the inforamtion. 
print ("\nIs the following correct?\n") 
print ("•Name:",username) 
print ("•Age:",userage) 
print ("•Phone Number:",userphoneno) 

#Confirming the data. 
print ("\nType Y for yes, and N for no. (Non-case sensitive.)") 
answer = input ("• ") 
if answer == 'Y'or'y': 
    print ("Okay, thank you for registering!") 
    break 
else: 
    #Restart from #Getting the user's information.? 

我的问题出现在代码的最后一节。当输入“Y或y”时程序就会正常结束,但如果输入“N或n”,我似乎无法解决如何让用户输入数据。我尝试了一个While循环,我猜是解决方案,但我似乎无法让它正常工作。

任何帮助将不胜感激。谢谢!

+4

向我们展示您尝试的while循环?另外,答案=='Y'or'y''将始终评估为真。看看[这](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values)。 –

回答

1

你应该使用while循环!用一个函数包装处理用户输入的部分,然后如果用户没有回应则继续调用该函数。顺便说一下,您应该使用raw_input而不是input。例如:

#User sign up page. 

#Getting the user's information. 

def get_user_info(): 
    username = raw_input("Plese enter your first name here: ") 
    userage = raw_input("Please enter your age here: ") 
    userphoneno = raw_input("Please enter your home or mobile number here: ") 

    #Showing the inforamtion. 
    print ("\nIs the following correct?\n") 
    print ("Name:",username) 
    print ("Age:",userage) 
    print ("Phone Number:",userphoneno) 
    print ("\nType Y for yes, and N for no. (Non-case sensitive.)") 
    answer = raw_input("") 
    return answer 

answer = get_user_info() 
#Confirming the data. 
while answer not in ['Y', 'y']: 
    answer = get_user_info() 

print ("Okay, thank you for registering!") 
+0

由于OP(原始海报)正在使用Python 3,因此您需要使用'input'而不是'raw_input'。(您可以通过他为每个'print'语句使用的括号来判断,因为省略这些将会打印元组。 ) – mbomb007

+0

或者如果你愿意,你可以在函数get_user_info()中添加while循环来使用递归。 –

+0

'raw_input()'在Python 3中不可用。请更改您的代码以使用'input()',因为海报正在使用Python 3.如果您实际运行了自己的代码,则会看到打印错误if Python 2,或者'raw_input'在Python 3中无效。 – mbomb007

相关问题