Search code examples
python-3.xexitcontinue

Can`t exit from program


Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here

#import sys


def body_cycle(*args):

    if option == "/":
        error_func_for_zero(first_number, second_number, option)
        print(division_option(first_number, second_number))
        print()
        print(begin)


def error_func_for_zero(*args):

    try:
       first_number / 0 or second_number / 0

    except ZeroDivisionError:
       print("YOU CANNOT DIVIDE BY ZERO!")
       print(begin)

def division_option(*args):

    return first_number / second_number


begin = " " 

while begin:

    print("Hello, I am calculator. ")  
    print("Please, enter your numbers (just integers) ! ")

    print()

    first_number = int(input("First number: "))

    print()

    second_number = int(input("Second number: "))

    print()

    option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")

    print(body_cycle(first_number, second_number, option))


ask = " "

while ask:

    exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")

    if exit_or_continue == "Y" or "y":
       print("OK")

    elif exit_or_continue == "N" or "n":  
       #break
       ask == False

    else:
       print("Break program. ")
       break

Solution

  • You just want to replace ask == False by ask = False.

    In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:

    def operation(a, b, option):
    
        if option == "+":
            return a + b
    
        elif option == "-":
            return a - b
    
        elif option == "*":
            return a * b
    
        elif option == "/":
            try:
                return a / b
            except ZeroDivsionError
                return "YOU CANNOT DIVIDE BY ZERO!"
    

    The rest can be put in a single loop instead of two, like so:

    print("Hello, I am calculator. ")  
    
    while True:
        print("Please, enter your numbers (just integers) ! ")
        print()
    
        first_number = int(input("First number: "))
        print()
    
        second_number = int(input("Second number: "))
        print()
    
        option = input("Remember: you can't divide by zero.\n
                        Choose your option (+, -, *, /): ")
    
        # Result.
        print(operation(first_number, second_number, option))
    
        exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
                                  Choice: ").lower()
    
        if exit_or_continue == "y":
           print("OK")
    
        elif exit_or_continue == "n":
           break