r/PythonLearning • u/The-Turnt-Tiger • 7d ago
Help Request Need help understanding how != works
Hello, I'm working on learning the basics of try/except blocks. To do so, I'm intentionally raising errors. The question is: why is my TypeError occurring when I enter an integer? I checked the input type, and it shows as an integer, but the error is still raised. What am I missing here?
9
u/BanSolitude 7d ago
Your original question has been answered, but I will point out that your code as written will never hit line 25. int(...) will raise an exception if you pass in a value that cannot be converted to an integer, if the code makes it to line 24 then carsAvailable must be an integer, and the check is redundant.
1
u/The-Turnt-Tiger 7d ago
I see what you're saying. I'm using the raise to help visualize what's happening while I try to understand how this works. Thank you for pointing that out though.
4
3
u/Flame77ofc 7d ago
a != b is the same as !(a == b)
like
1 != 3 -> True!(1 == 3) -> !(False) -> !False -> True
0
u/The-Turnt-Tiger 7d ago
I don't understand how you're trying to explain this, but that's ok. Another comment helped me understand. Thank you anyway; I appreciate your response.
2
u/TotalUnlucky2814 7d ago
carsAvailable casts the input string as an int... If it fails you have an error at line 22 so you will never be able to arrive to line 24
1
1
u/zztopsboatswain 7d ago
Because carsAvailable does not literally equal or not equal "int". what you want is
try:
...
except TypeError:
...1
1
u/atarivcs 7d ago
carsAvailable = int(...)If that assignment succeeds, carsAvailable is guaranteed to be an integer. Checking the type is redundant.
1
u/sexiestsaxiestman 7d ago
isinstance is the standard way of doing type checks. Ex: if isinstance(carsAvailable, int). Basically what your code is doing is checking if the value of carsAvailable is equal to the integer type which it is not. You also already explicitly convert the input to an int using int(...) so the type check is unnecessary. Ps, snake_case is more common in python than camelCase 😉
-3


24
u/Ok-Promise-8118 7d ago
You are comparing the variable to the type int. You want to compare the type of the variable to the type int. You already have the concept in your print statement.