我现在在我的大学里学习Python初学者课程。我的家庭作业的一部分是创建一个类似于著名的儿童歌曲99瓶汽水的程序。任务是:
有道理吧?所以,我的代码是:
#Bottles of Pop on the Wall
#User inputs a number to start with
#Program returns with singing the popular song down to 0
#
print("Bottles of Pop on the Wall Program")
userBottle = int(input("How many bottles? "))
bottleCount = userBottle
while bottleCount > 1:
newBottle = userBottle - 1
bottleCount -= 1
if bottleCount > 99:
print("ALERT: no more than 99 bottles allowed, reverting to 99 bottles")
userBottle = 99
bottleCount = 99
newBottle = 99
print(userBottle , "bottles of pop on the wall, ", userBottle , "bottles of pop" ,
"\ntake one down, pass it around, " , newBottle , "bottles of pop on the wall")
userBottle -= 1
if bottleCount == 1:
print(userBottle , "bottle of pop on the wall, ", userBottle , "bottle of pop" ,
"\ntake one down, pass it around, " , "no bottles of pop on the wall")
input("\nThank you for playing! Press Enter to exit.")
因此,如果用户输入任何低于100的数字,程序就可以完美地工作。但是,如果用户输入任何高于99的内容,那就是我遇到问题的地方。在
会发生的是循环将运行到1,但不会结束。它将重复最后一次,并返回:
^{pr2}$显然这是不正确的。我的循环有什么问题,所以我可以确保当用户输入大于99的数字时不会发生这种情况?在
非常感谢你,我非常感谢你的帮助!在
看起来你有别名问题。在
在循环外,您要求用户输入一个数字,假设他们输入101,然后设置
bottleCount = userBottle
。然后在循环内部,将userBottle
的值重置为99。但请注意以下几点:以下是你的程序。您可能已更改userBottle值,但尚未更改bottleCount值。在
我们要做的是编写一个函数,以一种可控的方式获取userBottle值,该函数只返回它的lef,直到值正确为止。例如:
^{pr2}$你应该用一个变量来跟踪瓶子的数量
下一步,您应该使用格式字符串和
^{pr2}$.format
方法。例如这样可以避免在瓶子上循环。它使用列表理解来代替:
样本输出:
^{pr2}$我擅自修改了这首歌的最后一行。你喝了0瓶汽水后,我觉得再从墙上拿一瓶是没有意义的。如果你愿意,你可以很容易地把它改回来。在
相关问题 更多 >
编程相关推荐