【问题标题】:99 Bottles of Beer on the Wall墙上有 99 瓶啤酒
【发布时间】:2016-10-06 19:14:51
【问题描述】:

我是 Python 的初学者。我有一个学校项目,要制作一个可以制作歌曲“墙上的 99 瓶啤酒”的程序

我想问一下,当我输入一个非整数值(例如一个字符串)时,如何让它显示一个错误语句。

还有如何避免这个错误:

Traceback (most recent call last):
  File "C:\Users\skyfi\Desktop\Intro to Com. Prog. Notes\Chapter 11\zheng_tianyu_assignment4_part1.py", line 42, in <module>
    solution.song()
  File "C:\Users\skyfi\Desktop\Intro to Com. Prog. Notes\Chapter 11\zheng_tianyu_assignment4_part1.py", line 9, in song
    while int(i) > 0:
ValueError: invalid literal for int() with base 10: 'no more'

感谢您的帮助!

    def __init__(self):
        self.num = input("Input number of beer: ")

    def song(self):
        i = int(self.num)
        if i == 0:
            print("No more beers on the wall.")
        while int(i) > 0:
            for i in range(i, 0, -1):
                bottle = "bottles"

                if i == 1:
                    bottle = "bottle"

                if i >= 0:
                    print("{0} {1} of beer on the wall, {0} {1} of beer.".format(i, bottle))

                    i = i - 1

                if i == 1:
                    bottle = "bottle"

                if i == 0:
                    i = str(i)
                    i = "no more"
                    bottle = "bottles"

                print("Take one down, pass it around, {0} {1} of beer on the wall.".format(i, bottle))
                print(" ")




        if i < 0:
            print("Invalid input!")


solution = Assignment4Part1()

solution.song()

【问题讨论】:

  • 请修复您的代码 - 有些在您的粘贴中丢失了。例如类声明。

标签: python-3.x syntax-error


【解决方案1】:

首先,你不需要这个:

    while int(i) > 0:
          ^^^

您的 i 已经是一个 int。

如果您想捕获整数覆盖失败的错误,您需要将转换包装在 try/except 块中:

try:
   i = int(self.num)
except ValueError:
   # Your error handling code goes here
   # Note: i will have no value assigned.

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2021-04-27
    • 2018-07-17
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    相关资源
    最近更新 更多