Python Forum

Full Version: May i ask how i can stop my coding running
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good Day, may i ask how can i stop my code running. I am using if else statement.

try:
A = "111111"

if A == "123456":
print('OK')
else:
print('NG')

if A == "111111":
print('OK')
else:
print('NG')


if output get OK my code will continue run the next step.

If output get NG how i can stop running my code to the
next step
It's unclear what 'try:' is doing here (is it part of try...except?).

To answer your question: you need to use elif instead of if. However, if you look at the code (you print out same messages) then it can be expressed more compactly:

if a in ['123456', '111111']:
    print('OK')
else:
    print('NG')
(Oct-03-2019, 06:28 AM)perfringo Wrote: [ -> ]It's unclear what 'try:' is doing here (is it part of try...except?).

To answer your question: you need to use elif instead of if. However, if you look at the code (you print out same messages) then it can be expressed more compactly:

if a in ['123456', '111111']:
    print('OK')
else:
    print('NG')
try is the python syntax.
may i ask if my output get "NG" how i can stop running the code
You can use the "exit" method from the "sys" module...
import sys

try: # Remember, a "try:" must always include an "except:" statement
    A = "111111"

    if A == "123456":
        print('OK')
    else:
        print('NG')
        sys.exit(1)

    if A == "111111":
        print('OK')
    else:
        print('NG')
        sys.exit(1)

except: 
    pass # Do nothing
OR (more Pythonicly) you can use that "try:, except:"...
try: # Remember, a "try:" must always include an "except:" statement
    A = "111111"

    if A == "123456":
        print('OK')
    else:
        raise ValueError("The value of 'A' ({}) was incorrect.".format(str(A)))

    if A == "111111":
        print('OK')
    else:
        raise ValueError("The value of 'A' ({}) was incorrect.".format(str(A)))

except ValueError as e:
    print("NG")

Quote:may i ask if my output get "NG" how i can stop running the code
A variation on perfringo's (correct) code...

while True:
    a = input("Enter a number...")
    if a in ['123456', '111111']:
        print("OK")
    else:
        print("NG")
        break # Will stop the infinite "while" loop
You have been adviced two times also in previous Thread to use code tag @christing.