HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Algorithm maths quiz + write to a text file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mathsfilequiztextwritealgorithm

Problem

Are there any ways I can clean this code up to make it more user-friendly?

```
import random #Random Function
import os

print("What is your name?") #Asking User Name
name = input().title() #.title() capitilises the first letter in each word, so when the name is printed in later code the first letter will always be capitilised.
class_name = input("Which class do you wish to input results for? ")
print (name, ", Welcome to the OCR Controlled Assessment Maths Test")
score = 0 #Set Score to 0
question = 0 #Set Question Number to 0
while question < 10: #After 10 Questions, it will stop asking the user questions.
operator = random.randint(1,3)#Addition,Multiplication,Subtraction
num1 = random.randint(1,25)#Random Number between 1 and 10 to be used in the questions
num2 = random.randint(1,25)#Random Number between 1 and 10 to be used in the questions
if operator == 1: #If Random Operator = 1, it will ask addition questions
print("What is", num1, "+", num2)
ans = num1 + num2

elif operator == 2:#If Random Operator = 2, it will ask multiplication questions
print("What is", num1, "*", num2)
ans = num1 * num2

else: #If Random Operator = 3/Else, it will ask subtraction questions.
print("What is", num1, "-", num2)
ans = num1 - num2

while True:
try:
user_ans = int(input()) #The Answer the user inputs to the question asked
except ValueError: #When anything but a interger is inputted.
print ("That is not a valid answer")
continue #Dosen't print Invalid Code Error
else:
break

if user_ans == ans: #If user answer matches that of the question
print("Correct")
score += 1

else: #If user answer dosen't match that of a question.
print("Incorrect")

question += 1 #When a question is answered, it will +1 until it equals 10 at which point it will stop.

print("Well done", name, "you scored", score, "/10") #Print Final Score o

Solution

A few advices :

-
Python has a code style called PEP8. It is a worth reading. Also, you'll find various tools to check that your code is PEP8-compliant like pep8. You'll also find various other tools to check the quality of your code : pyflakes, pychecker, pylint, etc.

-
avoid useless comments. It can be tempting to comment every line you write as you start programming. However, what you are doing adds more noise that it actually helps. As a rule of thumb, "Code Tells You How, Comments Tell You Why". Also, comments are easy to get out of sync with the code (you have places where your code says "25" and the comment says "10", how confusing).

-
you can add an argument to input so that you don't have to call print before.

-
your while question

-
you should try to use the
with keyword whenever you handle files. If you do so, you don't have to call close explicitly.

-
you should try to ask yourself if your variable describe how you use it. For instance,
class_name is a proper name for what you do at the beginning. However, it doesn't sound like a proper filename. You could simple create a new variable : filename = class_name + ".txt"

-
avoid useless tests : in
elif viewscore != "yes".lower(), the condition will always be true. You could simply write else.

-
calling
lower() on "yes" doesn't seem really interesting does it ?

Now, for more "complicated" advices.

You can try to split the logic in small reusable units like functions (or classes). For instance, you could write :

def get_int_input():
    while True:
      try:
        return int(input())
      except ValueError:
        print ("That is not a valid answer")


Instead of having some code to handle the different possible operations, you could have a structure containing the relevant information : the symbol to be printed and the corresponding operation. You could use a list of tuple to store everything and then, it's easy to pick one at random and use it :

import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

for _ in range(10):
    num1 = random.randint(1,25)
    num2 = random.randint(1,25)
    op, symbol = random.choice(OPERATIONS)
    print("What is", num1, symbol, num2)
    if get_int_input() == op(num1, num2):
        print("Correct")
        score += 1
    else:
        print("Incorrect")


If you ever need to add one, it's quite easy.

It is also a good habit to use a
if __name__ == '__main__':` guard.

Similarly to what we've done to get an integer input, we can define a function to get a boolean input.

The final code looks like :

import random
import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

NB_QUESTIONS = 10

def get_int_input(prompt=''):
    while True:
      try:
        return int(input(prompt))
      except ValueError:
        print("Not a valid input (integer is expected)")

def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            print("Not a valid input (yes/no is expected)")

if __name__ == '__main__':
    name = input("What is your name?").title()
    class_name = input("Which class do you wish to input results for? ")
    print(name, ", Welcome to the OCR Controlled Assessment Maths Test")

    score = 0
    for _ in range(NB_QUESTIONS):
        num1 = random.randint(1,25)
        num2 = random.randint(1,25)
        op, symbol = random.choice(OPERATIONS)
        print("What is", num1, symbol, num2)
        if get_int_input() == op(num1, num2):
            print("Correct")
            score += 1
        else:
            print("Incorrect")

    print("Well done", name, "you scored", score, "/", NB_QUESTIONS)

    filename = class_name + ".txt"

    with open(filename, 'a') as f:
        f.write(str(name) + " : " + str(score) + '\n')

    if get_bool_input("Do you wish to view previous results for your class"):
        with open(filename, 'r') as f:
            print(f.read())
    else:
        input ("Press any key to exit")

Code Snippets

def get_int_input():
    while True:
      try:
        return int(input())
      except ValueError:
        print ("That is not a valid answer")
import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

for _ in range(10):
    num1 = random.randint(1,25)
    num2 = random.randint(1,25)
    op, symbol = random.choice(OPERATIONS)
    print("What is", num1, symbol, num2)
    if get_int_input() == op(num1, num2):
        print("Correct")
        score += 1
    else:
        print("Incorrect")
import random
import operator

OPERATIONS = [
    (operator.add, "+"),
    (operator.mul, "*"),
    (operator.sub, "-")
    ]

NB_QUESTIONS = 10

def get_int_input(prompt=''):
    while True:
      try:
        return int(input(prompt))
      except ValueError:
        print("Not a valid input (integer is expected)")

def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            print("Not a valid input (yes/no is expected)")

if __name__ == '__main__':
    name = input("What is your name?").title()
    class_name = input("Which class do you wish to input results for? ")
    print(name, ", Welcome to the OCR Controlled Assessment Maths Test")

    score = 0
    for _ in range(NB_QUESTIONS):
        num1 = random.randint(1,25)
        num2 = random.randint(1,25)
        op, symbol = random.choice(OPERATIONS)
        print("What is", num1, symbol, num2)
        if get_int_input() == op(num1, num2):
            print("Correct")
            score += 1
        else:
            print("Incorrect")

    print("Well done", name, "you scored", score, "/", NB_QUESTIONS)

    filename = class_name + ".txt"

    with open(filename, 'a') as f:
        f.write(str(name) + " : " + str(score) + '\n')

    if get_bool_input("Do you wish to view previous results for your class"):
        with open(filename, 'r') as f:
            print(f.read())
    else:
        input ("Press any key to exit")

Context

StackExchange Code Review Q#79350, answer score: 9

Revisions (0)

No revisions yet.