Python中的Zero Division阻止程序运行



我仍在努力学习多项选择题测试程序。我快到了。只有几个bug还没解决。该程序会记录你答对、答错的问题数量以及当前的百分比。但是,我的程序不会运行,因为最初,用户没有回答任何问题。因此,它们的正确率为NULL%。我的代码如下:

import random
import sys
import os
import math
right_answer_total = float(0)
wrong_answer_total = float(0)
answer_total = float(right_answer_total + wrong_answer_total)
percentage = 100 * (float(right_answer_total) / float(answer_total))
word_drills = {'class': 'Tell Python to make a new kind of thing.',
               'object': 'Two meanings: the most basic kind of thing, and any instance of some thing.',
               'instance': 'What you get when you tell Python to create a class.',
               'def': 'How you define a function inside a class.',
               'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.',
               'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.',
               'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.',
               'attribute': 'A property classes have that are from composition and are usually variables.',
               'is-a': 'A phrase to say that something inherits from another, as in a Salmon *** Fish',
               'has-a': 'A phrase to say that something is composed of other things or has a trait, as in a Salmon *** mouth.'}

def start():
    # For loop that creates a list named keys. It grabs 3 random keys from the dictionary word_drills
    keys = [x for x in random.sample(word_drills, 3)]
    # User is presented with a question. A value from the previous randomly selected keys is selected as the 'question'
    correctanswer = word_drills[random.choice(keys)]
    print "Question: ", correctanswer 
    # Set the variables key1, key2, & key3 to the 3 keys in the list 'keys'
    key1, key2, key3 = keys[0], keys[1], keys[2]
    # User is presented with 3 choices.
    print "nn(a)%s   (b)%s   (c)%s" % (key1, key2, key3)
    a, b, c = word_drills[key1], word_drills[key2], word_drills[key3]
    selection = raw_input("> ")
    print selection
    if selection == "a":
        if a == correctanswer:
            print "That's correct!"
            answered_correctly()
        else:
            print "I'm sorry, that is incorrect..."
            not_answered_correctly()
    elif selection == "b":
        if b == correctanswer:
            print "That's correct!"
            answered_correctly()
        else:
            print "I'm sorry, that is incorrect..."
            not_answered_correctly()
    elif selection == "c":
        if c == correctanswer:
            print "That's correct!"
            answered_correctly()
        else:
            print "I'm sorry, that is incorrect..."
            not_answered_correctly()
    else:
        print "That is not a valid selection."
        exit(0)
def answered_correctly():
    global right_answer_total
    right_answer_total += 1
    stat_tracking()
def not_answered_correctly():
    global wrong_answer_total
    wrong_answer_total += 1
    stat_tracking()
def stat_tracking():
    os.system('cls' if os.name=='nt' else 'clear') 
    print "-" * 37
    print "|         Stat Tracking             |"
    print "-" * 37
    print "| Correct | Incorrect |  Percentage  |"
    print "-" * 37
    print "|    %d    |     %d     |     %d %%     |" % (right_answer_total, wrong_answer_total, percentage) 
    print "-" * 37
    print "nnn"
    start()
stat_tracking()

我不确定是否有解决办法,或者我是否做错了。如有任何协助,我们将不胜感激。谢谢

在没有回答任何问题的情况下,没有任何有意义的内容可以打印出来。添加除数为0的特殊检查,然后打印出100%,或者只打印出N/a或其他内容。

此外,这里还有一些关于代码的提示。

right_answer_total = float(0)
wrong_answer_total = float(0)
answer_total = float(right_answer_total + wrong_answer_total)
percentage = 100 * (float(right_answer_total) / float(answer_total))

如果将from __future__ import division放在代码的开头,那么所有这些float都是不必要的。

print "|    %d    |     %d     |     %d %%     |" % (right_answer_total, wrong_answer_total, percentage) 

不赞成使用字符串插值运算符。如果不需要Python 2.5兼容性,请使用str.format

print "|    {}    |     {}     |     {} %     |".format(right_answer_total, wrong_answer_total, percentage) 

由于在启动时用户还没有回答任何问题,您可以将其初始设置为0

如果以后出现问题,你可以像一样提前检查零除法

if answer_total != 0:
    percentage = 100 * (float(right_answer_total) / float(answer_total))
else:
    percentage = 0.0

您还可以考虑使用浮点文字(如0.0)来初始化变量,而不是使用float函数来转换int。

在你修复了你可能发现的错误之后,去http://codereview.stackexchange.com使用您的代码来获得一些通用的编码建议。

将第9行更改为:

percentage = 100 * (float(right_answer_total) / float(answer_total)) if (right_answer_total>0 and answer_total >0) else 0

最新更新