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)
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)
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)
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)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.