PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes ▼
    • Python Quizzes
    • Java MCQ Quizzes
  • Online Compilers▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
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 | 27 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))Code language: Python (python)
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)Code language: Python (python)
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)
Code language: Python (python)
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 FalseCode language: Python (python)

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")
Code language: Python (python)
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")Code language: Python (python)

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

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. mohamed says

    November 19, 2023 at 2:03 pm

    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)

    I appreciated your effort for this excellent website, and thanks allot.

    I think about last inputs you mean(input3)
    input3= input(“Enter the last number “)
    check_user_input(input3)

    Reply
  2. KRISHNENDU DUTTA says

    December 14, 2022 at 6:59 am

    in the check_user_input function, if I enter any float value, then why it is not converted into an integer when “int(input)” is used………………….
    please explain
    I am new to python, so I am confused because I learned that if int/float/str is used, it will convert the value into integer/float/string if possible.
    In the case of float value, it can be converted to an integer, but in this case, it is not converted into an integer …………
    so I am really confused; please help

    Reply
  3. Hashini Madushani says

    August 20, 2022 at 6:50 pm

    Create a python program to input any number through the keyboard and display (print) the number. how to create this

    Reply
  4. shiva says

    January 26, 2022 at 6:55 pm

    #Write Python program which error checks if the user enters a string or not
    try:
        string=input("enter the data " )
        print("data contains string")
    except valueerror:
        print("data cannot contains string")
    print("program ends")

    # this program is not executing , can anybody correct this one

    Reply
    • Arthur says

      December 8, 2022 at 4:53 pm

      Hi, Shiva. I’m no expert and am also learning. But I can see the following problem: any value can be a string. If you type “123” in an input(), it will not consider it as a string.

      Now, if you try something like:

      try:
      number=int(input("enter the data: " ))
      print("data contains an integer")
      except ValueError:
      print("data does not contain an integer")
      print("program ends")

      You may get the expected error. Note the appropriate typing of “ValueError”, not “valueerror” (Python diferentiates that). Try using a IDE, such as VSCode, to get fast feedback for small typing errors like that.

      Reply
  5. aURa says

    September 29, 2021 at 6:18 pm

    VERY nice. Thanks!

    Reply
  6. Bugha says

    August 2, 2021 at 8:39 pm

    Can you please suggest a youtube video on how to make a python game????

    Reply
  7. joy says

    June 14, 2021 at 8:40 pm

    How about this what is the input and output. can you help me? I just want to know how?

    enter your age 60
    input is an integer number, number = 60
    enter any number Philippines100
    No.. input is not a number. it’s a string
    enter the last number 52
    input is an integer number. number = 52

    Reply
    • daocanon says

      November 12, 2021 at 10:15 am

      while True:
      
      	age = input("enter your age :")
      
      	try:
      
      		val = int(age)
      		print("input is an integer number","age =",age)
      		break;
      
      	except ValueError :
      		print("No.. input is not a number. it’s a string")
      Reply
  8. Sam williams says

    May 2, 2021 at 11:12 pm

    Hello, I’m working on a particular project in python and I tried looking at this lesson, but I can’t seem to find a way to apply it to my situation. I thought maybe you might know?

    Program’s current objective: I need to be able to ask the user to input ‘Integer’ values for the efficiency of the vehicles rating. I also want the program to not crash if the user puts an invalid value. i.e. floating point or string value. Although I can’t seem to be able to get the program to re-ask the question until it achieves a valid answer. Then will carry on the operations from there.

    def main(): 
    
    	# This varible holds the users inputed name. 
    	Name = input("Hello, what is your name?")  
    	
    	# This list holds the cars that will be checked out. 
    	Cars = ["Car A", "Car B", "Car C", "Car D", "Car E"]
    	
    	# This list holds the percentage of efficiency values of Cars A - E. 
    	# Which will eventually delete all but the highest value at the end of the program
    	Cancel_Cars = [] 
    	
    	# We first need to establish the percentage value of efficiency for the cars. 
    	for Car_num in range (0, len(Cars)): 
    	
    		# Asks user for the first time to enter an integer value for the vehicles efficiency value.
    		try: 
    			
    			Cancel_Cars.append(int(input("Hello " + Name + ", we need you to input the efficency value of " + Cars[Car_num] + ". (PLEASE ENTER INTEGER VALUE)") ))
    		
    		# If the user enters the incorrect value the first time. The program will re-ask the question here.
    		except ValueError:  
    			
    			Cancel_Cars.append(int(input("You did not enter a valid value, please try again and enter a valid value for " + Cars[Car_num] + "."))) 		
    			
    			
    	#THIS CODE UNDER HERE IS TO TRANSVERSE THROUGH THE LOOP 
    	for n in range(0, len(Cancel_Cars)): 
    		print(str(Cancel_Cars[n]))
    
    main()
    Reply
    • Dobby says

      September 9, 2021 at 6:27 pm

      Please check this code:

      
      val = ''
      while type(val) != int:
          val = input("Please enter an integer value: ")
          try:
              val = int(val)
          except ValueError:
              print("No, this is not an integer value")
      
      print("Here is the integer value: ", val)

      I think this should solve your problem.

      Reply
  9. vickers says

    July 3, 2020 at 3:47 am

    Thank you very much this saved my game project 🙂

    Reply
    • Vishal says

      July 3, 2020 at 10:48 am

      You are welcome.

      Reply
  10. im helpful says

    June 12, 2020 at 7:47 am

    
    print("Press 1 to convert miles to KM")
       print("Press 2 to convert KM to miles")
       print("Press 3 to convert fahrenheit to celsuis")
       print("Press 4 to convert celsuis to fahrenheit")
       print("Press 5 to leave program")
       equation = input ("which equation would you like? ")
    
            
       if equation =="5":
           break;
       elif equation == "1":
            num = int(input("enter a number "))
            ans = num * 1.60934;
            print("Km: " + str(ans));
       elif equation == "2":
            num = int(input("enter a number "))
            ans = num / 1.60934;
            print("Miles: " + str(ans));
       elif equation == "3":
            num = int(input("enter a number "))
            ans = (num - 32) * 5 / 9;
            print("Celsuis: " + str(ans));
       elif equation == "4":
            num = int(input("enter a number "))
            ans = num / 5 * 9 + 32;
            print("Fahrenheit: " + str(ans));
    
    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")
    
    Reply
  11. Artur says

    April 17, 2020 at 3:10 pm

    Shouldn’t there be a:

    except ValueError:
        try:
          val = float(num)
          print("Input is an float number.")
          print("Input number is: ", val)
    Reply
    • im says

      April 30, 2020 at 3:53 pm

      yes, propably a miss

      Reply
  12. Mihkel says

    April 9, 2020 at 11:43 am

    Thank you so much. Great help!

    Reply
    • Vishal says

      April 10, 2020 at 3:56 pm

      You’re welcome

      Reply
  13. aya farag says

    December 3, 2019 at 1:17 am

    #Write a Python program to check a string represent an integer or not.

    s =input('enter a value : ')
    print(type(s))
    if type(s)==str:
        print(s,"The string is an integer")
    else:
        print( s,"The string is not an integer")
    

    why my code print always the two massage

    Reply
    • Vishal says

      December 4, 2019 at 3:51 pm

      It will always print two messages. first is print(type(s)) and second is from the the if-else condition.
      You typed wrong messages in the if-else block.

      Reply
  14. Edward B Lipp III says

    June 21, 2019 at 12:04 am

    In my code, I want to enter a string. If the default type for input is a string, why do I have to put quotes around it?
    python mscode.py

    enter series of words separated by spaces: aa bb
    Traceback (most recent call last):
      File "mscode.py", line 17, in main
        text = input("enter series of words separated by spaces: ")
      File "", line 1, in 
    NameError: name 'a' is not defined
    

    python mscode.py
    enter a series of words separated by spaces: “aa bb”
    This works properly. Why do I need quotes?

    Reply
    • Vishal says

      June 21, 2019 at 7:18 am

      Hi Edward, You don’t need to provide it in double-quotes. Can you please paste your code so I can look into it

      Reply
  15. 0_ace_0 says

    April 5, 2019 at 4:05 am

    next = input(“>”)
       if "10" in next or "11" in next or "99" in next:
             how_much=int(next)
        else:
             dead(“Man, learn to type a number”)
             exit(0)
    
        if how_much < 50:
    		 #here you didnt have brackets
             print("Nice, you're not greedy, you win!")
             exit(0)
         else:
             dead("You greedy bastard!")
    

    #and maybe you have as well indentation errors

    Reply
    • Devesh says

      August 6, 2020 at 7:48 pm

      n= input("Number please: ")
      if n.isdigit():
          how_much = int(n)
          if how_much <= 50:
              print("Nice")
          else:
              print("Greedy")
      else:
          print("Please learn to write a number")

      You were making it complicated, try this, this is simple. And yes, your code has too many errors like variable definition and using functions.

      Reply
  16. Disionas says

    March 13, 2019 at 5:02 pm

    I am trying this program on python 2.7.1:

    next = raw_input(">")
        try:
            if (next.isdigit()):
                how_much=int(next)
            else:
                dead("Man, learn to type a number")
                exit(0)
    
        if how_much < 50:
            print "Nice, you're not greedy, you win!"
            exit(0)
        else:
            dead("You greedy bastard!")
    
    I get the message:
    if how_much < 50:
         ^
    SyntaxError: invalid syntax
    

    Can you explain to me why this happens and how I can solve it

    Reply
  17. hello says

    February 4, 2019 at 12:06 pm

    what if you only want letter input and no int or float?

    Reply
    • Vishal says

      February 4, 2019 at 12:57 pm

      Hey, Abdul use input() method without doing any explicit casing. input() method always converts user input into a string. a single char is also nothing but the string in Python.

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

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 OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com