Home > Software design >  Refactoring Python's code - with variables
Refactoring Python's code - with variables

Time:10-20

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

CodePudding user response:

here is a way to make everything cleaner:

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

CodePudding user response:

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

CodePudding user response:

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