我如何才能让我的Python 3代码更紧凑?

问题描述 投票:-2回答:1

这是我的代码,我觉得这是一个有点笨重和重复。 “””键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))
python processing-efficiency coding-efficiency
1个回答
0
投票

由于这是在评论中说,你可以使用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}')
© www.soinside.com 2019 - 2024. All rights reserved.