'paper scissors rock python game
This is my attempt to create paper, rock and scissors game There seems to be an error with while loop, "roundNum is not defined", please help?
import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer = options[random.randint(0,2)]
print(computer)
How do I create code to ask the payer if he wants to play again? and if so to run the code again?
Solution 1:[1]
Make sure your indentation is correct.
import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer = options[random.randint(0,2)]
print(computer)
Solution 2:[2]
The issue is with the indentation of while loop.
As function game and while are at same level any object declared inside the game function will be out of scope/unreachable for while loop.
A simple tab will resolve the issue in this case as follow :
import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer = options[random.randint(0,2)]
print(computer)
Solution 3:[3]
The reason you are getting the error RoundNum is not defined is because you are defining variables inside of a function, this means that you will have to call the function game() to define the three variables roundNum, playerScore and computerScore. To solve this, we remove the game() function and define the three variables in the main script like this:
import random
options = ['rock', 'paper', 'scissors']
roundNum = 1 # Defines the roundNum variable
playerScore = 0
computerScore = 0
def game(rounds):
while roundNum <= rounds:
print('Round Number ' + str(roundNum)
Option = input('Please choose rock, paper, or scissors > ')
Computer = options[random.randint(0, 2)]
# After all the rounds are finished, ask if the player wants to play again
x = input("Do you want to play again? ")
# If they say yes, start a new round of Rock, paper, Scissors
if x.lower() == "yes":
game(1)
# If they don't want to play then exit the program
if x.lower() == "no":
print("Bye")
exit()
game(1)
Edit: if you want to ask whether the player wants to play again, just add call the input function inside a variable, then check what the player said, if they say yes then start a new game of Rock, Paper Scissors, if they don't then exit the program
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jakob Madsen |
| Solution 2 | Kakarot_JG |
| Solution 3 |
