2

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")

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.