There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:
), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n
never changes, only does the value of num
.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num)
is greater than 0 and if it is, print 'Valid number'
and do break
to stop the loop; if it's not, print 'Invalid number'
(though then the loop doesn't need to be defined by while n < 0:
; rather by while True:
.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.