Home > Net >  how do I separate an integer from a string
how do I separate an integer from a string

Time:01-21

I’m trying to make a calculator without any errors.

When a , b and c gets a input it is supposed to calculate the answer and print it

But when a or b is not an integer then it is supposed say “ the first input and the second input needs to be a number”

a image of the code

Although a and b were a integer it still responded with “the first input and the second input needs to be a number”

CodePudding user response:

use isdigit() method to check whether it is a number or not

On your code:-

a = input()
if a.isdigit():

However, if you want to take the user's input as an integer directly and you expect the input to be a number, then it would be more efficient to use the int() function. This function will try to convert the input to an integer, and if it is not a number, it will raise a ValueError exception which you can catch and handle as appropriate.

try:
    a = int(input("Enter a number: "))
    print("The number you entered is: ", a)
except ValueError:
    print("Invalid input, please enter a number.")
  • Related