Home > OS >  Python: from str to int or float using input()
Python: from str to int or float using input()

Time:09-30

I have the following script:

1   mylst = []
2   num = input("Enter height: ")
3   
4   if isinstance(num, int) or isinstance(num, float):
5       mylst.append(num)
6   else:
7       print("END")
8   
9   print(mylst)

Let's say I have the following heights in cm (without decimal): 175, 181, 189

And then I decided to enter heights in inch (with decimal): 5.6, 5.9, 6.2

So mylst will be ['175', '181', '189', '5.6', '5.9', '6.2']

I know that the output type of input() is always a str. And, yes, my script is not a loop. I don't want to change the input() into int(input()) or float(input()) every time I run the code. I need to use only if else statements. No while loop, no try except, and no for loop

So basically, I enter a number, whether it is an int or float, then it will convert str number into int or float, or stay str if the input is a non-number (alphabetic or any character), then it runs through if else statements.

I just can't figure it out how to convert the string number to an integer or float number. The .isdecimal() doesn't work, it will be considered as a str if the number value with a decimal.

Could you please help me with this?

Thank you!

CodePudding user response:

Check out the str.isnumeric() method for seeing if a string is an integer.

The better implementation would be to use a try/except case.

Code example:

if num.isnumeric():
    mylst.append(int(num))
elif num.replace(".", "").isnumeric():  # best I could think of without using try/except
    mylst.append(float(num))
else:
    # append if string, not sure if this is what is intended
    mylst.append(num)
  • Related