End in middle of Python

Asked 2 years ago, Updated 2 years ago, 20 views

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

2022-09-21 14:53

2 Answers

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.


2022-09-21 14:53

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


2022-09-21 14:53

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.