0
[Solved] What's wrong with the exception handling in this code?
I played around with it a lot. Could you please have a look? Thank you. https://code.sololearn.com/cF1m8wYI3Lkq/?ref=app
11 Answers
+ 3
Your code will raise a TypeError for any input because input is always string.
+ 4
You could do it like this:
n = input()
if not n.isdigit():
raise TypeError
n = int(n)
+ 1
+ 1
Korkunç TheTerrible
Everything I post can be copied and modified.
We're here to learn, after all.
+ 1
Bob_Li Thank you, it's much appreciated :-)
+ 1
Korkunç TheTerrible
Here's my thought on learning Python, or most other languages...
While writing your own code for performing operations is a great way to become more fluent in coding, you should also be aware of modules and libraries that already exists which may be able to perform the task better.
We don't have to reinvent the wheel everytime.
0
Simon Sauter
ouch. ouw. thanks, thanks a lot *facepalm*
0
Simon Sauter So then it's better if Python just caught it rather than me raising one, right? for the integer at least?
I could do float though--> no, I see
There was a function that accepted 5.0 and 5 both as integers...
Edit: I corrected it
Edit: No, the handling's still bad.
I'll rewrite it as int(input), except, removing the "raise"
0
Simon Sauter Thank you, I had no idea isdigit() only worked for integers in a string.(thought decimal places were called digits too)
0
Simon Sauter Hi. I was unable to spare as much time as I'd like to for this for the past 3 days, and it's only now I can ask about it.
I cannot get isdigit to work. (or it's something else that doesn't work)
The weirdest thing is it doesn't even print the test message that I coded in before raising TypeError, yet the output is the TypeError message coded in the exception.
Says 5 is not an integer.
I had tried some other stuff earlier today and as far as I understand, the error has nothing to do with isdigit, it's just that when I enter "5" it fits none of the conditions described. I cannot tell why. I did fac(int(n)) instead of n = int(n) and then fac(n), because I couldn't get that one to work either.
I hope I am not being blind as a bat again.
I did it some other way, btw. But that's irrelevant.
0
Bob_Li This is next in line for me to study, thank you. Do you think you'll delete it later? If you do, I'd like to copy and save it.