簡體   English   中英

我怎樣才能讓我的 Python 3 代碼更緊湊?

[英]How could I make my Python 3 code more compact?

這是我的代碼,我發現它有點笨重和重復。 """ 鍵 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的值並將其鏈接到要使用的目標函數。

  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}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM