0

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 ?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Ibrahim
  • 11
  • 1
  • 6
  • 1
    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 Jan 19 '20 at 06:50
  • Does this answer your question? [How do you set a conditional in python based on datatypes?](https://stackoverflow.com/questions/14113187/how-do-you-set-a-conditional-in-python-based-on-datatypes) – MisterMiyagi Jan 19 '20 at 06:54
  • @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 Jan 19 '20 at 07:00
  • I added like this if type(number) == float: – Ibrahim Jan 19 '20 at 07:01
  • @MisterMiyagi I already used those ways but it not working. – Ibrahim Jan 19 '20 at 07:33
  • 2
    @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. – juanpa.arrivillaga Jan 19 '20 at 07:36
  • @Ibrahim The check does not match because ˋinputˋ always returns a ˋstrˋ. Your checks are working fine, the data types you test against simply *are not* equal. You may want to convert your str to float or int, or you may just want to check whether the input is a literal for either — it’s impossible to tell from your question. – MisterMiyagi Jan 19 '20 at 07:49
  • this might help [how can i read inputs as numbers](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers/26855555#26855555) – AntiMatterDynamite Jan 19 '20 at 08:05
  • You can drop all the ifs and just use ```float.hex(float(number))``` for them all - int-s, or float-s. You will just get back normalised form, and that's the only difference. – Grzegorz Skibinski Jan 19 '20 at 09:08
  • @MisterMiyagi thanks for you reply, if you look at my code, it is a simple converter, that either converts float or decimal to Hexadecimal, but I just added a check to see if the user entered float or decimal. can you understand now? thanks – Ibrahim Jan 20 '20 at 08:07
  • @GrzegorzSkibinski I don't want to drop if statements because I want add a condition to check if float or integer is entered by the user. – Ibrahim Jan 20 '20 at 08:09
  • 1
    @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. – MisterMiyagi Jan 20 '20 at 09:00

4 Answers4

3

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', <class 'str'>)

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, <class 'int'>)

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")
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
2

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")
L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

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)
Asad Ullah
  • 43
  • 1
  • 3
  • 7
-1

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'

Ibrahim
  • 11
  • 1
  • 6