1. 首页
  2. 机器学习

用Python程序制作一个简单的计算器

要理解此示例,您应该了解以下Python编程主题:

  • Python函数
  • Python函数参数
  • Python用户定义函数用Python程序制作一个简单的计算器
# 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("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # Take input from the user
    choice = input("Enter choice(1/2/3/4): ")

    # Check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        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))
        break
    else:
        print("Invalid Input")

输出

选择操作
1.加
2.减
3.乘
4.除
输入选项(1/2/3/4):3
输入第一个数字:15
输入第二个数字:14
15.0 * 14.0 = 210.0

在此程序中,我们要求用户选择一个操作。选项1、2、3和4有效。如果有其他输入,输入无效 显示并继续循环,直到选择了有效选项为止。

取两个数字,并使用一个if...elif...else分支来执行特定的部分。用户定义的函数add()subtract()multiply()divide()评估各自的操作和显示输出。

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站不拥有所有权,不承担相关法律责任。如发现有侵权/违规的内容, 联系QQ1841324605,本站将立刻清除。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

服务热线:130-0886-1890

QR code