Search code examples
pythonprintingauto

Stop program on condition python


I'm a novice in python and I'm working because getting hands on work is always the best way to learn. I'm stuck here, none of my logic seems to help me with the little code I know.

I want to stop a program after it meets a certain condition. I've given an example below.

ex_list = ["1","2","3"]

print(*ex_list, sep="\n")

Expected Output:

1 
2
3

Output:

1
2 
2 is here exiting

Here, the number after two which is 3 is not shown. The program terminates just on finding 2.

I tried if I could access and process the print content so I put the content into a variable and using if statements. It didn't work... any help would be appreciated.


Solution

  • Try something like this:

    import sys
    ex_list = [1,2,3]
    for e in ex_list:
      print e
      if e == 2:
        print '2 is here! exiting..' 
        sys.exit(0)