【问题标题】:How could I make my Python 3 code more compact?如何使我的 Python 3 代码更紧凑?
【发布时间】:2019-06-29 10:05:20
【问题描述】:

这是我的代码,我发现它有点笨重且重复。 """ 钥匙 UCIO = 用户选择的输入操作 x = 全局变量,用户操作的第一个数字 y = 全局变量,用户操作的第二个数字 z = 局部变量,所选操作的结果数 """

# Declaring the types of operates the user cold use
print("Select an operation")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Power")

# Making the code look neater
print("")

# Gathering information from the user to calculate equation
UCIO = input("Enter an operation 1/2/3/4/5: ")
x = input("Enter your first number: ")
y = input("Enter your second number: ")

# Making the code look neater
print("")

# Calculating an equation with the operation "+"
if UCIO == "1":
    z = float(x) + float(y)
    print(x + " " + "+" + " " + y + " " + "=" + " " + str(z))

# Calculating an equation with the operation "-"
elif UCIO == "2":
    z = float(x) - float(y)
    print(x + " " + "-" + " " + y + " " + "=" + " " + str(z))

# Calculating an equation with the operation "*"
elif UCIO == "3":
    z = float(x) * float(y)
    print(x + " " + "*" + " " + y + " " + "=" + " " + str(z))

# Calculating an equation with the operation "/"
elif UCIO == "4":
    z = float(x) / float(y)
    print(x + " " + "/" + " " + y + " " + "=" + " " + str(z))

# Calculating an equation with the operation "^"
elif UCIO == "5":
    z = float(x) ** float(y)
    print(x + " " + "^" + " " + y + " " + "=" + " " + str(z))

【问题讨论】:

  • 提示:使用UCIO的值设置一个字符串变量op_str和一个函数op,然后使用op_strop定义z并打印结果一次.
  • 你签出click了吗? Awesome 还可以很好地创建框架列表。你可以选择一个你喜欢的 CLI 框架:github.com/vinta/awesome-python#command-line-tools

标签: python processing-efficiency coding-efficiency


【解决方案1】:

正如cmets中所说,您可以使用UCIO的值并将其链接到要使用的目标函数。

  1. 创建一个包含UCIO 的字典。每个UCIO都有一个alias、一个message和一个操作函数fct
  2. 通过遍历字典并选择其message 键来打印所有可能的选项
  3. 收集您的输入,UCIOxy
  4. 如果UCIO在可能的选项中,使用字典中对应的操作函数fct
  5. 否则通知错误

ops = {}
ops['1'] = { 'alias': '+', 'message': 'Addition', 'fct': lambda x, y : x + y }
ops['2'] = { 'alias': '-', 'message': 'Substraction', 'fct': lambda x, y : x - y }
ops['3'] = { 'alias': '*', 'message': 'Multiplication', 'fct': lambda x, y : x * y }
ops['4'] = { 'alias': '/', 'message': 'Division', 'fct': lambda x, y : x / y }
ops['5'] = { 'alias': '^', 'message': 'Power', 'fct': lambda x, y : x ** y }

for k in ops.keys():
    print(f'{k}. {ops[k]["message"]}')

UCIO = input(f"Enter an operation {'/'.join(ops.keys())} : ")
x = input("Enter your first number: ")
y = input("Enter your second number: ")

if UCIO in ops and UCIO in ops:
    result = ops[UCIO]['fct'](float(x), float(y))
    print(f'{x} {ops[UCIO]["alias"]} {y} = {result}')
else:
    print('No candidates for the operation {UCIO}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2022-01-15
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多