[Tutor] Times Tables Program that constantly tells you that you are wrong!

Peter Otten __peter__ at web.de
Thu Aug 16 05:09:51 EDT 2018


Matthew Polack wrote:

> Hi All,
> 
> Thanks to your help I've nearly got my demo 'Times Tables' program fully
> working.
> 
> The last remaining issue is the program does not calculate the percentage
> right when you make mistakes...it just keeps giving a result of 100%.
> 
> I've looked and head scratched...and am not sure.
> 
> Can anyone figure out what is wrong with this code?

You increment the score no matter whether the answer is correct or not.

>     if response == answer:
>         score = int(score + 1)

>     else :
>         score= int(score + 1)

Random remarks

- Your code suffers from "over-globalisation". You only need to declare a 
variable global when you want to change it from within a function. Example:

x = 0

def show_x():
   # no global necessary
   print("x =", x)

def inc_x():
    global x
    x += 1

- You create a new Label in every call of viewXXX(). For long-running 
applications that will consume a lot of memory. You should instead create 
the label once and then update it

percentViewLab = Label(...)
percentViewLab.grid(...)

def viewPercent():
    percentViewLab["text"] = percentScore

- You convert integers to integers.

>        score = int(score + 1)

should better be written

         score = score + 1

or
         score += 1

- I rarely say that, but you have too many functions -- or rather you have 
written them in such a way that you need to call them in a special order. 
Personally I would omit the percentCheck function and the percentScore 
variable and rewrite viewPercent as

def viewPercent():
    percentViewLab["text"] = score/total*100

or if you want to keep the function

def get_percent_score():
    return score/total*100

def viewPercent():
    percentViewLab["text"] = get_percent_score()

With both approaches viewPercent() can never show an out-of-date value.





More information about the Tutor mailing list