OK!我得到的代码无法正常工作,以下是代码:
def abDucks (a,b):
while (a>1):
print(a, "Little Ducks swimming in the sea")
print("And if ",b," Little Ducks should accidentally drown")
print("There'll be ", (a-b), "Little Ducks swimming in the sea\n")
a=(a-b)
if (a<=1):
print(a, "Little Ducks swimming in the sea")
print("And if ",b," Little Ducks should accidentally drown")
print("There'll be no Little Ducks swimming in the sea\n")
我遇到的问题是它计为0然后会打印: 如果没有小鸭子不小心淹死了 没有小鸭子在海里游泳
请帮助
我从来没有得到无限循环大声笑:P 当我使用(8,2)
运行此代码时会发生这种情况8 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 6 Little Ducks swimming in the sea 6 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 4 Little Ducks swimming in the sea 4 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 2 Little Ducks swimming in the sea 2 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 0 Little Ducks swimming in the sea 0 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be no Little Ducks swimming in the sea
答案 0 :(得分:3)
您可以简洁地编写相同的代码,就像这样
def abDucks (a,b):
while (a - b >= 1):
print(a, "Little Ducks swimming in the sea")
print("And if ",b," Little Ducks should accidentally drown")
print("There'll be ", (a-b), "Little Ducks swimming in the sea\n")
a -= b
else:
print(a, "Little Ducks swimming in the sea")
print("And if ",b," Little Ducks should accidentally drown")
print("There'll be no Little Ducks swimming in the sea\n")
通过此更改,输出变为
8 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 6 Little Ducks swimming in the sea 6 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 4 Little Ducks swimming in the sea 4 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be 2 Little Ducks swimming in the sea 2 Little Ducks swimming in the sea And if 2 Little Ducks should accidentally drown There'll be no Little Ducks swimming in the sea