Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How should I break the loop in this problem?

The problem:

We have to create a game, where a user inputs the number of pencils they want to use.
Expand your program by creating a loop. Each player takes turns removing pencils until 0 pencils remain on the table. Each iteration prints 2 lines: lines with pencils (vertical bars) and whose turn is now by printing the NameX‘s turn substring.


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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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: How should I break the loop?

>Solution :

The following code should work:

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)

Sample:

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

Instead of having the print statements indicating whether or not it is John or Jack’s turn at the end of the loop, we can move them to the beginning so they will only run when there are remaining pencils.

Additionally, we will only print the number of pencils remaining if there are pencils left.

I hope this helped! Please let me know if you have any questions!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading