Here is what I need coded:
- Detect user input for the words: "add" and "sub" aka subtraction.
- If the wrong answer is given, it should re-ask the question.
- If the user chooses either, it should generate two numbers from 1-9, number 1 >= number 2, and the user should be asked the answer.
- If the answer is correct, it should move to the next round (our teacher said there must be 5 rounds, at each end of the round the code should ask the user to type "add" or "sub" again.
- If the user gives the wrong answer, it should re-ask the question.
- The code ends when all 5 rounds are done, or if the user types "end" at any time with a message saying "Goodbye".
My code is:
import random
i = 1
while i < 6:
answer1 = input("Hello, please type \"add\" for adding, or \"sub\" for subtracting")
first_number = random.randrange(1, 9)
second_number = random.randrange(1, first_number)
one = str(first_number)
two = str(second_number)
if answer1 == "add":
the_answer = first_number + second_number
the_answer_actual = str(the_answer)
user_answer = int(input(one + " + " + two + " = "))
if the_answer == user_answer:
print("The answer is correct!")
i += 1
elif the_answer != user_answer:
print("Wrong answer. The correct answer was " + the_answer_actual)
i += 1
else:
continue
elif answer1 == "sub":
the_answer = first_number - second_number
the_answer_actual = str(the_answer)
user_answer = int(input(one + " - " + two + " = "))
if the_answer == user_answer:
print("The answer is correct!")
i += 1
elif the_answer != user_answer:
print("Wrong answer. The correct answer was " + the_answer_actual)
i += 1
else:
continue
elif answer1 == "end" or i < 6:
print("Goodbye.")
break
else:
pass
======================================================================== Problem: This error code appears when the 5th round is over:
- Traceback (most recent call last):
-File "C:\Users\kingh\PycharmProjects\pythonProject\main.py", line 8, in
- second_number = random.randrange(1, first_number)
- File "C:\Users\kingh\AppData\Local\Programs\Python\Python39\lib\random.py", line 316, in randrange
- raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (1, 1, 0)
passis used as a placeholder,continuemight be more appropriate for theelseclause. - TekkSparrowanswer1have something likefunction_selction, instead ofanswer2haveactual_solution, and instead ofans2haveactual_solution_string. It makes it less confusing for us to understand what is happening as we don't need to think 'wait was ans2 the string or the int, what even is ans2??'. It will also make it easier for you to work on your own code - Maritn Ge