Usually if you put int(a) or int(b) it will convert “a” and “b” into integers
If I try print(int(4.5)) it will print 4
But if I try it in a try statement:
JavaScript
x
22
22
1
def zero_dev(num1, num2):
2
try:
3
a = int(num1)/int(num2)
4
return int(a)
5
except ZeroDivisionError:
6
return 'Zero Division Exception: integer division or modulo by zero'
7
except ValueError:
8
try:
9
val = int(num1)
10
pass
11
except ValueError:
12
return f"Input Exception: invalid literal for int() with base 10: '{num1}'"
13
try:
14
val1 = int(num2)
15
except ValueError:
16
return f"Input Exception: invalid literal for int() with base 10: '{num2}'"
17
18
19
num_a = input()
20
num_b = input()
21
print(zero_dev(num_a, num_b))
22
Edit: If num1 = 4 and num2 = 4.5
How come Python didn’t convert num2 into an integer?
Previously int() would convert a float into an integer.
But here it doesn’t convert it, it tells me “num2” has a base of 10, it is not an integer.
Advertisement
Answer
input()
always returns a string. So num_a = input(...)
makes num_a
a string.
int()
won’t convert floats-as-strings to integers:
JavaScript
1
9
1
>>> int(3.4) # ok
2
3
3
>>> int("3") # ok
4
3
5
>>> int("3.4") # not ok
6
Traceback (most recent call last):
7
File "<stdin>", line 1, in <module>
8
ValueError: invalid literal for int() with base 10: '3.4'
9
But float()
has no problems with string inputs of floats or ints:
JavaScript
1
5
1
>>> float("3.4")
2
3.4
3
>>> float("3")
4
3.0
5
So combine that to get the behaviour you want – first convert the input (which is a string) to a float
and then to an int
:
JavaScript
1
3
1
>>> int(float("3.4"))
2
3
3