【发布时间】: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()
【问题讨论】:
-
请修复您的代码 - 有些在您的粘贴中丢失了。例如类声明。