繁体   English   中英

我应该如何打破这个问题的循环?

[英]How should I break the loop in this problem?

问题:

我们必须创建一个游戏,用户在其中输入他们想要使用的铅笔数量。 通过创建一个循环来扩展您的程序。 每个玩家轮流取出铅笔,直到桌上剩下 0 支铅笔。 每次迭代都会打印 2 行:带有铅笔的行(竖线),现在轮到其打印NameX的轮次子字符串。


How many pencils would you like to use:
> 5
Who will be the first (John, Jack):
> John
|||||
John's turn:
> 2
|||
Jack's turn:
> 1
||
John's turn:
> 2

我的解决方案:

person = input("Who will be the first (John, Jack):")
print("|" * number_of_pencil)
print(f"{person}'s turn")

while number_of_pencil > 1:
    pencil = int(input())
    number_of_pencil -= pencil
    print("|" * number_of_pencil)
    if person == "John":
        print("Jack's turn")
        person = "Jack"
    else:
        print("John's turn")
        person = "John"

输出:

Who will be the first (John, Jack):> John
|||||
John's turn
> 2
|||
Jack's turn
> 1
||
John's turn
> 2

Jack's turn

需要的建议:我应该如何打破循环?

以下代码应该可以工作:

number_of_pencil = int(input("How many pencils would you like to use: "))
person = input("Who will be the first (John, Jack): ")
print("|" * number_of_pencil)

while number_of_pencil > 1:
    if person == "John":
        print("John's turn")
        person = "Jack"
    else:
        print("Jack's turn")
        person = "John"
    pencil = int(input())
    number_of_pencil -= pencil
    if number_of_pencil > 0:
      print("|" * number_of_pencil)

样本:

How many pencils would you like to use: 5
Who will be the first (John, Jack): John
|||||
John's turn
2
|||
Jack's turn
1
||
John's turn
2

我们可以将它们移到开头,这样它们只会在有剩余铅笔时运行,而不是在循环结束时显示是否轮到 John 或 Jack 的 print 语句。

此外,如果还有铅笔,我们只会打印剩余的铅笔数量。

我希望这有帮助! 请让我知道,如果你有任何问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM