(Nov-19-2023, 04:05 PM)RockBlok Wrote: Could anyone provide feedback on the preferred way to terminate a program?
It's a little vague question,i would say that preferred way is to think about a nice way to exit/terminate of program when write it.
Then many time there is no need to use
quit(), exit(), sys.exit()
at all,in some cases it may be useful.
A example,so here use a control variable
q
to exit the loop,also this exit program just bye
return
out of the function.
def file_deletion():
file_to_delete = input('File to delete: ')
print(f'Deleting <{file_to_delete}>\n')
input('Push enter to retun to menu')
def file_creation():
pass
def show_menu():
print ("\nExample menu")
print ("-----------------")
print ("1) File deletion")
print ("2) File creation")
print ("Q) Exit\n")
def menu():
while True:
show_menu()
choice = input('Enter your choice: ').lower()
if choice == '1':
file_deletion()
elif choice == '2':
file_creation()
elif choice == 'q':
return
else:
print(f'Not a correct choice: <{choice}>,try again')
if __name__ == '__main__':
menu()
Output:
G:\div_code\ur_env
λ python meny.py
Example menu
-----------------
1) File deletion
2) File creation
Q) Exit
Enter your choice: car
Not a correct choice: <car>,try again
Example menu
-----------------
1) File deletion
2) File creation
Q) Exit
Enter your choice: 1
File to delete: foo.txt
Deleting <foo.txt>
Push enter to retun to menu
Example menu
-----------------
1) File deletion
2) File creation
Q) Exit
Enter your choice: q
G:\div_code\ur_env