如何在基本计算器中包含平方根

How to include square root in a basic calculator

所以我在python中写了一个基本的计算器:

import math
import sys

num1 = float(input("Enter a number "))

operator = input("Enter a operator ")

num2 = float(input("Enter a second number "))
if operator == '+':
    print (num1) + (num2)
elif operator == '-':
    print(num1 - num2)
elif operator == '*':
    print(num1 * num2)
elif operator == '/':
    print(num1 / num2)

elif operator == "sqrt":
        print(math.sqrt(num1))

else:
    print("Unknown operator")

我想制作 平方根命令 函数,这样当我选择 num1 和平方根运算符时,它会跳过其余部分,直接给我结果。而不是需要也写出 num2.

把它放在一个函数中,这样你就可以在请求 num2 之前 return 如果合适的话:

import math

def calc():
    num1 = float(input("Enter a number "))
    operator = input("Enter a operator ")

    if operator == "sqrt":
        print(math.sqrt(num1))
        return

    num2 = float(input("Enter a second number "))
    if operator == '+':
        print (num1) + (num2)
    elif operator == '-':
        print(num1 - num2)
    elif operator == '*':
        print(num1 * num2)
    elif operator == '/':
        print(num1 / num2)


calc()

其他一元运算可以简单地添加为 elifs 在 sqrt.

的下面

另一种方法可能是根据操作数的数量将您的运算符放入字典中:

import math

unary_ops = {
    "sqrt": math.sqrt,
}
binary_ops = {
    "*": float.__add__,
    "-": float.__sub__,
    "*": float.__mul__,
    "/": float.__truediv__,
}

num1 = float(input("Enter a number "))
operator = input("Enter a operator ")
if operator in unary_ops:
    print(unary_ops[operator](num1))
elif operator in binary_ops:
    num2 = float(input("Enter a second number "))
    print(binary_ops[operator](num1, num2))
else:
    print(f"Sorry, I don't know how to '{operator}'.")