Help me please urgently!

Ian Kelly ian.g.kelly at gmail.com
Sun Mar 15 12:10:33 EDT 2015


On Sun, Mar 15, 2015 at 9:43 AM, Jenny Hale <jhale7021 at gmail.com> wrote:
> Hi
>
> How would I do this?
> The teacher wants to keep track of the scores each member of the class obtains in the quiz. There are three classes in the school and the data should be kept separately for each class.

Is this a homework assignment? It looks like you already have a
solution or most of one. Do you have any specific question that you
need help with?

Since it's not clear to me what sort of help you're looking for, I've
added some constructive style comments below. It mostly looks good to
me.

> import random
> import operator
>
> MATHS_OPERATIONS = [
>     (operator.add, "+"),
>     (operator.mul, "*"),
>     (operator.sub, "-")
>     ]
>
> NUM_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

It's generally polite to your user if you accept additional variations
such as y/n. An easy way to do that is with the test
('yes'.startswith(val)) which will match the word 'yes' or any prefix
of it.

>         else:
>             print("Not a valid input (yes/no is expected)")
>
> if __name__ == '__main__':

This should all be moved into a function, and the body of the if
statement would then just be a call to the function. This way you
won't be polluting your global namespace with lots of variables that
should really be local in scope. It also makes code reuse easier -- if
another module wants to launch this script, all it has to do is import
this module and call the function.

>     name = input("What is your name?").title()
>     class_name = input("What is your Class? ")
>     print(name, ", Welcome to the Maths Test")
>
>     score = 0
>     for _ in range(NUM_QUESTIONS):
>         num1 = random.randint(1,100)
>         num2 = random.randint(1,100)
>         op, symbol = random.choice(MATHS_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)

This would probably be a bit cleaner with a formatted string, either
the % style or using str.format.  The former would look like this:

print("Well done, %s! You scored %d / %d." % (name, score, NB_QUESTIONS))

The latter is the new(er) hotness and would look like this:

print("Well done, {}! You scored {} / {}.".format(name, score, NB_QUESTIONS))

It's up to you (and your instructor) which style you prefer.

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

Another place where I would suggest a formatted string.

>     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")

input is going to wait for the user to press Enter, not "any key".



More information about the Python-list mailing list