简体   繁体   English

如何使我的代码在python中正确循环?

[英]How do I make my code loop properly in python?

My goal is to make sure when the user types in numbers in the userName input, then it should not accept it and make them try again. 我的目标是确保当用户在userName输入中键入数字时,它不应该接受它并使他们再试一次。

Same thing with userNumber. 与userNumber相同。 When a user types in letters, they should be prompted with another line telling them to try again. 当用户输入字母时,应该用另一行提示他们再输入一次。

The problem is that when they do type in the correct input, the program will continue looping and listing the numbers indefinitely. 问题在于,当他们输入正确的输入时,程序将继续循环并无限期地列出数字。

I'm new to coding, and I'm trying to figure out what I'm doing wrong. 我是编码的新手,我试图弄清楚自己在做错什么。 Thank you in advance! 先感谢您!

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

You never stop the loop. 您永远不会停止循环。 There's two ways to do this: either change the loop condition ( while true loops forever), or break out from within. 有两种方法可以执行此操作:更改循环条件(永远为while true循环),或从内部break

In this case, it's easier with 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!')

The second loop has the same problem, with the same solution and additional corrections. 第二个循环具有相同的问题,具有相同的解决方案和其他更正。

Alternative way: use a condition in your while loops. 另一种方法:在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM