I'm a beginner who just started learning Python.
How do I end the code in the middle?
For example,
#1st step
num = int(input('number: '))
if num >= 50:
print('my number is over 50')
elif num >=30:
print('my number is over 30')
elif num>=10:
print('end')
#I don't want to go to 2nd step here (when I get elif) and end it.
else:
print( num )
#2nd step
num2 = int(input('number2: '))
print('my number is ', num2)
It is. I looked it up and found that only the exit() function came out in Python IDLE He ended the Shall itself.
I just want to stop this Python file!!
python
class customEx(BaseException): pass
#1st step
num = int(input('number: '))
try:
if num >= 50:
print('my number is over 50')
elif num >=30:
print('my number is over 30')
elif num>=10:
print('end')
#I don't want to go to 2nd step here (when I get elif) and end it.
raise customEx
else:
print( num )
#2nd step
num2 = int(input('number2: '))
print('my number is ', num2)
except customEx:
pass
Try to deal with the exception.
import sys
#1st step
num = int(input('number: '))
if num >= 50:
print('my number is over 50')
elif num >=30:
print('my number is over 30')
elif num>=10:
print('end')
sys.exit(1)
else:
print( num )
#2nd step
num2 = int(input('number2: '))
print('my number is ', num2)
Do it like this
That's good
© 2025 OneMinuteCode. All rights reserved.