+ 1

Error in python

Can someone help me with my bug in my code? This is the part: #exceptions something = input() # take an input try: # do something with the input something = (int(something)) # if it's not a number it's a ValueError print(something) print(someting) # make a mistake print(movies[something]) except ValueError: # if input isn't a number print("type in a number") except IndexError: # if number is too high print("number must be under 6") except NameError: # if I used a wrong variable print("something is wrong with something ;)") try: # do something with the input print(something + 1) # if it's not a number it's a TypeError print(something # another mistake except TypeError: # if input isn't a number print("type in a number") except SyntaxError: print("There's a bug in the code") https://sololearn.com/compiler-playground/chE9gTsNZeHl/?ref=app

12th Aug 2025, 3:32 PM
Jakob
Jakob - avatar
6 odpowiedzi
+ 1
As I understand it, it works like this: The SyntaxError is raised before the code is executed (when the code is parsed, that is: when it is checked if it is a valid code). The NameError is only checked at runtime, when the code is executed. So, the SyntaxError has a special role compared to the other Errors. Whenever a SyntaxError is encomluntered, the code will not be executed at all, and hence, other non-syntactical errors won't be raised.
12th Aug 2025, 4:16 PM
Lisa
Lisa - avatar
+ 1
The first try-except block already raises an exception, and the code is no further interpreted. What behavior do you expect for your code?
12th Aug 2025, 3:47 PM
Lisa
Lisa - avatar
+ 1
I would like to trigger all except blocks for the demo.
12th Aug 2025, 3:49 PM
Jakob
Jakob - avatar
+ 1
I assume that the syntax error has higher precedence than the name error and that's why we're sent to line 129 straight away. I will need to have a closer look when I am free!
12th Aug 2025, 3:56 PM
Lisa
Lisa - avatar
+ 1
Thank you very much! I can wait 😀
12th Aug 2025, 3:59 PM
Jakob
Jakob - avatar
+ 1
Thanks! Is there another way to do what I want or should I just delete it?
12th Aug 2025, 4:19 PM
Jakob
Jakob - avatar