墙上有99瓶啤酒

时间:2016-06-07 03:24:38

标签: python-3.x syntax-error

我是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()

1 个答案:

答案 0 :(得分:0)

首先,你不需要这个:

    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.