0

So basically want to stop a script if an if statement is not met, the statement is this:abbrevationabbrevation

if x > 40 : print ("Please enter a number between 2 and 40")

If the user enters 41 for example, I don't want the program to continue running, but at the moment it does.

7
  • Welcome to SO. Did you know if you copy/paste your post title verbatim into Google, you will have your answer? Commented Nov 8, 2018 at 21:02
  • Been looking for the last day before asking on here, can't find an answer. :) Commented Nov 8, 2018 at 21:03
  • 2
    not using a function or while loop? then only option to exit from script would be sys.exit() Commented Nov 8, 2018 at 21:05
  • Tried that, problem is the rest of the script won't work if I do that, so if they enter a completely valid number like 20, it still won't work cause program told it to exit before it got to that point. Commented Nov 8, 2018 at 21:09
  • @LM sys.exit() should always be inside a condition otherwise rest of the code would automatically become unreachable Commented Nov 8, 2018 at 21:12

4 Answers 4

1
import sys

if (x > 40):
    print ("Invalid input received. Exiting now")
    sys.exit()
else:
    # do the result of your program
Sign up to request clarification or add additional context in comments.

Comments

0

A simple solution could be to raise an exception that will ultimately stop your script from running

if x > 40 or x < 2:
    raise Exception("Please enter a number between 2 and 40")

you can call sys.exit() which will raise SystemExit exception or raise the same exception to play safe

Comments

0

As mad_ mentioned, you can just use exit from the sys module

import sys
if x > 40:
    sys.exit()
else:
    print('do something')

2 Comments

This is backwards from what he wants.
My bad, I went straight to the point of the functionality on the title and not the actual requirement but hopefully the idea helps, and just fixed it
0

You can use a break statement. Simply put break in the if condition or the while loop

1 Comment

I think the "if not using function or while loop" in the title is because they already know about control flow tools like return and break

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.