Check user Input is a Number or String in Python
In this lesson, you will learn how to check user input is a number or string in Python. We will also cover how to accept numbers as input from the user. When we say a number, it means it can be integer or float.
Understand user input
Python 3 has a built-in function input() to accept user input. But it doesn’t evaluate the data received from the input() function, i.e., The input() function always converts the user input into a string and then returns it to the calling program.

Check input is a number or a string in Python
Let us understand this with an example.
As you can see, The output shows the type of a variable as a string (str).
Solution: In such a situation, We need to convert user input explicitly to integer and float to check if it’s a number. If the input string is a number, It will get converted to int or float without exception.
Convert string input to int or float to check if it is a number
How to check if the input is a number or string in Python
-
Accept input from a user
Use the input() function to accept input from a user
To check if the input string is an integer number, convert the user input to the integer type using the int() constructor.
To check if the input is a float number, convert the user input to the float type using the float() constructor.
If an input is an integer or float number, it can successfully get converted to int or float type. Else, we can conclude it is a string
Note: If an input is an integer or float number, it can successfully get converted to int or float, and you can conclude that entered input is a number. Otherwise, You get a valueError exception, which means the entered user input is a string.
Program :
- As you can see in the above output, the user has entered 28, and it gets converted into the integer type without exception.
- Also, when the user entered 3.14, and it gets converted into the float type without exception.
- But when the user entered a number with some character in it (28Jessa), Python raised a ValueError exception because it is not int.
Use string isdigit() method to check user input is number or string
Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.
Let’s execute the program to validate this.
Also, If you can check whether the Python variable is a number or string, use the isinstance() function.
Example
Only accept a number as input
Let’s write a simple program in Python to accept only numbers input from the user. The program will stop only when the user enters the number input.
Practice Problem: Check user input is a positive number or negative
Next Steps
Let me know your comments and feedback in the section below.
Also, Solve:
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Проверьте, является ли переменная целым числом или нет в Python
В этом посте мы обсудим, как проверить, является ли переменная целым числом или нет в Python.
1. Использование isinstance() функция
Стандартное решение для проверки, является ли данная переменная целым числом или нет, использует isinstance() функция. Он возвращается True если первый аргумент является экземпляром второго аргумента.
Вы также можете использовать числовые абстрактные базовые классы вместо конкретных классов. Чтобы проверить целочисленное значение, вы можете использовать numbers.Integral Класс Python:
2. Использование float.is_integer() функция
Если вам нужно рассмотреть числа с плавающей запятой со всеми нулями после запятой, рассмотрите возможность использования float.is_integer() функция. Он возвращается True если экземпляр с плавающей запятой конечен с целым значением и False в противном случае.
3. Использование int() функция
Наконец, вы можете использовать конструктор int для проверки целочисленных значений. Функция int(x) преобразует аргумент x до целого числа. Если x уже является целым числом или числом с плавающей запятой с целым значением, то выражение int(x) == x будет соответствовать действительности.
Python Check if a variable is a number
In this Python tutorial, we will discuss Python Check if a variable is a number and also cover the below points:
- How to check if a variable is an integer in Python
- Check if variable is not a number in Python
- Python check if variable is number or string
- How to check if a variable is number or array in Python
- Python check if variable is number or list
- Check if variable is whole number in Python
- Python check if variable is real number
- How to check if variable contains a number in Python
- Python check if variable is between two numbers
Python variable is like a memory location where to store a value. To declare a variable we just have to assign a value to it. You don’t have to give any additional commands unlike any other programming languages like C, C++, Java where you have to give an additional command for declaration and assigning purpose.
Table of Contents
Python Check if a variable is a number
- In this section, we will learn how to check if a variable is a number in Python.
- We can use a method to check if a variable is a number is using a try-except block. In the try block, we can use the given variable to an int or float.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if a variable is a number
Here is the screenshot of following given code

How to check if a variable is an integer in Python
Suppose you have a couple of variables in a program A and B. A has an integer value while B has a decimal value so how will you check whether a is an integer or not and if b is also an integer or not.
- In this section, we will learn how to check if a variable is an integer in Python.
- Now the methods that we are going to use to check if the variable is an integer or not.
- Isinstance method()
- Try-except method()
- Round method()
Isinstance method() is a built-in method in python which returns true when the specified object is an instance of the specified type otherwise it will return false.
Syntax:
Example
Let’s take an example to check if a variabe is an integer.
Here is the screenshot of following given code

- In the Try-except block, we can use the given variable to an int or float.
- we can use a method to check if a variable is an integer is using a try-except block.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if a variable is an integer.
Here is the Screenshot of following given code

Round method in Python returns the nearest integer when no values are passed to the optional digit argument.
Syntax:
Here is the syntax of Round method
Example
Let’s take an example to check if a variable is an integer
Here is the screenshot of following given code

Python check if a variable is not a number
- In this section, we will learn how to check if a variable is not a number in Python.
- we can use a try-except method to check if a variable is not a number is using a try-except block. In the try block, we can use the given variable to an int or float.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if a variable is not a number
Here is the screenshot of following given code

Python check if variable is number or string
- In this section, we will learn how to check if a variable is a number or string in Python.
- We can easily use an isinstance method to check if a variable is a number or string is using an isinstance() method.
- Isinstance method() is a built-in method in python which returns true when the specified object is an instance of the specified type otherwise it will return false.
Syntax:
Example
Let’s take an example to check if a variable is number or string
Here is the Screenshot of following given code

This is how to check if variable is number or string in Python.
Python check if variable is number or array
- In this section, we will learn how to check if a variable is a number or array in Python.
- we can use a try-except method to check if a variable is a number or array is using a try-except block. In the try block, we can use the given variable to an int or float.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if a variable is a number or array
Here is the Screenshot of following given code

This is how to check if variable is number or array in Python.
Python check if variable is number or list
- In this section, we will learn how to check if a variable is a number or a list in Python.
- we can use a try-except method to check if a variable is a number or a list is using a try-except block. In the try block, we can use the given variable to an int or float.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if a variable is a number or list
Here is the Screenshot of following given code

This is how to check if variable is number or list in Python.
Python check if a variable is a whole number
- In this section, we will learn how to check if a variable is a whole number in Python.
- Now the methods that we are going to use to check if the variable is a whole number.
- int() method
- try-except method
int() function is a built up function that will convert any string or float to into a integer form.
Syntax:
Here is the syntax of int() method
Example
Let’s take an example to check if variable is whole number.
Here is the Screenshot of following given code.

- Now another method is the Try-except block, we can use the given variable to an int or float.
- we can use this method to check if a variable is a whole number by using a try-except block.
Syntax:
Here is the syntax of try-except block
Example
Let’s take an example to check if variable is whole number.
Here is the screenshot of following given code.

Python check if variable is real number
- Any number that can be plotted on a number line is called a real number in Python.
- In this section, we will learn how to check if a variable is a real number or not.
- we can use a try-except method to check if a variable is a number or a list is using a try-except block. In the try block, we can use the given variable to an int or float.
Syntax:
Example
Let’s take an example to check if variable is real number or not.
Here is the Screenshot of following given code.

This is how to check if variable is real number in Python.
Python check if variable is between two numbers
- In this section, we will learn how to check if a variable is between two numbers in Python.
- Create a range of integers from start to end. Use keyword integers to check if a variable is between two numbers.
Syntax:
Example
Let’s take an example to check if variable is between two numbers.
Here is the Screenshot of following given code.

This is how to check if variable is between two numbers in Python.
You may like the following Python tutorials:
In this Python tutorial, we learned how to check if a variable is a number in Python and the below examples:
- Python Check if a variable is a number
- Python check if a variable is an integer
- Python check if a variable is not a number
- Python check if a variable is number or string
- Python check if a variable is number or array
- Python check if a variable is number or list
- Python check if a variable is whole number
- Python check if a variable is real number
- Python check if a variable is between two numbers

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
How can I check if string input is a number?
How do I check if a user’s string input is a number (e.g., -1 , 0 , 1 , etc.)?
The above won’t work since input always returns a string.

30 Answers 30
Simply try converting it to an int and then bailing out if it doesn’t work.
See Handling Exceptions in the official tutorial.

Apparently this will not work for negative values, but it will for positive numbers.

The method isnumeric() will do the job:
isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.
So negative numbers are not accepted.
For Python 3 the following will work.
EDITED: You could also use this below code to find out if its a number or also a negative
you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers 🙂 . let me know if anythings wrong in the given code.
If you specifically need an int or float, you could try "is not int" or "is not float":
If you only need to work with ints, then the most elegant solution I’ve seen is the ".isdigit()" method:

Works fine for check if an input is a positive Integer AND in a specific range
I would recommend this, @karthik27, for negative numbers
Then do whatever you want with that regular expression, match(), findall() etc
natural: [0, 1, 2 . ∞]
integer: [-∞, . -2, -1, 0, 1, 2, ∞]
float: [-∞, . -2, -1.0. 1, -1, -0.0. 1, 0, 0.0. 1, . 1, 1.0. 1, . ∞]

The most elegant solutions would be the already proposed,
Unfortunately, it doesn’t work neither for negative integers nor for general float values of a. If your point is to check if ‘a’ is a generic number beyond integers, I’d suggest the following one, which works for every kind of float and integer :). Here is the test:

This solution will accept only integers and nothing but integers.

This works with any number, including a fraction:
You can use the isdigit() method for strings. In this case, as you said the input is always a string:

Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):
This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)
Here is a simple function that checks input for INT and RANGE. Here, returns ‘True’ if input is integer between 1-100, ‘False’ otherwise
If you wanted to evaluate floats, and you wanted to accept NaN s as input but not other strings like ‘abc’ , you could do the following:
I’ve been using a different approach I thought I’d share. Start with creating a valid range:
Now ask for a number and if not in list continue asking:
Lastly convert to int (which will work because list only contains integers as strings:
This makes a loop to check whether input is an integer or not, result would look like below:
I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.
This was the solution that ended up working well for me to force an answer I wanted:
I would get exceptions before even reaching the try: statement when I used
and the user entered «J» or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.

This checks if the string has only numbers in it and has at least a length of 1. However, if you try isnumeric with a string with a negative number in it, isnumeric will return False .
Now this is a solution that works for both negative and positive numbers
Looks like there’s so far only two answers that handle negatives and decimals (the try. except answer and the regex one?). Found a third answer somewhere a while back somewhere (tried searching for it, but no success) that uses explicit direct checking of each character rather than a full regex.
Looks like it is still quite a lot slower than the try/exceptions method, but if you don’t want to mess with those, some use cases may be better compared to regex when doing heavy usage, particularly if some numbers are short/non-negative:
On Python 3.10 on Windows shows representative results for me:
Explicitly check each character:
A lot slower than the try/except:
But a fair bit quicker than regex, unless you have an extremely long string?
(In case you’re using it already). and then:
None are close to the simplest isdecimal, but that of course won’t catch the negatives.