LucidKoder
LucidKoder

Reputation: 1

How to add a while loop within a while loop in Python?

I have been working on a very simple Python code that is basically the old Rock Paper Scissors Game.

Currently, when the user inputs anything outside of the choices (Rock, paper, scissors), The prompt will keep on asking the user for an input in a while loop until they choose one of the options. (rock, paper, or scissors).

Now I want to implement the same exact idea when I ask them for another input down the line when I ask (Do you want to play again? Y/N).

I want the code to continue if the answer is Y. I want the code to print (Thanks for playing) when the answer is N. But I want the input to be asked continuously in a while loop if the answer is anything other than Y or N (for example a typo).

Example:

User inputs = Y Code = Continues to ask the first input (What is your choice? (Rock, paper, or scissors?): )

User inputs = N Code = prints (Thanks for playing!) and the loop is escaped

User inputs = H (anything other than Y or N) code = prints(Please enter a valid response) and asks the prompt again (Do you wish to play again? Y/N?:

Here is the code so far (from Bro Code on YouTube)

options = ("rock", "paper", "scissors")
running = True

while running:

    player = None
    computer = random.choice(options)

    while player not in options:
        player = input("Enter a choice (rock, paper, scissors): ")

    print(f"Player: {player}")
    print(f"Computer: {computer}")

    if player == computer:
        print("It's a tie!")
    elif player == "rock" and computer == "scissors":
        print("You win!")
    elif player == "paper" and computer == "rock":
        print("You win!")
    elif player == "scissors" and computer == "paper":
        print("You win!")
    else:
        print("You lose!")

    if not input("Play again? (y/n): ").lower() == "y":
        running = False

print("Thanks for playing!")

I tried creating a True False variable and creating another while loop but since I'm a beginner, I had massive indentation errors and the code didnt work.

Upvotes: 0

Views: 126

Answers (3)

Tim Roberts
Tim Roberts

Reputation: 54897

Here's an example of moving the input validation into a function:

import random

options = ("rock", "paper", "scissors")

def get_input( prompt, valid ):
    while True:
        value = input(prompt).lower()
        if value in valid:
            return value
        print("Invalid reponse.  Choose from", valid)

while True:

    computer = random.choice(options)

    player = get_input("Enter a choice (rock, paper, scissors): ", options)

    print(f"Player: {player}")
    print(f"Computer: {computer}")

    if player == computer:
        print("It's a tie!")
    elif player == "rock" and computer == "scissors":
        print("You win!")
    elif player == "paper" and computer == "rock":
        print("You win!")
    elif player == "scissors" and computer == "paper":
        print("You win!")
    else:
        print("You lose!")

    if get_input("Play again? (y/n): ", ('y','n')) != 'y':
        break

print("Thanks for playing!")

Now that function can be reused in other modules. You could even simplify it by making yes/no the default:

def get_input( prompt, valid='yn' ):
    while True:
...
    if get_input("Play again? (y/n): ") != 'y':

Upvotes: 0

richard
richard

Reputation: 36

you can nest while loops, but anything more than two deep and I get confused. after that point write an input function.

import random


mapping = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'}
options = list(mapping.keys())

while True:
    player = None
    computer = random.choice(options)
    while player not in options:
        player = input("enter a choice (rock, paper, scissors): ")
    
    print(f"player: {player}")
    print(f"computer: {computer}")
    
    if computer == player: print("it's a tie!")
    elif computer == mapping[player]: print("computer win!")
    else: print("you win!")
    
    # walrus operator sets variable then tests condition, Python 3.8+ only
    while not (retry := input("Play again? (y/n): ").lower()) in ('y', 'n'):
        continue # ask again until we get y/n
    if retry == 'n':
        print("thanks for playing!")
        break

Upvotes: 0

Quizzer515SY
Quizzer515SY

Reputation: 70

Having nested while loops isn't a great practice to have because as your code gets bigger, the loops get more and more difficult to debug. In small programs like these though, it doesn't really matter.

You can copy and paste the code below, it should work. All I did is add another while loop structured exactly the same as the one that checks if you typed "rock, paper, scissors".

Regarding indentation: most code editors will allow you to select many lines of code. If you then press tab, it should indent all the lines by the same amount. Hope this was helpful!

-Quizzer515SY

import random

options = ["rock", "paper", "scissors"]
computer = random.choice(options)
running = True

while running:
    player = None
    while player not in options:
        player = input("Enter a choice (rock, paper, scissors): ")
    
    print(f"Player: {player}")
    print(f"Computer: {computer}")
    
    if player == computer:
        print("It's a tie!")
    elif player == "rock" and computer == "scissors":
        print("You win!")
    elif player == "paper" and computer == "rock":
        print("You win!")
    elif player == "scissors" and computer == "paper":
        print("You win!")
    else:
        print("You lose!")
    
    i = None
    while i not in ["y", "n"]:
        i = input("Play again? (y/n): ").lower()
    if not i == "y":
        print("Thanks for playing!")
        running = False

Upvotes: 1

Related Questions