如何从头开始循环程序

时间:2016-01-13 18:34:14

标签: python loops

我正在为游戏或其他东西编写模拟注册页面,在代码的最后我要确认用户输入的数据是否正确。我这样做是打字。

#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循环,我猜测它是解决方案,但我似乎无法让它正常工作。

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

你应该使用while循环!用函数包装处理用户输入的部分,然后在用户响应no时继续调用该函数。顺便说一下,您应该使用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!")
相关问题