我有一个简单的 Python 计算器,我需要一个 "quit" 选项

I have a simple Python Calc and I need a "quit" choice

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y

print("İşlem seçiniz.")
print("1.Toplama")
print("2.Çıkarma")
print("3.Çarpma")
print("4.Bölme")

while True:
    # Take input from the user
    choice = input("Seçim yapınız(1/2/3/4): ")

    # Check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("İlk numarayı giriniz: "))
        num2 = float(input("İkinci numarayı giriniz: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))

    else:
        print("Hatalı Giriş")

这是我的带有 def 函数的简单计算器,我需要在菜单中有一个 quit/break 选项,我想要这样的一个选项代码

    def run():
        while True:
            choice = get_input()
            if choice == "a":
                # do something
            elif choice == "q":
                return

    if __name__ == "
__main__":
    run()

如果有人帮助我,我将不胜感激。谢谢。

这是我的学校作业,如果你能详细解释一下代码,我将不胜感激。我尽可能地提高自己,不能做这么简单的事情让我很难过,但我需要你的帮助。祝我好运进步。并注意身体,待在家里

您可以通过以下方式导入sys模块并退出代码:

import sys

def run():
    # do stuff
    if choice == "q":
        sys.exit() # this exits the python program

我以前制作过几个菜单,在这种情况下我最喜欢的选项是将菜单选项放在它自己的函数中,然后让它 return 将选择权返回给主函数。像这样:

def multiply(number1, number2):
    return number1 * number2

def showmenu():
    print("1. Multiply")
    print("2. Quit")
    return input("Choice:")

def main():
    playing = True

    num1 = 5
    num2 = 3

    while playing:
        choice = showmenu()

        if choice == '1':
            print(f'{num1} * {num2} = {multiply(num1,num2)}')

        elif choice == '2':
            print("Quitting!")
            playing = False

if __name__ == "__main__":
    main()

如果用户说输入 q,添加一个选项以在输入时中断 while 循环?

elif(x == "q"):
   break