I define a variable named 'computerChoice' in a function and then attempt to use it in another variable but it says that 'computerChoice' is undefined... Being new to Python, I am not sure why this is happening so I hope that you could help answer my question!
def computerDecision():
import random
for x in range(1):
num = random.randint(1,4)
if num == 1:
computerChoice = 'rock'
elif num == 2:
computerChoice = 'paper'
elif num == 3:
computerChoice = 'scissors'
def determineWinner():
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
The computerChoice variable is restricted in scope to the function in which it was defined. This is to prevent functions from interfering with one another. You can declare it to be global (accessible from anywhere) with the keyword global:
global computerChoice
This is probably not what you want, however, as your functions do not need to interact with each other. You can just make computerDecision() return its choice.
import random
def computerDecision():
for x in range(1):
num = random.randint(1,4)
if num == 1:
return 'rock'
elif num == 2:
return 'paper'
elif num == 3:
return 'scissors'
def determineWinner():
computerChoice = computerDecision()
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
Also note that computerDecision() can be redefined more simply, as just return random.choice(("rock", "paper", "scissors")).
Related
WHile I was attempting a simple rock, paper scissors, I ran into this proble. When I execute the file and input the user_input, it says to me that the variable computer_choice doesn’t exist, even though it does exist. I would appreciate if someone could help me, thank you.
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint (0, 2)
computer_choice = options[random_number]
print ("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors" :
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper" :
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_pick == "rock" :
print("You Won!")
user_wins += 1
continue
else:
print("You Lost!")
computer_wins += 1
continue
print("You won", user_wins,"times and the computer won", computer_wins, "times.")
print("Goodbye")
You have to be careful with indentation when using python:
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
# not at this level
# at this level
random_number = random.randint(0, 2)
computer_choice = options[random_number]
print("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors":
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper":
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_choice == "rock": #not computer_pick
print("You Won!")
user_wins += 1
continue
Also you wrote computer_pick in line 31, probably you mean computer_choice
I want the computer to follow a win-stay, lose-switch strategy but I can't seem to get the computer to change its option from rock. Please help!
import random
def game():
game_start
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = 'rock'
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock':
computer_choice = 'rock'
elif user_choice == 'paper' and computer_choice == 'scissors':
computer_choice = 'scissors'
elif user_choice == 'rock' and computer_choice == 'paper':
computer_choice = 'paper'
print(computer_wins)
computer_count += 1
if user_choice == 'rock' and computer_choice == 'scissors':
computer_choice = 'paper'
elif user_choice == 'scissors' and computer_choice == 'paper':
computer_choice = 'rock'
elif user_choice == 'paper' and computer_choice == 'rock':
computer_choice = 'scissors'
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 0
user_count += 0
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
It's because you put computer_choice = 'rock' inside the while loop. Having inside causes it to be reset to rock for every play.
Another issue is that your if statements only prints who wins and increases count for the last one.
You can also compress the if statements a little, but that wasn't part of the question, so I didn't do it here.
game_start
computer_count = 0
user_count = 0
def game():
computer_choice = 'rock'
while True:
#base_choice = ['scissors', 'paper', 'rock']
# no point in having an unused list
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock':
computer_choice = 'rock'
print(computer_wins)
computer_count += 1
elif user_choice == 'paper' and computer_choice == 'scissors':
computer_choice = 'scissors'
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'paper':
computer_choice = 'paper'
print(computer_wins)
computer_count += 1
if user_choice == 'rock' and computer_choice == 'scissors':
computer_choice = 'paper'
print(you_win)
user_count += 1
elif user_choice == 'scissors' and computer_choice == 'paper':
computer_choice = 'rock'
print(you_win)
user_count += 1
elif user_choice == 'paper' and computer_choice == 'rock':
computer_choice = 'scissors'
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
# no point in adding 0
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
In response to your making it random comment, you need to import the random module.
Here, the base_choice is used, so uncomment it and it'll work:
import random #place at beginning of code
# can instead do `from random import choice`
base_choice = ['scissors', 'paper', 'rock']
# needs to be before you use it in random.choice
# to get random choice, do
computer_choice = random.choice(base_choice)
could you tell me why my program doesnt increment "bot_points = 0"
"your_points = 0" to stop the while loop when some of these values reach 3
import random
rock_paper_scissors = ["ROCK", "PAPER", "SCISSORS"]
bot_points = 0
your_points = 0
while bot_points <= 3 or your_points <= 3:
user_choice = input('type "rock", "paper" or "scissors": ').upper()
bot_choice = random.choice(rock_paper_scissors)
if bot_choice == "ROCK" and user_choice == "ROCK":
print("Draw")
elif bot_choice == "ROCK" and user_choice == "PAPER":
print("You win")
your_points = your_points+1
elif bot_choice == "PAPER" and user_choice == "PAPER":
print("Draw")
elif bot_choice == "PAPER" and user_choice == "SCISSORS":
print("You win")
your_points= your_points+1
elif bot_choice == "PAPER" and user_choice == "ROCK":
print("You lose")
bot_points = bot_points+1
elif bot_choice == "SCISSORS" and user_choice == "PAPER":
print("You lose")
bot_points = bot_points+1
elif bot_choice == "SCISSORS" and user_choice == "ROCK":
print("You win")
your_points = your_points+1
elif bot_choice == "SCISSORS" and user_choice == "SCISSORS":
print("Draw")
elif bot_choice == "ROCK" and user_choice == "SCISSORS":
print("You lose")
bot_points = bot_points+1
Two issues:
You test for <= 3, so it won't end until someone wins four times
You test bot_points <= 3 or your_points <= 3, so it won't end until both players win at least four times; and would end when either reaches the threshold
If you want to end when either player wins three times, change the test to:
while bot_points < 3 and your_points < 3:
(I am new to python, please don't judge the quality of the code right now.)
So, I am making a program which let's you play rock, papers and scissors with the code. This is my code:
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
elif computer_choice == "scissors":
print(f"{name} wins!")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
if computer_choice == "rock":
print(f"{name} wins!")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
elif computer_choice == "papers":
print(f"{name} wins!")
if user_choice == computer_choice:
print("Tie!")
But, like when I run the code, it is working out really good. However, the problem is that if the user does not enter the correct spelling, the output looks really messed up. Like this:
Enter your name:
_____
Hi _____, choose between rock, papers and scissors
> asdf
ERROR
Computer chooses: rock
I do not want the last line, the one which says "Computer chooses: rock". Please someone suggest how do I go about this.
Thanks in advance 🙏
(EDIT: Also, if you can suggest how I can include a point system in this, which calculates how many times the computer wins, the user wins and how many times the match was a tie, the effort would be really appreciated.)
Just use continue to force the user to enter a valid choice:
while True:
user_choice = str(input('> '))
user_choice = user_choice.lower()
if user_choice not in choices:
print(f"You chose {user_choice}, please choose rock, paper, or scissors")
continue
[...]
Looks like your error problem has already been solved : )
But for the tie and score counter I have prepared the following code-
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
Cwin = 0
Userwin = 0
Tie = 0
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "scissors":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "rock":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "papers":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == computer_choice:
print("Tie!")
Tie = Tie + 1
print(int(Tie) , "Ties so far")
Look here the screenshot of it working properly-
Just add computer choose inside else:
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
else:
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
elif computer_choice == "scissors":
print(f"{name} wins!")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
if computer_choice == "rock":
print(f"{name} wins!")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
elif computer_choice == "papers":
print(f"{name} wins!")
if user_choice == computer_choice:
print("Tie!")
Here is a possible implementation:
import random
name = str(input("Enter your name: "))
choices = ["rock", "scissors", "paper"]
print(f"Hi {name}, choose between rock, paper and scissors")
while True:
user_choice = None
while user_choice not in choices:
user_choice = str(input('> '))
user_choice.lower()
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == computer_choice:
print("Tie!")
elif choices[(choices.index(user_choice) + 1) % len(choices)] == computer_choice:
print(f"{name} wins!")
else:
print(f"Computer wins!")
Some insights:
You can accomplish the comparing mechanism with a rounded list, and not explicit comparison.
Do a while loop for the user input until it is correct.
i have the following code for a rock paper scissors game:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
if choice != "rock":
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass
else:
pass
else:
print "The computer chose " + computerchoice + "."
if choice == computerchoice:
print "It's a draw!"
elif choice + computerchoice == "rockpaper":
print "Computer wins, paper covers rock!"
elif choice + computerchoice == "rockscissors":
print "Player wins, rock crushes scissors!"
elif choice + computerchoice == "paperrock":
print "Player wins, paper covers rock!"
elif choice + computerchoice == "paperscissors":
print "Computer wins, scissors cut paper!"
elif choice + computerchoice == "scissorsrock":
print "Computer wins, rock crushes scissors!"
elif choice + computerchoice == "scissorspaper":
print "Player wins, scissors cuts paper!"
rps()
Whenever i run it, it works fine if i pick rock, but if i pick paper or scissors, the code stops. It wont throw any kind of error, it just stops. Please help me!
This should be closer to what you need:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
if choice not in ["scissors","paper","rock"]: # check if choice is valid
rps()
print "The computer chose " + computerchoice + "."
if choice == computerchoice: # move on to your comparison checks
choice + computerchoice
print "It's a draw!"
elif choice + computerchoice == "rockpaper":
print "Computer wins, paper covers rock!"
elif choice + computerchoice == "rockscissors":
print "Player wins, rock crushes scissors!"
elif choice + computerchoice == "paperrock":
print "Player wins, paper covers rock!"
elif choice + computerchoice == "paperscissors":
print "Computer wins, scissors cut paper!"
elif choice + computerchoice == "scissorsrock":
print "Computer wins, rock crushes scissors!"
elif choice + computerchoice == "scissorspaper":
print "Player wins, scissors cuts paper!"
rps()
The problem is from the first choice if statement:
if choice != "rock":
if choice != "paper":
if choice != "scissors":
when rock is selected it jumps to the else statement without evaluating the other two if statements. A more intuitive but admittedly non-Pythonic way is to have a series of nested if statements:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
print "The computer chose " + computerchoice + "."
if choice == 'rock':
if computerchoice == 'rock':
print 'Draw: you both picked rock'
elif computerchoice == 'scissors':
print 'You win! Rock beats scissors'
elif computerchoice == 'paper':
print 'You lose. Try again'
elif choice == 'paper':
if computerchoice == 'rock':
print 'You win!'
elif computerchoice == 'scissors':
print 'You lose.'
elif computerchoice == 'paper':
print 'You draw.'
elif choice == 'scissors':
if computerchoice == 'rock':
print 'You lose.'
elif computerchoice == 'scissors':
print 'You draw.'
elif computerchoice == 'paper':
print 'You win.'
else:
print 'I am sorry, I could not make out what you typed. Try again'
rps()
rps()
Loop just your input. Don't recursively call the whole game again. Also setup a variable to test against for valid choices. Also if you break out the win conditions you can add to it easily. Maybe something like this
import random
CHOICES = {'rock': 'crushes', 'paper': 'covers', 'scissors': 'cuts'}
def win(p1, p2):
if p1 == p2:
return 0
if p1 == 'rock':
return 2 if p2 == 'paper' else 1
if p1 == 'paper':
return 2 if p2 == 'scissors' else 1
if p1 == 'scissors':
return 2 if p2 == 'rock' else 1
def rps():
computerchoice = random.choice(CHOICES.keys())
choice = raw_input("Rock, paper, or scissors?:").lower()
while choice not in CHOICES:
print "Check your spelling and try again."
choice = raw_input("Rock, paper, or scissors?:").lower()
print "The computer chose %s." % computerchoice
winner = win(choice, computerchoice)
if winner==0:
print "It's a draw!"
if winner==1:
print "Player wins, %s %s %s!" % (choice, CHOICES[choice], computerchoice)
if winner==2:
print "Computer wins, %s %s %s!" % (computerchoice, CHOICES[computerchoice], choice)
rps()
Now say you want to add lizard and spock. Just update CHOICES and the win() function. :)
Check theese lines out:
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass #here you tell it to do nothing when you choose "scissors"
else:
pass #here you tell it to do nothing when you choose "paper"
I think you just need to re-sort your if/else statements :-)
The else section (containing the brains of your code) of the first if:
if choice != "rock":
if choice != "paper":
if choice != "scissors":
never runs if player doesn't select 'rock' i.e. 'paper', 'scissors' and any invalid input will ensure the else containing the important section of your code doesn't get executed.
you definitely don't need recursion for such a simple algorithm (calling rps() from rps())
you should try to implement it like this:
input == ""
while input != "quit":
input = raw_input(...)
if input not in ["r", "p", "s"]: continue
computer_choice = ...
if foo beats bar: print ...
if bar beats foo: print ...
Let's look at this.
if choice != "rock":
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass
else:
pass
else:
# Do stuff...
You input scissors.
Does "scissors" != "rock"? Yes, so lets go further.
Does "scissors" != "paper"? Yes, so lets go further.
Does "scissors" != "scissors"? No, so let's look at the alternative else clause:
else:
pass
This code does nothing... Every other if/else clause is then broken out of after this... See the issue?
There are also a lot of simplifications you can do, for example you can make use of tables and lists more often instead of using so many if statements. For example (although the code remains largely untested):
import random
def convert_choice(choice):
choice_map = {"rock":0, "paper":1, "scissors":2}
return choice_map[choice]
def rock_paper_scissors():
choices = ["rock", "paper", "scissors"]
computer_choice = random.randint(0,2)
player_choice = raw_input("Rock, paper, or scissors? ")
raw_player_choice = convert_choice(player_choice) * 3
print "Copmuter played: " + choices[computer_choice]
print "You played: " + player_choice
win_states = {0:"tied", 3:"won", 6:"loss",
-1:"loss", 2:"tied", 5:"won",
-2:"won", 1:"loss", 4:"tied"}
print "You " + win_states[raw_player_choice - computer_choice]
def main():
rock_paper_scissors()
if __name__ == "__main__":
main()