I am learning python from CS106. Please review my code for Khan Sole Academy, I think my code not efficient. Please add critique and advice for beginner like me.

About Code

Generate 2 random numbers and add those numbers. If the user supplied answer is correct, row will increase by 1, goal is 3. If answer is false, row will be reset to zero.

Question From Assignment CS106

Your program should be able to generate simple addition problems that involve adding two 2-digit integers (i.e., the numbers 10 through 99). The user should be asked for an answer to each problem. Your program should determine if the answer was correct or not, and give the user an appropriate message to let them know. Your program should keep giving the user problems until the user has gotten 3 problems correct in a row.
(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)

   import random

MIN_NUM = 10
MAX_NUM = 99
row = 0

def main():
    Pre Condition: Generate random number. Additional num 1 and num 2
    Post Condition : Check user answers. If answer correct add row, if incorrect reset row to zero 
    row = 0
    while row < 3:
        # number generator
        num_1 = random.randint(MIN_NUM, MAX_NUM)
        num_2 = random.randint(MIN_NUM, MAX_NUM)
        print("What is " + str(num_1) + " + " + str(num_2) + " ?")
        total = num_1 + num_2
        #user answer
        user_input = int(input("Your answer: "))
        # Check user answer
        # if answer is incorrect, reset row to zero
        if user_input == total:
            row += 1
            print("Correct!  You've gotten " + str(row) +" correct in a row ")
            print("Incorrect. The expected answer is " + str(total))
            row = 0    

if __name__ == "__main__":

1 Answer 1


Actually, your code is efficient - it does exactly what it is supposed to do, and does not take any extra steps.

There are a few other issues, of the kind that are expected from a new coder in the process of learning, so here are some tips:

Global row variable

In Python, if you declare a variable outside of a function and then one with the same name inside a function (by assigning it value, as you do with row), you create a new variable, that "overshadows" the global one.

Basically, the top row in you code is never used, instead, main has its own local copy.

But that is ok, because you don't need a global row variable any way.
As a general practice it is best to avoid global variables completely.
There are very few cases where they are needed, especially in object oriented languages like Python.

String formatting

When you want to compose a string from multiple parts, including values in variables you should use formatting instead of string concatenation with '+'.

It is a more robust method allowing for prettier output, and makes your code more readable and more convenient to modify should the need arise.
Also, if you are putting together a lot of parts, this will be more efficient.

If you are using Python 3.6 or newer, you can do this:

print(f"What is {num_1} + {num_2} ?")
print(f"Correct!  You've gotten {row} correct in a row.")

If you are on an older version of Python, you can do this:

print("What is {} + {} ?".format(num_1, num_2))
print(f"Correct!  You've gotten {} correct in a row.".format(row))

As you can see, you no longer have to convert numbers to strings manually, the formatting function will do it for you!

Pay attention to hints in questions

You have used constants for range of random numbers, but not for the maximum number of correct answers in a row.

The question almost requires you use a constant by saying:

(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)

In general, numbers that have meaning but are written as is directly in the code (like the number of correct answers) are called "magic numbers" and are considered bad practice.

Just add at the top:


And use MAX_IN_ROW everywhere else in the code you need to check this value.

Input validation

This may be an advanced topic you have not covered yet, but as a rule of thumb all programs must guard against bad or invalid user input.

Some questions, especially on time constrained exams tell you to omit such checks, but if not explicitly instructed to do so, and if you can, you should check all input before using it.

For this question, exception handling would be appropriate:

    user_input = int(input("Your answer: "))
except ValueError:
    print("Invalid answer! You must type a positive decimal number.")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.