PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Check user Input is a Number or String in Python

Check user Input is a Number or String in Python

Updated on: April 24, 2021 | 26 Comments

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.

python check input is a number or a string
Check input is a number or a string in Python

Let us understand this with an example.

number1 = input("Enter number and hit enter ")
print("Printing type of input value")
print("type of number ", type(number1))
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'

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

  1. Accept input from a user

    Use the input() function to accept input from a user

  2. Convert input to integer number

    To check if the input string is an integer number, convert the user input to the integer type using the int() constructor.

  3. Convert input to float number

    To check if the input is a float number, convert the user input to the float type using the float() constructor.

  4. Validate the result

    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 :

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
Output

Enter your Age 28
Input is an integer number. Number =  28

Enter any number 3.14
Input is a float  number. Number =  3.14

Enter the last number 28Jessa
No.. input is not a number. It's a string
  • 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.

def check_is_digit(input_str):
    if input_str.strip().isdigit():
        print("User input is Number")
    else:
        print("User input is string")


num1 = input("Enter number and hit enter")
check_is_digit(num1)

num2 = input("Enter number and hit enter")
check_is_digit(num2)
Output

Enter number and hit enter 45
User input is Number

Enter number and hit enter 45Jessa
User input is string

Also, If you can check whether the Python variable is a number or string, use the isinstance() function.

Example

num = 25.75
print(isinstance(num, (int, float)))
# Output True

num = '28Jessa'
print(isinstance(num, (int, float)))
# Output False

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.

while True:
    num = input("Please enter a number ")
    try:
        val = int(num)
        print("Input is an integer number.")
        print("Input number is: ", val)
        break;
    except ValueError:
        try:
            float(num)
            print("Input is an float number.")
            print("Input number is: ", val)
            break;
        except ValueError:
            print("This is not a number. Please enter a valid number")
Output

Please enter a number 28Jessa
This is not a number. Please enter a valid number

Please enter a number 28
Input is an integer number.
Input number is:  28

Practice Problem: Check user input is a positive number or negative

Show Solution
user_number = input("Enter your number ")

print("\n")
try:
    val = int(user_number)
    if val > 0:
        print("User number is positive ")
    else:
        print("User number is negative ")
except ValueError:
    print("No.. input string is not a number. It's a string")

Next Steps

Let me know your comments and feedback in the section below.

Also, Solve:

  • Python input and output exercise
  • Python input and output quiz
  • Python exercise for beginners
  • Python Quiz for beginners

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

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 Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com