重构 Python 的代码 - 使用变量



嗨,我正在自学Python,我打算重构这段代码。我想使用函数的声明和调用。

所以原始代码是:

num1 = int(input("Enter a number: "))
num1 = num1**2
num1 = num1 - 5
num1 = num1 / 3
num2 = int(input("Enter another number: "))
num2 = num2**2
num2 = num2 - 5
num2 = num2 / 3
result = Math.sqrt(num1*num2)

到目前为止我在做什么。有什么建议吗?:

import math
def calculate(num1,num2, result):
num1 = int(input("Enter a number: "))
num1 = num1**2
num1 = num1 - 5
num1 = num1 / 3
num2 = int(input("Enter another number: "))
num2 = num2**2
num2 = num2 - 5
num2 = num2 / 3
result = math.sqrt(num1*num2)
return(result)
print(calculate())

以下是我的重构建议:

import math
def getNum(msg):
num = int(input(msg))
num = num ** 2
num = num - 5
num = num / 3
return num
def calculate():
num1 = getNum("Enter a number: ")
num2 = getNum("Enter another number: ")
result = math.sqrt(num1 * num2)
return result
print(calculate())
import math
def calculate(num1, num2):

num1 = num1**2
num1 = num1 - 5
num1 = num1 / 3
num2 = num2**2
num2 = num2 - 5
num2 = num2 / 3
return math.sqrt(num1*num2)
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
print(calculate(num1, num2))

这里有一种让一切都更干净的方法:

import math
def get_value(input_string): # reusable code should be functionized
num1 = int(input(input_string)) # get user input with the various strings you would like to output
return ((num1**2) - 5) / 3 # do all of the same math once, since these are basic functions can do on a single line
def calculate(): # only using local variables
num1 = get_value("Enter a number: ")
num2 = get_value("Enter another number: ")
return math.sqrt(num1*num2) # don't need to store it as an intermediate value can just return the value generated
print(calculate())

最新更新