Python 简单计算器代码示例:加减乘除运算实现
以下是一个简单的计算器程序的 Python 代码,实现加减乘除四种基本运算。
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return 'Error: division by zero'
return a / b
print('Welcome to the calculator program!')
print('Please enter two numbers and the operation you want to perform.')
num1 = float(input('Enter the first number: '))
num2 = float(input('Enter the second number: '))
operation = input('Enter the operation (+, -, *, /): ')
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
result = 'Error: invalid operation'
print('The result is:', result)
该程序首先定义了四个函数,分别实现加、减、乘、除四种基本运算。然后,程序会提示用户输入两个数字和要执行的操作。根据用户输入的操作符,程序会调用相应的函数进行计算,并输出结果。如果用户输入了无效的操作符或除数为零,则程序会输出错误信息。
原文地址: https://www.cveoy.top/t/topic/oalM 著作权归作者所有。请勿转载和采集!