Trouble with prompting the user for input until it is correct in a while loop

29 views Asked by At
if num < 0:
    input('Only  nonnegative intergervalues allowed, try again: ')
elif num == 0:
    print('The factorial of 0 = 1')

while num > 1:
    factor = factor * num
    num = num -1
else:
    num = int(input('Only  nonnegative intergervalues allowed, try again: '))

This is what I have. I'm only trying to use the while loop for the program. It prompts the user twice if the integer is negative and then the loop breaks. I need the loop to keep prompting the user until correct input is given. I'm not sure where the error is. Do I need a nested while loop or is the problem with the else statement?

I've tried another while loop underneath the original loop but unsure if I had it done correctly. Also tried moving some things around?

2

There are 2 answers

2
Grismar On

Part of the issue is with your interpretation of the else on the while loop. It will only ever get executed once, as the while loops exits without a break. I think your expectation was that after the else block, the while condition would be evaluated again. This is not the case, use an if statement in the while loop instead.

You probably wanted something like:

# since Python does not have a repeat .. until loop, while True with a break works
while True:
    num = int(input('Enter a non-negative integer value: '))
    if num < 0:
        input('Only non-negative integer values allowed, try again: ')
    else:
        break

factorial = 1
x = num  # save num to print later, work with x to compute factorial

while x > 0:
    factorial = factorial * x
    x = x - 1

print(f'The factorial of {num} is: {factorial}')

The else on a while loop can be useful, if you need to do something only if the loop completes without a break. For example:

total = 0
while total <= 10:
    s = input(f'Total is {total}, add how much? ("x" to stop): ')
    if s == 'x':
        break
    total = total + int(s)
else:
    print(f'You reached a total over 10 of {total}')

A few notes on your code:

  • the first part reads text input into num, but doesn't do anything with it. You probably left some of your code out, as num isn't defined before the if statement.
  • the second part assumes num has an int value, because that's what it compares it with, but at that point the value would be a str.
  • the else part of the while would always execute if num were a positive integer, but that's not the behaviour you want - however, if num were negative, it would never be reached, since that's not what the else on a while is for.

On a personal note, I don't like the fact that the else keyword was reused on for and while in Python. Something like after would have made more sense. But programming languages like to keep the number of keywords to a minimum, and else was reused here, leading to the confusion you had - which makes sense when first learning the language.

0
Suramuthu R On
# The external loop if input is invalid
i = 0
while i < 5:
    
    # If it is 5th attempt, error message
    if i == 4:
        print('Sorry, The maximum number of attempts exceeded')
    
    #Upto 5 times of invalid input, takes another input
    num = int(input())

    #If the input is valid
    if num > 0:
        r = 1
        while num >= 1:
            r = r * num
            num = num - 1
        print(r)
        break    
    else :
        print('The number can not be zero or negative')
    i += 1