For the following code, I have trouble improving it.
I need to write a function getExpression(level, operator) which has one integer parameter representing a level and another string parameter representing the arithmetic operator. The function generates a string expression as well as the answer, based on the requirements for the level. Both the string expression and the result value are returned.
import random
def getExpression(level, operator):
# Generate operands based on the level
if operator == "+":
# Addition
if level == 1:
num1 = random.randint(1, 9) # Single digit operand
num2 = random.randint(1, 9)
elif level == 2:
num1 = random.randint(10, 99) # Two digit operand
num2 = random.randint(10, 99)
elif level == 3:
num1 = random.randint(100, 999) # Three digit operand
num2 = random.randint(100, 999)
elif level == 4:
num1 = random.randint(1000, 9999) # Four digit operand
num2 = random.randint(1000, 9999)
elif level == 5:
num1 = random.randint(10000, 99999) # Five digit operand
num2 = random.randint(10000, 99999)
# Return the expression and result
result = num1 + num2
expression = f"{num1} + {num2} = "
elif operator == "-":
# Subtraction
if level == 1:
num1 = random.randint(2, 9) # Single digit operand
num2 = random.randint(1, num1-1) # Ensure num2 is smaller than num1
elif level == 2:
num1 = random.randint(10, 99) # Two digit operand
num2 = random.randint(1, num1-1) # Ensure num2 is smaller than num1
elif level == 3:
num1 = random.randint(100, 999) # Three digit operand
num2 = random.randint(1, num1-1) # Ensure num2 is smaller than num1
elif level == 4:
num1 = random.randint(1000, 9999) # Four digit operand
num2 = random.randint(1, num1-1) # Ensure num2 is smaller than num1
elif level == 5:
num1 = random.randint(10000, 99999) # Five digit operand
num2 = random.randint(1, num1-1) # Ensure num2 is smaller than num1
# Return the expression and result
result = num1 - num2
expression = f"{num1} - {num2} = "
elif operator == "*":
# Multiplication
if level == 1:
num1 = random.randint(2, 9) # Avoid starting with 1
num2 = random.randint(2, 9)
elif level == 2:
num1 = random.randint(10, 99)
num2 = random.randint(2, 9)
elif level == 3:
num1 = random.randint(100, 999)
num2 = random.randint(2, 9)
elif level == 4:
num1 = random.randint(1000, 9999)
num2 = random.randint(2, 9)
elif level == 5:
num1 = random.randint(10000, 99999)
num2 = random.randint(2, 9)
# Return the expression and result
result = num1 * num2
expression = f"{num1} * {num2} = "
return expression, result