How do I make my code loop properly in python?

984 views Asked by At

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.

Same thing with 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. ')
2

There are 2 answers

2
fferri On BEST ANSWER

Alternative way: use a condition in your while loops.

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
salezica On

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.

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