Search code examples
pythonpython-3.xfunctionrefactoringinvoke

Refactoring Python's code - with variables


Hi I'm learning Python by myself and I'm tying to refactor this code. I want to use declaration and invoke of the function.

So the original code is:

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)

What I'm doing so far. Any suggestions?:

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())

Solution

  • Here is my refactoring suggestion:

    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())