【问题标题】:Coin Class HW assignment硬币类硬件分配
【发布时间】:2021-12-08 21:00:58
【问题描述】:

所以我正在为班级做一个投币类程序,而直接来自书中的这段代码在 Pycharm 和 VSC 中给了我错误。我已经重读了 10 次,找不到让程序运行的错误。试图弄清楚我是否遗漏了什么,或者示例源代码已关闭。


import random


# The Coin Class simulates a coin that can be flipped

class coin:
    def __init__(self):
        side.up = 'Heads'

    # Side up data attribute w/ heads

    # The Toss generates a random number in
    # the range of 0 - 1. If the number is 0, then side up is heads, otherwise side up is tails

    def toss(self):

        if random.randint(0, 1) == 0:
            self.sideup = 'Heads'
        else:
            self.sideup = 'Tails'

    # The get_sideup method returns the value referenced by sideup

    def get_sideup(self):
        return self.sideup

    # The main function


def main():
    # create an object from the coin class
    my_coin = coin()

    # Display that side facing up
    print('This side is up:', my_coin.get_sideup())

    # Toss Coin
    print('I am tossing the coin . . .')
    my_coin.toss()

    # Display the side of the coin that is facing up
    print('This side is up:', my_coin.get_sideup())

    # Call the main function
main()
``

【问题讨论】:

  • 您应该已经收到一条类似于NameError: name 'side' is not defined. 的错误消息,将__init__ 中的side.up = 'Heads' 更改为self.sideup = 'Heads'
  • 请注意,生成的错误消息是问题描述的一个组成部分,应该包含在您的问题中。更好的是,学习如何阅读它们是一项基本技能,这样您就可以独立调试程序。

标签: class debugging random syntax coin-flipping


【解决方案1】:

您有一个变量 self 等于空,并且您正试图访问它的一个名为“up”的属性

    def __init__(self):
        side.up = 'Heads'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多