问题:
我们必须创建一个游戏,让用户输入他们想要使用的铅笔数量。 通过创建一个循环来扩展您的程序。每个玩家轮流取出铅笔,直到 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。
此外,如果还有铅笔,我们只会打印剩余铅笔的数量。
希望对您有所帮助!如果您有任何问题,请告诉我!
https://stackoverflow.com/questions/72919715/
相关文章:
sass - 当我在汇总中使用 scss 时出现意外字符 '@'(请注意,您需要插件才能导入非 Ja
reactjs - 在进行客户端查询时,我应该如何为 Github graphql API 提供身份
python - 为什么这两种计算总和的方法会产生不同的运行时间
python - 同时从两列中减去值( Pandas , python )
Python 修补类 - 方法 return_value 返回 MagicMock
windows - 为什么 powershell 说 cl.exe 不被识别?
reactjs - eslint 无法加载配置 "react-app"以从中扩展