[Tutor] Why won't it enter the quiz? (off topic)

Jacob S. keridee at jayco.net
Fri Sep 30 02:33:41 CEST 2005

Wow! What an argument...
A couple of comments on the code

> {code}
> import random
> def add(a,b):
>    answer = a+b
>    guess = float(raw_input(a," + ",b," = "))

This is easier IMHO, but the same
guess = float(raw_input("%s+%s="%(a,b)))

>    return answer, guess
> num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
> num2 = random.choice(range(1,10))

Oh my.  Read the documentation on the random module.
Specifically random.randrange or even random.randint
Note: the difference between the two -- a <= result < b  as opposed to a <= 
result <= b

> while 1:
>    q = random.choice(range(15,31)) ### to choose the number of questions
>    cq = 1 ### To find the current question
>    correct = 0
>    while cq >= q: ### To find whether or not to end the quiz.

Of course, this has been corrected to   while cq <= q:

>        print cq
>        answer, guess = add(num1,num2)
>        if guess != answer:
>            print "Incorrect! The correct answer is: ",answer
>            cq += 1
>        elif guess == answer:
>            print "Correct!"
>            correct += 1
>            cq += 1
>    else:
>        print "Questions: ",q
>        print "Correct: ",correct
>        print "Percent Correct: ",(cq/q)*100

Okay, this is a problem -- Due to the integer division cq/q, Percent Correct 
will only display 0, ever

>        break
> print "Goodbye."

They probably won't see the stats because the program will execute the four 
print statements and immediately exit.  I suggest changing the last 
statement to

raw_input("Goodbye. Press enter to exit. ")

> {/code}

I have one more comment.  The code in the add function doesn't really seem 
to be that well grouped together ~ IOW, it seems like you defined a function 
just because you felt like you needed practice typing def something(args):

It seems much easier (in this case) to just leave the add() code in the 
actual main block. Does this make sense?

Oops.  I have two comments.  In add() (which I suggest removing) you define 
guess with float(...) whereas your answer is an integer.   (a+b)  So you may 
run into trouble with floating point precision.
For example. ~~Okay, I stand corrected, in my test, none (out of 0-100) gave 
me any trouble.

Hope this helps,
Jacob Schmidt 

More information about the Tutor mailing list