一天下午我感到无聊,决定制作一个简单的蟒蛇计算器,要求两个数字并执行和操作。它起初是一个64行代码,我简化它现在只需9行代码!我只是好奇,如果有人能使代码少于9行。是否可以拥有更少的行并仍然执行相同的操作?请发布您可以提出的内容,我认为它不会短于9行。这是我写的,功能齐全。 Python 2.7:
num1 = float(raw_input("What will be your first number?:\n"))
num2 = float(raw_input("What will be your second number?:\n"))
Q_3 = raw_input("What will be your operation?:\n")
if Q_3 == "+": print(num1 + num2)
if Q_3 == "-": print(num1 - num2)
if Q_3 == "/": print(num1 / num2)
if Q_3 == "*": print(num1 * num2)
if Q_3 == "%": print(num1 % num2)
if Q_3 == "**": print(num1 ** num2)
答案 0 :(得分:3)
5行:
num1 = float(raw_input("What will be your first number?:\n"))
num2 = float(raw_input("What will be your second number?:\n"))
Q_3 = raw_input("What will be your operation?:\n")
if Q_3 in ("+", "-", "/", "*", "%", "**"):
print(eval("%s %s %s" % (num1, Q_3, num2)))
或者有4行:
num1, num2, Q_3 = map(raw_input, ["What will be your first number? ",
"What will be your second number? ", "What will be your operation? "])
if Q_3 in ("+", "-", "/", "*", "%", "**"):
print(eval("%s %s %s" % (float(num1), Q_3, float(num2))))
答案 1 :(得分:0)
感谢JuniorCompressor,新的计算器代码可以简化为2行!!
num1, num2, Q_3 = map(raw_input, ["What will be your first number? ", "What will be your second number? ", "What will be your operation? "])
if Q_3 in ("+", "-", "/", "*", "%", "**"): print(eval("%s %s %s" % (float(num1), Q_3, float(num2))))