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.