Home > Software design >  Python cannot ignore str when input is int()
Python cannot ignore str when input is int()

Time:09-23

SO I have a program where the input is in an int, but when the user enters a str, the program crashes. I want the program to ignore any str that it can't convert to an int. I tried declaring a variable that said type(input). Then, I added an if statement:

if (variable) == str:
  print(oops)

Remember I declared the input as an int. So I don't know. Thank you.

CodePudding user response:

You can use exceptions for this. You get a Value Error when you try to convert a string input to int. By enclosing it in a try clause here, it is telling that if a Value Error arises, you can ignore it. For now I've used the pass statement, but if there's something else you want to do if the input is a string, you can add it there.

try:
    x = input()
    value = int(x)
    print(value)
except ValueError:
    pass

CodePudding user response:

You can use try-except to handle the case.

try:
    value = int(input())
except ValueError:
    print("Input is not an int type")
    pass
  
    

CodePudding user response:

In python you can call isinstance() on the variable passing the datatype you want to check for-

sent = 'your_string'
num = 24 
                                                                                      
isinstance(sent, int) # returns False
isinstance(num, int) # returns True 
isinstance(sent, str) # returns True 
isinstance(num, str) # returns False                                                                                                                                                                                                                           

Applicable with other data types too!

So a simple-

if not isinstance(str, int):
    print('Only integer values accepted')

CodePudding user response:

if my_input.isdigit():
    int(my_input)
    # your code goes here
else:
    print('oops')
    exit() # maybe you like to exit

CodePudding user response:

You could do something like

input_number = input("Enter your number")
if type(eval(input_number)) == int:
    #Do stuff
else:
    print('Sorry that is an invalid input')

I also noticed you said

Remeber I declared the input as an int

Python is not statically typed, so you don't have to declare a variable as a certain data type, and along with that even if you do, their type can still be changed.

CodePudding user response:

You can use str.isnumeric() to check if input is of int type or not. THis is better than using try..except

input_number = input("enter a number: ")
if input_number.isnumeric():
      input_number = int(input_number)
      # do magic
  • Related