这是Python中高效的计算器吗? [英] Is this an efficient calculator in Python?

查看:57
本文介绍了这是Python中高效的计算器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Python中高效的计算器吗?

Is this an efficient calculator in Python?

def calculator():

    print("\nBasic Calculator.\n")

    num_1 = input("Enter your first number: ")
    operation = input("Enter your operation: ")
    num_2 = input("Enter your second number: ")

    if operation == ("+"):
        sum = float(num_1) + float(num_2)
        print ("The answer is:",(sum))

    elif operation == ("-"):
        sum = float(num_1) - float(num_2)
        print ("The answer is:",(sum))

    elif operation == ("*"):
        sum = float(num_1) * float(num_2)
        print ("The answer is:",(sum))

    elif operation == ("/") and num_2 == ("0"):
        print ("\nYou cannot divide by zero.")

    elif operation == ("/"):
        sum = float(num_1) / float(num_2)
        print ("The answer is:",(sum))

    else:
        print("Invalid Operation.")

    restart = input("\nDo you want to enter another equation? Yes or No?").lower()

    if restart == ("yes"):
        calculator()

    else:
        print ("\nEnding Program.")
        quit()

calculator()


推荐答案

您可以使用 eval()

a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))



0.5

按用户处理恶作剧:

a = 1
b = 0
operation = '/'
try:
    print(eval(f'{a} {operation} {b}'))
except Exception as exp:
    print(exp)

这篇关于这是Python中高效的计算器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆