Reputation: 23
In my program, I want to take in an input which should be a number.If the user inputs a string, however, the program returns an exception.I want the program set in such a way that the input is converted to int and then if the string is anything other than an int the program prints that "Stop writing please".Like for example:
x=input("Enter a number")
if int(x)=?: #This line should check whether the integer conversion is possible
print("YES")
else #This line should execute if the above conversion couldn't take place
print("Stop writing stuff")
Upvotes: 2
Views: 59
Reputation: 1681
You'll need to use try-except blocks:
x=input("Enter a number")
try:
x = int(x) # If the int conversion fails, the program jumps to the exception
print("YES") # In that case, this line will not be reached
except ValueError:
print("Stop writing stuff")
Upvotes: 2
Reputation: 192
You can simply use a try-except block to catch the exceptional case, and inside there, print your statement. Something like this:
x=input("Enter a number")
try:
x=int(x)
print("YES")
except:
print("Stop writing stuff")
Upvotes: 0