Check input type python

How to check if input is float or int?

I want to make a simple converter, to print either hexadecimal number of float or integer. My code is:

number = input("Please input your number. \n") if type(number) == type(2.2): print("Entered number is float and it's hexadecimal number is:", float.hex(number)) elif type(number) == type(2): print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) else: print("you entered an invalid number") 

But it is always skipping the first two statements and just print else statements. Can someone please find out the problem ?

Because the type of number is always str . Note, types/classes are objects. You can use them directly int instead of type(2) etc

@juanpa.arrivillaga thanks for reply but I checked this before but it was not wroking. I changed it again as you said but the it skips if and elif statements.

@Ibrahim No, I wasn’t saying that would fix your problem. I already explained to you that input will always return an object of type str , which is why it’s being skipped.

@Ibrahim I’ve edited your title to match what you have just described. Feel free to adjust it further if you think it’s not correct.

4 Answers 4

TLDR: Convert your input using ast.literal_eval first.

The return type of input in Python3 is always str . Checking it against type(2.2) (aka float ) and type(2) (aka int ) thus cannot succeed.

>>> number = input() 3 >>> number, type(number) ('3', ) 

The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python’s basic data types. It automatically parses int and float literals to the correct type.

>>> import ast >>> number = ast.literal_eval(input()) 3 >>> number, type(number) (3, ) 

In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:

import ast number = ast.literal_eval(input("Please input your number. \n")) if type(number) is float: print("Entered number is float and it's hexadecimal number is:", float.hex(number)) elif type(number) is int: print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) else: print("you entered an invalid type") 

Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try — except to respond to this case:

import ast try: number = ast.literal_eval(input("Please input your number. \n")) except Exception as err: print("Your input cannot be parsed:", err) else: if type(number) is float: print("Entered number is float and it's hexadecimal number is:", float.hex(number)) elif type(number) is int: print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number)) else: print("you entered an invalid type") 

input returns a string, you are trying to check whether it looks like a float or an integer:

number = input("Enter your number? ") try: number = int(number) print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) except ValueError: try: number = float(number) print("Entered number is float and it's hexadecimal number is:", float.hex(number)) except ValueError: print("You entered an invalid number") 

If you want to check whether an input is int, float or string, we can also use these checks to determine this:

val= input("Please enter a value: ") # string if val.find(".")>-1 and val[:val.find(".")].isnumeric() and val[val.find(".")+1:].isnumeric(): # checks if string before and after "." is int val=float(val) elif y.isnumeric(): val=int(val) 

I wanted to make a simple converter that would convert decimal or float number to Hexadecimal using Python3. But before that I wanted to add a simple check if the number entered through command prompt is decimal or hexadecimal. But after some searching I found that the problem with input() function of Python3 is that anything entered through terminal using this function will always print as string and doesn’t evaluate it. So we can’t apply check condition directly. Now there is one possibility to use data-conversion function like number = int(input(«Enter the number»)) or number = float(input(«Enter the number»)) but here the main problem is we can only check one condition at a time, either, float or integer. Like the one shown below:

number = float(input("Enter the number")) if type(number) == float: print("Entered number is float and it's hexadecimal is:", float.hex(number)) else: print("you entered an invalid number") 

Or the same method can be used for int with little modification like:

number = int(input("Enter the number")) if type(number) == int: print("Entered number is, ", number,"and it's hexadecimal is:", hex(number)) else: print("you entered an invalid number") 

But here we can only enter integer because float can not be converted into integer using int() function. It will give the following error:

invalid literal for int() with base 10: ‘2.2’

Источник

Читайте также:  Php my little forum

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.

python check input is a number or a string

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
Читайте также:  Link css to html example

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.

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.

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

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.

Читайте также:  Practical database programming with java ying bai

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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

Источник

How to check input() data type in python? [duplicate]

I am trying to check a data type in python. I want to use an if statement to check if the data is a string or not. And everytime i input an integer it returns the value as a string. Here is the code.

inp = input("Input: ") if type(inp) != str: print("You must input a string") else: print("Input is a string") 

input() always returns a string. You can only manipulate the input after the user has entered the value.

@debugger Exactly, you manipulate the inputted value after it’s entered, by converting it to an integer.

def has_numbers(inputString): return any(char.isdigit() for char in inputString) to check if a digit is in the string.

3 Answers 3

First of all numbers can also be strings. Strings are anything which is enclosed in double quotes. Anyway if all you need is to get an input and verify that it’s not a number you can use:

inp = input("Input: ") if inp.isdigit(): print("You must input a string") else: print("Input is a string") 

Or if you wish to have a string with no digits in it the condition will go something like this:

inp = input("Input: ") if any(char.isdigit() for char in inp) : print("You must input a string") else: print("Input is a string") 

It will always be a string as input() captures the text entered by the user as a string, even if it contains integers.

@SJXD No, there isn’t. the return type of input() is a string. You have to parse that string according to whatever logic you want to impose, but the function returns a string.

The input() function always returns a datatype of string. To check if what you want to check a simple way would be to iterate over the string and if there is no character present then print «You must input a string».

inp = input("Input: ") for i in inp: if i.isalpha(): print("Input is a string") break else: print("You must input a string") 

A better solution would be using try except:

inp = input("Input: ") try: x=int(j) print("You must input a string") except: print("Input is a string") 

this is because int() function throws an error of there is a letter in the string given to it as an input parameter

Источник

Оцените статью