2

I am running a code that might get an error, but I want to run it as long as there is no error.

I thought about something like that:

while ValueError:
    try:
        x = int(input("Write a number: "))
    except ValueError:
        x = int(input("You must write a number: "))`
mins
  • 6,478
  • 12
  • 56
  • 75
ron cohen
  • 295
  • 1
  • 3
  • 9

2 Answers2

5

You were quite near

while True:
    try:
        x = int(input("Write a number: "))
        break
    except ValueError:
        print("You must write a number: ")

To know more about exception handling, refer the documentation

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

As an addition to Bhargav's answer, I figured I would mention one other option:

while True:
    try:
        x = int(input("Write a number: "))
    except ValueError:
        print("You must write a number: ")
    else:
        break

The try statement executes. If an exception is thrown, the except block takes over, and it's run. The else block is executed if no exception is thrown. And don't worry, if the except block ever executes, the else block won't be called. :)

Also, you should note that this answer is considered to be more Pythonic, while Bhargav's answer is arguably easier to read and more intuitive.

Zizouz212
  • 4,908
  • 5
  • 42
  • 66