2015-06-24 41 views
-1

我的目标是确保用户在userName输入中键入数字时,它不应该接受它并让它们再次尝试。如何让我的代码在Python中正确循环?

与userNumber相同的东西。当用户输入字母时,应该用另一行提示他们再次尝试。

问题是,当他们输入正确的输入时,程序将继续循环并无限期地列出数字。

我是新来的编码,我试图找出我做错了什么。先谢谢你!

userName = input('Hello there, civilian! What is your name? ') 

while True: 
    if userName.isalpha() == True: 
     print('It is nice to meet you, ' + userName + "! ") 
    else: 
     print('Choose a valid name!') 


userNumber = input('Please pick any number between 3-100. ') 

while True: 
    if userNumber.isnumeric() == True: 
     for i in range(0,int(userNumber) + 1,2): 
      print(i) 
    else: 
     print('Choose a number please! ') 
     userNumber = input('Please pick any number between 3-100. ') 
+1

你应该了解break语句:https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops –

+0

您不需要将布尔值与“True”进行比较。它已经评估为“真”或“假”。 – TigerhawkT3

回答

0

备选方法:在您的while循环中使用条件。

userName = '' 
userNumber = '' 

while not userName.isalpha(): 
    if userName: print('Choose a valid name!') 
    userName = input('Hello there, civilian! What is your name? ') 

print('It is nice to meet you, ' + userName + "! ") 

while not userNumber.isnumeric(): 
    if userNumber: print('Choose a number please! ') 
    userNumber = input('Please pick any number between 3-100. ') 

for i in range(0,int(userNumber) + 1,2): 
    print(i) 
+0

'string.isalpha()'在空字符串上的行为如何?大概就好了,但是这不是很清晰。代码 – slezica

+0

'str.isalpha()'/'isnumeric()'/'isalnum()'/'isdecimal()'它们都在空字符串上返回False。 – fferri

+0

谢谢!这有助于解决我的问题! – Kelvin

4

你永远不会停止循环。有两种方法可以做到这一点:或者改变循环条件(永远为while true循环),或者从内部改变break

在这种情况下,它与break简单:

while True: 
    # The input() call should be inside the loop: 
    userName = input('Hello there, civilian! What is your name? ') 

    if userName.isalpha(): # you don't need `== True` 
     print('It is nice to meet you, ' + userName + "! ") 
     break # this stops the loop 
    else: 
     print('Choose a valid name!') 

第二循环有同样的问题,同样的解决方案和额外的修正。

相关问题