问题是:

我们必须创建一个游戏,用户输入他们想要使用的铅笔数量.


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

My solution:

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"

The output:

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

Jack's turn

Suggestion required:我该如何打破循环?

推荐答案

以下代码应起作用:

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

我们可以将打印语句移到开头,这样它们只会在有剩余铅笔的情况下运行,而不是在循环结束时显示是轮到约翰还是杰克.

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

我希望这有帮助!如果你有任何问题,请告诉我!

Python相关问答推荐

python中csv. Dictreader. fieldname的类型是什么?'

通过追加列表以极向聚合

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

如何在Python中解析特定的文本,这些文本包含了同一行中的所有内容,

在pandas中,如何在由两列加上一个值列组成的枢轴期间或之后可靠地设置多级列的索引顺序,

在matplotlib中重叠极 map 以创建径向龙卷风图

如何从一个维基页面中抓取和存储多个表格?

pyspark where子句可以在不存在的列上工作

我的浮点问题--在C++/Python中的试用

如何从另一个连接引用DuckDBPyRelation?

函数以表格和图形的形式输出

基于直方图箱的样本数据

为什么我不能在Sphinxcontrib-HttpExample中使用python来换行JSON属性?

如何从直接URL和间接URL中提取文件扩展名?

FlaskApp无法在Google Cloud Run上运行:服务不可用503错误

用动态规划法计算斐波那契曲线的命中次数

如何使用libclang';S Python绑定获取返回类型和参数类型的完全限定名?

PyCharm调试器控制台不自动完成在调试器控制台中创建的变量