欢迎访问宙启技术站
智能推送

Python中如何使用Prompt()函数实现一个简单的计算器程序

发布时间:2024-01-02 09:45:07

Python中没有内置的Prompt()函数,但可以使用input()函数实现一个简单的计算器程序。下面是一个使用示例:

def calculator():
    print("欢迎使用简单计算器!")

    while True:
        # 获取用户输入的表达式
        expression = input("请输入一个表达式(使用空格分隔运算符和操作数):")
        
        # 将表达式拆分为运算符和操作数
        operator, operand1, operand2 = expression.split(" ")
        
        # 将操作数转换为数值
        operand1 = float(operand1)
        operand2 = float(operand2)
        
        # 根据运算符执行不同的操作
        if operator == "+":
            result = operand1 + operand2
        elif operator == "-":
            result = operand1 - operand2
        elif operator == "*":
            result = operand1 * operand2
        elif operator == "/":
            result = operand1 / operand2
        else:
            print("无效的运算符,请重新输入!")
            continue
        
        print("计算结果:", result)
        
        # 询问用户是否继续计算
        choice = input("是否继续计算?(输入'y'继续,其他键退出):")
        if choice != "y":
            break

calculator()

这个简单的计算器程序用一个无限循环实现,用户可以输入两个操作数和一个运算符来进行加、减、乘、除运算。输入的表达式形如运算符 操作数1 操作数2,使用空格分隔。程序会根据运算符执行相应的计算,并输出结果。

请注意,在此示例中没有进行输入验证,如果输入的格式不正确,程序可能会产生错误。在实际应用中,可以根据需求进行输入验证来确保输入的正确性。