'Can anyone help me simplify the following code? [closed]
I'm attempting to reduce the redundancy within my code. If anyone can provide suggestions I would appreciate it. Below is the code I have in python. I understand that the input is used three times and is not necessary but I can't get the code to work without it. If anyone has experience with importing modules in an easier manner and would like to assist, I would also appreciate that.
# import Mylib to satisfy requirements 1 and 2
from Mylib import scalc
# Added try except to lowRange and highRange user input
while True:
lowRange = int(input('lowRange:'))
highRange = int(input('highRange:'))
try:
firstNumber = int(input('firstNumber:'))
except ValueError:
print("You must type a number between lowRange and highRange")
else:
if (firstNumber >= lowRange) and (firstNumber < highRange):
print("You entered: ", firstNumber)
else:
print("The number you entered is incorrect!")
try:
secondNumber = int(input('secondNumber:'))
except ValueError:
print("You must type a number between lowRange and highRange")
else:
if (secondNumber > lowRange) and (secondNumber < highRange):
print("You entered: ", secondNumber)
else:
print("The number you entered is incorrect!")
print("firstNumber=", firstNumber)
print("secondNumber=", secondNumber)
add = (firstNumber + secondNumber)
print("The result of " + str(firstNumber), "+", str(secondNumber), "=", add)
sub = (firstNumber - secondNumber)
print("The result of " + str(firstNumber), "-", str(secondNumber), "=", sub)
mult = (firstNumber * secondNumber)
print("The result of " + str(firstNumber), "*", str(secondNumber), "=", mult)
div = (firstNumber / secondNumber)
print("The result of " + str(firstNumber), "/", str(secondNumber), "=", div)
print()
yn = input("Continue using calculator? y/n ->")
if yn == "y":
continue
else:
print("Thanks for using my calculator!")
break
##Module to import##
# Get two numbers from user
# define functions for each operation
lowRange = int(input('lowRange:'))
highRange = int(input('highRange:'))
firstNumber = int(input('firstNumber:'))
def add(firstNumber, secondNumber, ):
return firstNumber + secondNumber
def sub(firstNumber, secondNumber, ):
return firstNumber - secondNumber
def mult(firstNumber, secondNumber, ):
return firstNumber * secondNumber
def div(firstNumber, secondNumber):
return firstNumber / secondNumber
# range function
def isinrange(lr, hr, n):
lr = lowRange
hr = highRange
n = firstNumber
if n > lr and n < hr:
return True
else:
return False
def scalc(p1):
astring = p1.split(",")
firstNumber = float(astring[0])
secondNumber = float(astring[1])
if astring[2] == "+":
add(firstNumber, secondNumber)
elif astring[2] == "-":
sub(firstNumber, secondNumber)
elif astring[2] == "*":
mult(firstNumber, secondNumber)
elif astring[2] == "/":
div(firstNumber, secondNumber)
return firstNumber, secondNumber
p1 = input("select two numbers and operator")
any help is appreciated.
Solution 1:[1]
The key to reducing redundancy is to look at the things you're doing over and over, and turn them into functions (or find an existing function that can do that type of thing).
Inputting numbers with error handling is the type of thing that makes sense to break out into its own function with its own while loop that will repeat until a valid number is entered.
You can also potentially make use of for loops and functools.reduce to eliminate some copying and pasting -- it doesn't make much of a difference in terms of the overall number of lines of code with only two variables, but it does eliminate duplication, and it allows you to very easily add a third variable by just changing a single line of code:
from functools import reduce
def input_range() -> range:
while True:
try:
r = range(
int(input("lowRange: ")),
int(input("highRange: ")) + 1
)
if not r:
raise ValueError("highRange must be greater than lowRange")
return r
except ValueError as e:
print(e)
def input_number(name: str, bound: range) -> int:
while True:
try:
n = int(input(f"{name}: "))
if n not in bound:
raise ValueError(
"You must type a number between lowRange and highRange"
)
return n
except ValueError as e:
print(e)
funcs = {
"+": int.__add__,
"-": int.__sub__,
"*": int.__mul__,
"/": int.__truediv__,
}
while True:
bound = input_range()
numbers = {
name: input_number(name, bound)
for name in ("firstNumber", "secondNumber") # try adding "thirdNumber"!
}
for name, number in numbers.items():
print(f"{name}={number}")
for symbol, func in funcs.items():
expr = symbol.join(map(str, numbers.values()))
result = reduce(func, numbers.values())
print(f"The result of {expr}={result}")
if input("Continue using calculator? y/n ->") != "y":
print("Thanks for using my calculator!")
break
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
