Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program for random sum
#1
Hi,

I started learning Python yesterday. I'm trying to create a program that generates a sum of two random integers for the user to calculate. I want the code to generate a new calculation if the user chooses Yes after inputting the correct result and prompt the user to try again if the result is incorrect, but I can't figure out how to do it. Any hints, please? Thank you :)

This is what I have so far, but obviously wrong:

import random

def random_calculation():

    number1 = random.randint(1,100)
    number2 = random.randint(1,100)
    result = number1 + number2

    user_result = int(input(f"Calculate: {number1} + {number2} = "))

    if result == user_result:
        new_calculation = input("Correct! New calculation? (Y/N) ")
        if new_calculation == Y:
            random_calculation()
    else:
        while result != user_result:
            input(f"Incorrect. Try again. \nCalculate {number1} + {number2} = ")


random_calculation()
Reply
#2
Your main problem is that Y is an undefined variable. You probably want to test if the input == "Y". But there are more problems here.

The first time through your code you convert user input to an int. If the user makes a mistake your program asks the user to try again, but this time you don't save the input to a variable. result never changes, so you never break out of the incorrect loop.

Let's assume you fix this problem by modifying the code to look like this:
        while result != user_result:
            user_result = input(f"Incorrect. Try again. \nCalculate {number1} + {number2} = ")
This doesn't work either! The problem now is that "result" is an int and "user_result" is a str. When you initially ask for input you convert it to an int, so if the user guesses correctly the first time the program identifies this is a correct answer. If the user makes a mistake they get stuck in the "incorrect" loop again.

The obvious fix is to always convert input to an int, but obvious is not always right. How about instead of converting the input to an int you convert the result to a str?
import random
 
def random_calculation():
 
    number1 = random.randint(1,100)
    number2 = random.randint(1,100)
    result = str(number1 + number2)
 
    user_result = input(f"Calculate: {number1} + {number2} = ")
 
    if result == user_result:
        new_calculation = input("Correct! New calculation? (Y/N) ")
        if new_calculation == "Y":
            random_calculation()
    else:
        while result != user_result:
            user_result = input(f"Incorrect. Try again. \nCalculate {number1} + {number2} = ")
 
 
random_calculation()
There are good reasons for doing things in the non-obvious way. int(str) is a program killer. If str contains a letter it crashes. If str contains a decimal it crashes. If the user just presses Enter without typing anything it crashes. Since you are not using the result for anything other than comparing it to user_result it makes more sense to avoid the perils of int() and convert result to a str.

But there is still more wrong. Now your program loops until the user enters a correct answer. The program also allows doing another equation if the user guesses correctly the first time, but if the user makes a mistake the program exits as soon as they enter a correct answer.

A well designed program has functions that each perform well defined tasks. A reasonable test for "well defined" is writing a description of what the function does. If the description is more than a sentence or two you might need to redesign your function. Your random_calculation() function "Quizzes the user to solve an equation. If the user makes a mistake they are allowed to try again until entering a correct answer. After the user enters the correct answer the function asks the user if they would like to try another equation". This is too many things for one function to do. I would remove the "asks the user if they would like to try another equation" part and have that done outside the function.
Cristopher likes this post
Reply
#3
(Jan-15-2022, 03:21 PM)deanhystad Wrote: Your main problem is that Y is an undefined variable. You probably want to test if the input == "Y". But there are more problems here.

Thank you, I forgot to put quotes around Y, that is fixed now. However, if I enter an incorrect answer and then the correct answer, it still displays as incorrect. I know there's a problem, but I can't figure out where. Any help?
Reply
#4
You could break your code down into separate functions that have the responsibility to do just one thing.
you can make sure each function does what it should and then peice them together.
So you could have a function that returns the random numbers.
Two functions to get a valid user input (note you can refer to this https://python-forum.io/thread-18971.html)
Then create a function that loops using the other functions.
Reply
#5
Thanks deanhystad for your detailed answer. Thanks Yoriz for your help and the link.

(Jan-15-2022, 03:31 PM)deanhystad Wrote: I would remove the "asks the user if they would like to try another equation" part and have that done outside the function.

When you say "outside the function", do you mean creating another function and place it there?

The confusing part for me is that if I define the cases outside the function, Python doesn't recognize the variables (number1, number2, result and user_result) I defined earlier inside the function random_calculation(). Do I need to create two (or more) separate functions? If so, how do I piece them together? How do I create several functions with the same variables throughout?
Reply
#6
As well as being able to pass things into a function they also return things back.
def a_function(func_in):
    print(func_in)
    func_out = "I was returned from the function"
    return func_out


returned_from_func = a_function("I was passed to the function")
print(returned_from_func)
Output:
I was passed to the function I was returned from the function
Reply
#7
random_calculation() needs to know about number1, number2, result and user_result. None of this information is needed to determine if the user wants to run random_calculation() again. Strip down random_calulation() to only do one equation.
import random
 
def random_calculation():
    number1 = random.randint(1, 100)
    number2 = random.randint(1, 100)
    result = str(number1 + number2)
    while True:
        if input(f"Calculate: {number1} + {number2} = ") == result:
            print("Correct!")
            break
        else:
            print("Incorrect.  Try again.")

random_calculation()
And then think about how you can write a loop that will call random_calulation() again if the user types "Y" when prompted or quit looping if they type something else.
Cristopher likes this post
Reply
#8
I think I did it...

import random
  
def random_calculation():
    number1 = random.randint(1, 100)
    number2 = random.randint(1, 100)
    result = str(number1 + number2)
    while True:
        if input(f"Calculate: {number1} + {number2} = ") == result:
            print("Correct!")
            break
        else:
            print("Incorrect.  Try again.")
 
random_calculation()

while input("New calculation? (Y/N) ") == "Y":
    random_calculation()  
Thank you deanhystad, for your guidance. I just learned that "break" is used to stop a loop. Now, I'd like to make a version of this where the program chooses addition or subtraction at random. I'll give it a try...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Noob here. Random quiz program. Using a while loop function and alot of conditionals. monkeydesu 6 1,392 Sep-07-2022, 02:01 AM
Last Post: kaega2
  Random Dice roll program th3h0bb5 1 5,545 Oct-18-2016, 09:25 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020