0

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!

2
  • @Isma I am sorry but I am quite new so if you could demonstrate that it would be awesome! Commented Jul 5, 2018 at 9:03
  • Your try..except splits the entire routine into two separate parts. You want one while with the try..except inside, not as an outer control loop. Commented Jul 5, 2018 at 9:11

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.