【问题标题】:How do I make my code loop properly in python?如何在 python 中正确地使我的代码循环?
【发布时间】:2015-06-24 23:15:38
【问题描述】:

我的目标是确保当用户在用户名输入中输入数字时,它不应该接受它并让他们重试。

与用户编号相同。当用户输入字母时,应该用另一行提示他们再试一次。

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

我是编码新手,我正试图找出我做错了什么。提前谢谢!

 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. ')

【问题讨论】:

标签: python loops while-loop isnumeric


【解决方案1】:

你永远不会停止循环。有两种方法可以做到这一点:要么更改循环条件(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!')

第二个循环也有同样的问题,解决方法相同,并进行了额外的更正。

【讨论】:

    【解决方案2】:

    替代方法:在 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)
    

    【讨论】:

    • string.isalpha() 在空字符串上的行为如何?大概就好了,不过这不是很清晰的代码
    • str.isalpha()/isnumeric()/isalnum()/isdecimal() 他们都在空字符串上返回False
    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 2022-01-21
    • 2012-01-22
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多