Actual Question
Why something like:
#Converting float to integer
a = 1.0
int(a) # a is now 1
# Converting String to float to integer
b = '1.0'
b = float(b) # b is now 1.0
b = int(b) # b is now 1
works but:
a = '1.0'
a = int(a) # this throws a ValueError (invalid literal for int() with base 10: "1.0")
Context for question
The reason I ask is because I had a problem with getting two numbers, p
and q
, as input and depending on:
- if both are integers, return
p//q
- if at least one is a float, return
p/q
- print a warning if either is not a valid number.
The method I used was:
p, q = input("Enter two numbers: ").split()
try:
p = int(p)
q = int(q)
print("P//Q = ", p//q)
except ValueError:
try:
p = float(p)
q = float(q)
print("P/Q = ", p/q)
except ValueError:
print("Invalid entries for p or q.")
This seems to work, but I was surprised when entering '1.0' for one of the values threw a value error when calling int('1.0')
.
I did try .isdigit()
and .isdecimal()
methods, however both fail on the string "0.5" etc.
Edited the question for clarity on what I was actually asking. I apologize for how the problem was posted