Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #87473 > unrolled thread

Help me please urgently!

Started byJenny Hale <jhale7021@gmail.com>
First post2015-03-15 08:43 -0700
Last post2015-03-15 13:44 -0400
Articles 4 — 4 participants

Back to article view | Back to comp.lang.python


Contents

  Help me please urgently! Jenny Hale <jhale7021@gmail.com> - 2015-03-15 08:43 -0700
    Re: Help me please urgently! Chris Angelico <rosuav@gmail.com> - 2015-03-16 03:00 +1100
    Re: Help me please urgently! Ian Kelly <ian.g.kelly@gmail.com> - 2015-03-15 10:10 -0600
    Re: Help me please urgently! Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-03-15 13:44 -0400

#87473 — Help me please urgently!

FromJenny Hale <jhale7021@gmail.com>
Date2015-03-15 08:43 -0700
SubjectHelp me please urgently!
Message-ID<43223410-538e-4834-82d4-98ab0702ae2d@googlegroups.com>
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.

Here is my code:

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
        else:
            print("Not a valid input (yes/no is expected)")

if __name__ == '__main__':
    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)

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

Could somebody here me please?

[toc] | [next] | [standalone]


#87474

FromChris Angelico <rosuav@gmail.com>
Date2015-03-16 03:00 +1100
Message-ID<mailman.392.1426435203.21433.python-list@python.org>
In reply to#87473
On Mon, Mar 16, 2015 at 2:43 AM, Jenny Hale <jhale7021@gmail.com> wrote:
> 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.
>

Thank you for being honest about this being course work.

So what's your code not doing correctly? You've shown us a pageful of
Python; I could point out problems like that your last line won't do
quite what it looks like, but that'd probably not what you're talking
about.

Be aware that you hopefully won't get your code written for you. What
you'll get is hints pointing you toward solving the problem yourself.
Ask with that in mind and you should be able to word up questions that
will help you with what you're stuck on. So have your best shot at it
yourself, then figure out what it is you're unable to do, and ask a
very specific question (or maybe several questions, as the case may
be); we're happy to help you to learn Python, but we won't simply give
you the answers so you can pass the course.

All the best!

ChrisA

[toc] | [prev] | [next] | [standalone]


#87477

FromIan Kelly <ian.g.kelly@gmail.com>
Date2015-03-15 10:10 -0600
Message-ID<mailman.395.1426435882.21433.python-list@python.org>
In reply to#87473
On Sun, Mar 15, 2015 at 9:43 AM, Jenny Hale <jhale7021@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".

[toc] | [prev] | [next] | [standalone]


#87480

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2015-03-15 13:44 -0400
Message-ID<mailman.398.1426441457.21433.python-list@python.org>
In reply to#87473
On Sun, 15 Mar 2015 08:43:32 -0700 (PDT), Jenny Hale <jhale7021@gmail.com>
declaimed the following:

>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 supposed to just be a grade book ("track the scores"), or (as
it seems by your code) also administer the quiz. And if it IS administering
the test, is it really fair that two students would get a different set of
questions (since you are using random so much). To make the grades fairly
comparable, all students should get the same set of problems to solve
(mixing up the order is a different matter).

	Will multiple students be taking this in parallel? Then you need to
figure out some way to do shared access to the grade book(s). If
sequential, do you really want a student to respond to that "view previous
results"?

	That is my main problem with the sample code -- you have mixed both the
teacher access (setting up the grade book, reviewing results) with the
student access (taking a randomly generated quiz).

	For a homework assignment, I'm probably getting a bit overly fancy
but... I'd produce three programs:

Generate Quiz (which creates a file, possibly lightly encrypted and binary)
of the questions -- that way every student sees the same set of questions
for fairness.

Take Quiz (uses the pregenerated quiz file to present questions. Also makes
sure the current student has not already taken the quiz, saves the score,
should also be encrypted)

Teacher Review (produces a report of the scores and student names, maybe
sorted by name or grade)

	Three programs, two data files (per class unless you want to share the
question pool across all classes and just keep the scores per class)
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web