【问题标题】:Zero Division in Python preventing program from runningPython中的零除法阻止程序运行
【发布时间】:2012-08-19 19:20:41
【问题描述】:

我仍在努力完成多项选择测验计划。我快到了。只有几个错误仍然可以解决。该程序会记录您正确、错误的问题数量和当前百分比。但是,我的程序不会运行,因为最初,用户没有回答任何问题。因此,它们的正确率为 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 "\n\n(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 "\n\n\n"
    start()

stat_tracking()

我不确定是否有解决此问题的方法,或者我是否可能做错了。任何和所有的帮助将不胜感激。谢谢。

【问题讨论】:

  • 我忍不住注意到你的字符串的一些内容。 def 可以在课堂之外使用。 self 只是一个常规名称;在实例方法中,无论第一个参数是当前实例,无论它的名称是什么。如果函数是类方法、静态方法或根本不在类中,情况会有所不同。模块也可以有属性,严格来说(如果我理解正确的话),方法也存储为属性;它们恰好是可调用的,因此可以附加括号来评估它们。

标签: python python-2.7 division divide-by-zero


【解决方案1】:

当没有问题得到回答时,打印出来没有任何意义。为除数 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 放在代码的开头,那么所有floats 都是不必要的。

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) 

【讨论】:

  • 字符串插值运算符真的被弃用了吗?你有参考吗?谷歌不是很有帮助。
  • str.format 的文档说“这种字符串格式化方法是 Python 3 中的新标准,应该优先于新代码中字符串格式化操作中描述的 % 格式化。”所以我想它在技术上并没有被弃用,但它是不鼓励的。 Str.format 无论如何都要好得多。 (更灵活,更易读,在常见情况下更容易使用,作为函数更容易使用。)
  • 我完全同意 str.format 更容易使用,感谢您查找 :)
【解决方案2】:

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

如果以后出现问题,您可以像这样事先检查零除法

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

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

在你修复了你可能发现的错误之后,最好带着你的代码去http://codereview.stackexchange.com 获得一些一般性的编码建议。

【讨论】:

  • 那个 if/else 语句会去哪里?进入 stat_tracking()?
  • 它应该放在您放置代码以更新百分比的任何位置。 (您目前似乎没有这样做..)但是stat_tracking 可能是个好地方。
  • 肯定的。不确定我是否提到了这一点,但我使用 Python 编码才不到一个月。在我前进的过程中学习新事物。谢谢你的建议。
【解决方案3】:

将第 9 行改为:

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

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多