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?
Part of the issue is with your interpretation of the
elseon thewhileloop. It will only ever get executed once, as the while loops exits without abreak. I think your expectation was that after the else block, the while condition would be evaluated again. This is not the case, use anifstatement in the while loop instead.You probably wanted something like:
The
elseon awhileloop can be useful, if you need to do something only if the loop completes without a break. For example:A few notes on your code:
num, but doesn't do anything with it. You probably left some of your code out, asnumisn't defined before theifstatement.numhas anintvalue, because that's what it compares it with, but at that point the value would be astr.elsepart of thewhilewould always execute ifnumwere a positive integer, but that's not the behaviour you want - however, ifnumwere negative, it would never be reached, since that's not what theelseon awhileis for.On a personal note, I don't like the fact that the
elsekeyword was reused onforandwhilein Python. Something likeafterwould have made more sense. But programming languages like to keep the number of keywords to a minimum, andelsewas reused here, leading to the confusion you had - which makes sense when first learning the language.