Reputation: 163
So I have a condition for accepting only a negative value for a variable and it should also not raise a value error. My code goes like this ->
try:
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x = int(input("Enter -ve value : " )
except ValueError:
print("Error wrong value!")
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x=int(input("Enter -ve value : " )
The only problem with this approach is that, suppose I press enter without entering a value for the first time. It takes me to the "except" condition and it works fine but if I enter a blank value again my code stops because of value error. How do I stop this from happening? Is there a more efficient way of writing this code without importing any modules?
Thank you for your time and efforts! I wrote this question on the mobile app so sorry if it causes any inconvenience!
Upvotes: 0
Views: 41
Reputation: 3336
You could try it like this:
x = 0
while x >= 0:
try:
x = int(input("Enter -ve value : "))
except ValueError:
print("Error wrong value!")
x = 0
This will achieve what you are asking for in that it will keep prompting you to enter a number while x >= 0
and will also ensure the exception handling is always carried out on each input too.
Upvotes: 4