How to exit a python script in an If statement?

593    Asked by darsh_6738 in Python , Asked on Aug 8, 2023

I have been using Python 3.2 and attempting to exit it after the user inputs that they do not wish to continue. Is there code that may exit in an if statement in a while loop? I have tried utilizing exit(), sys.exit(), sys.quit(), quit(), and raise System Exit

Answered by Diane Carr

If you wish to pause code execution in Python you must import the sys object. Then you can call the exit() method to pause the program from running. You can follow the below-mentioned procedure.


While True:
Answer = input (‘ do you want to continue?;’)
If answer.lower().startswith(“y”):
Print (“ok, carry on then”)
Elif answer.lower().startswith(“n”):
Print (“ok, sayonara”)
exit()

You can also use the break statement which breaks out of a loop in Python. The while loop can be utilized to make an infinite loop by offering a true condition. We apply the if statement with the loop and deploy the break statement when we wish to exit if statement in Python. It will break out of the loop and continue the program running. This can be used in the following code:

A - 10
While True:
If a>5:
Print (“within if statement”)
Break #exit if statement in Python
Print (“ if statement not exited”)
Else:
print(“if statement still not exited”)
Print (“if statement exited!”)

The Python online training offered at JanBask Training gives you an experience like offline classes thereby saving the students from the tiring journey to travel to the physical locations. The course provides a total Python discipline’s preparation by touching on every core concept from basic to advanced thereby making your job ready to face the tough competitive market.



Your Answer

Interviews

Parent Categories