0

I'm really new to python and I'm trying to make an if else statement that can only take integers. I'm trying to make something like this:

num = (input("Enter a number:"))
if (num is an int):
   num = num*2
elif (num is a str):
   print("please enter a number")
Sociopath
  • 13,068
  • 19
  • 47
  • 75
  • num1 will always be a string, python3 input is similar to raw_input from python2. You can either try to convert it to an int and manage the exception, or you can check if the string is a valid integer string. – matt Oct 10 '19 at 12:28
  • Possible duplicate of [What is the best (idiomatic) way to check the type of a Python variable?](https://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable) – Sayse Oct 10 '19 at 12:31

2 Answers2

0

You need to do this.

isinstance(<var>, int)

unless you are in Python 2.x in which case you want:

isinstance(<var>, (int, long))

Also, keep in mind that your code will always recive a string because the input function recives the keyboard input as a string.

Josep Bové
  • 626
  • 1
  • 8
  • 22
0

By default input() takes argument as str.

To convert it into int you can do

num1 = int(input("Enter a number:"))

If it is not number above code will throw an error.

ValueError: invalid literal for int() with base 10: 'abc'

To overcome this you can use try-except (Exception handling)

try:
    num1 = int(input("Enter a number:"))
    num1 = num1*2
except:
    print("please enter a number")
Sociopath
  • 13,068
  • 19
  • 47
  • 75