gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:26:52 26 4
gpt4 key购买 nike

问题:

我们必须创建一个游戏,让用户输入他们想要使用的铅笔数量。通过创建一个循环来扩展您的程序。每个玩家轮流取出铅笔,直到 table 上剩下 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。

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

希望对您有所帮助!如果您有任何问题,请告诉我!

关于python - 我应该如何打破这个问题的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72919715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com