Why isn't my variable showing as defined? - python

I'm trying to make "Rock, Paper, Scissors" as my second program. I keep encountering an error,
"Traceback (most recent call last):
File "/home/cabox/workspace/main.py", line 118, in <module>
File "/home/cabox/workspace/main.py", line 48, in Rock_Paper_Scissors
else:
NameError: name 'rps_choice' is not defined"
And here's the code.
import time
import random
def Rock_Paper_Scissors():
print("Welcome to the \"Rock, Paper, Scissors\" game!")
time.sleep(2)
def rps_input():
while True:
rps_choice = input("Say \"Rock\", \"Paper\", or \"Scissors\" to get started: ")
if rps_choice.upper() == "ROCK":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
if rps_choice.upper() == "PAPER":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
if rps_choice.upper() == "SCISSORS":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
else:
print("Sorry, please say \"Rock\", \"Paper\", or \"Scissors.\"")
time.sleep(2)
print("\n")
rps_input()
time.sleep(2)
rps_list = ["ROCK","PAPER","SCISSORS"]
rps_random = random.choice(rps_list)
print(rps_random, end='')
print("!")
time.sleep(2)
if rps_choice == rps_random:
print("You both picked the same. Please try again.")
rps_input()
else:
if rps_choice == "ROCK":
if rps_random == "PAPER":
print("The computer's paper beats your rock.")
time.sleep(2)
print("You LOSE.")
if rps_random == "SCISSORS":
print("Your rock beats the computer's scissors!")
time.sleep(2)
print("You WIN.")
if rps_choice == "PAPER":
if rps_random == "ROCK":
print("Your paper beats the computer's rock!")
time.sleep(2)
print("You WIN.")
if rps_random == "SCISSORS":
print("The computer's scissors beats your paper.")
time.sleep(2)
print("You LOSE.")
else:
if rps_random == "ROCK":
print("The computer's rock beats your scissors.")
time.sleep(2)
print("You LOSE.")
if rps_random == "PAPER":
print("Your scissors beat the computer's paper.")
time.sleep(2)
print("You WIN.")
time.sleep(2)
def RPS_Reset_Quit():
rq = input("Restart or quit? (R/Q): ")
if rq.lower() == "r":
print("\n")
Rock_Paper_Scissors()
if rq.lower() == "q":
print("Quiting...")
time.sleep(2)
quit()
else:
print("Sorry, please say either R or Q.")
time.sleep(2)
RPS_Reset_Quit()
RPS_Reset_Quit()
Rock_Paper_Scissors()
As you can maybe see, my variable, rps_choice, is not defined, even though it was defined and returned from the rps_input() function. I really have no clue as to why this is happening.

You meant to capture the returned value in rps_choice:
rps_choice = rps_input()
Also, I see you have rps_input() called on two different lines. Both these lines will need updating.

Because you defined it inside the function rps_input() so it belongs only to that function. Imagine it as a hierarchy, the variables from downer scopes can access the variables from upper scopes but it doesn't go the other way.

Related

RPS- Creating a tally with end result in Python

My teacher wants us to create a basic rock paper scissors game that loops until the user ends the game, at which point the program will add up all the wins/losses/ties (of the player) and display it. Here is what I have so far, but I cannot figure out how to create that running tally in the background that will spit out the calculation at the end. (The bottom part of the win/loss/tie product is written by my teacher. It must print this way.)
def main():
import random
Wins = 0
Ties = 0
Losses = 0
while True:
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
print(f"Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
if computer_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_action == "paper":
if computer_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif user_action == "scissors":
if computer_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")
play_again = input("Play again? (y/n): ")
if play_again.lower() != "y":
print("Good Game!")
print("Wins \t Ties \t Losses")
print("---- \t ---- \t ------")
print(wins, "\t", ties , "\t", losses)import random
Where you are printing out wether the user has tied, lost or won you can simply increment the related value.
The text may not be displaying together due to the text not being the same size, add more /t to the strings and it should line up.

Function not taking changed variable [duplicate]

This question already has answers here:
Why does assigning to my global variables not work in Python?
(6 answers)
Closed 8 months ago.
I'm trying to create a rock, paper, scissors game using functions but when I run the game it doesn't show who won. The function is called "Game()". That is the code:
import random
playerChoice=0
computerChoice=0
computerChoices=["Rock","Paper","Scissors"]
def Game():
def Rock():
if playerChoice=="Rock":
if computerChoice=="Rock":
print("Tie")
if computerChoice=="Paper":
print("You Lost")
if computerChoice=="Scissors":
print("You Won")
else:
Paper()
def Paper():
if playerChoice=="Paper":
if computerChoice=="Paper":
print("Tie")
if computerChoice=="Scissors":
print("You Lost")
if computerChoice=="Rock":
print("You Won")
else:
Scissors()
def Scissors():
if computerChoice=="Scissors":
print("Tie")
if computerChoice=="Rock":
print("You Lost")
if computerChoice=="Paper":
print("You Won")
Rock()
def Play():
playerChoice=input("Do you pick rock, paper or scissors? \n").capitalize()
computerChoice=random.choice(computerChoices)
print(f"Computer Picked {computerChoice}")
Game()
Play()
If you examine the choices right before you call Rock() in Game, you'll see that playerChoice and computerChoice are still set to 0. This is because when you do
playerChoice=input("Do you pick rock, paper or scissors? \n").capitalize()
computerChoice=random.choice(computerChoices)
it doesn't actually change the values of the global variables playerChoice or computerChoice. This is called shadowing.
What you can do is accept the choices as arguments:
def Game(playerChoice, computerChoice):
# ...
def Play():
playerChoice=input("Do you pick rock, paper or scissors? \n").capitalize()
computerChoice=random.choice(computerChoices)
print(f"Computer Picked {computerChoice}")
Game(playerChoice, computerChoice)
Also, you have an indentation error in Paper(), it should be this:
def Paper():
if playerChoice=="Paper":
if computerChoice=="Paper":
print("Tie")
if computerChoice=="Scissors":
print("You Lost")
if computerChoice=="Rock":
print("You Won")
else:
Scissors()
Your if statements are a bit messed up. Try using elif more.Try studying this.
import random
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
print(f"Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
if computer_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_action == "paper":
if computer_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif user_action == "scissors":
if computer_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")

Print wont print after elif statment [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
So I am trying to make a cowboy game (double 07) in python. I have the first elif statement working just fine but the other two aren't working. There are more to come but I want to sort the errors out so I don't continue doing them.
import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
#cool typing effect
from sys import stdout as s
from time import sleep as j
def w(print):
for i in print:
j(.03)
s.write(i)
s.flush()
next = input()
def noinput(print):
for i in print:
j(.03)
s.write(i)
s.flush()
#main code for the game hub
def guess_the_number():
os.system('clear')
num = random.randint(1, 50)
guess = "none"
while guess != num:
guess = input(Fore.CYAN + "Choose a number: ")
guess = int(guess)
if guess == num:
w(Fore.GREEN + "You guessed the correct number!")
os.system('clear')
else:
w(Fore.RED + "Sorry try again")
print(Fore.WHITE + "------------")
if guess > num:
w("your number is too large")
os.system('clear')
else:
w("your number is too small")
os.system('clear')
def rock_paper_scissors():
os.system('clear')
user_action = input(Fore.BLUE + "Pick your item (rock, paper, scissors): ")
w(Fore.WHITE + "you chose: " + user_action)
computer_choice = ["scissors", "paper", "rock"]
computer_choice = random.choice(computer_choice)
w(Fore.WHITE + "computer chose: " + computer_choice)
if user_action == computer_choice:
w(Fore.BLUE + f"Both players chose {user_action} its a tie!")
elif user_action == "rock":
if computer_choice == "scissors":
w(Fore.GREEN + "Player wins! Rock destroys Scissors.")
else:
w(Fore.RED + "Paper covers Rock! Computer wins.")
elif user_action == "paper":
if computer_choice == "rock":
w(Fore.GREEN + "Player wins! Paper covers Rock.")
else:
w(Fore.RED + "Scissors cut Paper! Computer wins.")
elif user_action == "scissors":
if computer_choice == "paper":
w(Fore.GREEN + "Player wins! Scissors cut Paper.")
else:
w(Fore.RED + "Rock destroys Scissors! Computer wins.")
os.system('clear')
play_again = input(Fore.CYAN + "Play again? y/n: ")
if play_again == ("y"):
os.system('clear')
rock_paper_scissors()
else:
os.system('clear')
choices()
The error is in this game
def cowboy_game():
os.system('clear')
#----cowboy game code-------
user_action = input("pick your move: ")
os.system('clear')
computer_choice = ["shoot", "reload", "guard"]
computer_choice = random.choice(computer_choice)
w("player chose: " + str(user_action))
w("computer chose: " + str(computer_choice))
#random if statement so elif will work since python is retarded in that way
fgf = print("")
if fgf == ("f"):
print("")
elif user_action == "shoot":
if computer_choice == "shoot":
print(Fore.WHITE + "Both Players killed each other. ")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
It prints the statement above
elif user_action == "shoot":
if computer_choice == "reload":
print(Fore.WHITE + "Player killed enemy.")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif user_action == "shoot":
if computer_choice == "guard":
print(Fore.WHITE + "Enemy blocked the bullet. No damage.")
cowboy_game()
os.system('clear')
It doesn't print at all for those statments
w(Fore.WHITE + "Welcome to my game hub! Pick a number to start ")
os.system('clear')
print("----------")
def choices():
print(Fore.CYAN + "1) Rock Paper Scissors")
print(Fore.WHITE + "----------")
print(Fore.CYAN + "2) Guess the number")
print(Fore.WHITE + "----------")
print(Fore.CYAN + "3) Cowboy game")
print(Fore.WHITE + "---------")
choices()
choice = input("Choice: ")
if choice == ('1'):
os.system('clear')
w("Everyone knows how to play this. Have fun!")
rock_paper_scissors()
if choice == ('2'):
os.system('clear')
w("Welcome to Guess the Number! Try and guess the number to play")
guess_the_number()
if choice == ('3'):
os.system('clear')
w("--(Welcome to cowboy! Instructions in the next line)--")
os.system('clear')
w("To shoot you need to reload first. choices: reload, guard, or shoot. What these do
are self explanatory lol")
w(Fore.CYAN + "press enter to start the game")
os.system('clear')
w(Fore.BLUE + "have fun! :)")
os.system('clear')
cowboy_game()
I cannot find anything online to help with this so I'm going to leave it up to the users on this site.
Your conditions for the Elif statements are the same.
try:
elif user_action == "shoot":
if computer_choice == "shoot":
print(Fore.WHITE + "Both Players killed each other. ")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif computer_choice == "reload":
print(Fore.WHITE + "Player killed enemy.")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif computer_choice == "guard":
print(Fore.WHITE + "Enemy blocked the bullet. No damage.")
cowboy_game()
os.system('clear')
elif user_action == "reload":
(rest of your edge cases)

I wrote a simple python game but functions in that are not executing

I am fairly new in python coding. I made a simple rock, paper, scissor game using random module. I wrote it in three functions. when I am executing it, I get no error but it is not executing the functions.
what I wrote:
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == y:
main()
elif play == n:
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
it is not executing play_game() and user_choice().
It only ask for the input.
The first thing which is wrong is that y and n are not under "" thus python is treating them as a variable. the second thing which was wrong is the position of the play game which should come below the main() to get executed. All user_choice() was not indented properly
Try this code
import random
def main():
global comp
global user
global play
play = ''
# preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
# computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
# user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input(
"Do you want to continue? press y or n for yes and no respectively. ")
if play == "y":
main()
elif play == "n":
print("Thank you for playing!")
exit()
# conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
Create another function main() and call play_game() and user_choice() within main.
The code calls the main() function and this takes an input, but it does not call any of the other functions.
This is why.
Expect that you mean to call play_game() and user_choice() from within main().
Working code.
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
user_choice()
play_game()
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == 'y':
main()
elif play == 'n':
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
if __name__ == '__main__':
main()

I have a bug in my program that I cannot figure out

So, I just recently started coding and decided to make a rock paper scissors game; However, my program has a bug where if the user enters "rock" the correct code block doesn't run. Instead it runs an else statement that's only meant to run when the user enters, "no". I tried using a while loop instead of just if else statements but it didn't make a difference.
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
user = str(input("Great, select Rock Paper or Scissors:"))
if q_1 != "yes":
if q_1 == comp:
print("Oh No, a Tie!")
elif q_1 == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif q_1 == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
else:
print("Ok :(")
There are a few issues with your code.
First of all your code only plays the game if the user doesn't enter "yes". You need to change if q_1 != "yes": to if q_1 == "yes":.
Secondly, your code asks the user to choose rock, paper or scissors regardless of whether they have said they want to play or not. Fix this by moving user = str(input("Great, select Rock Paper or Scissors:")) to under the if q_1 == "yes": if statement.
Thirdly, your code uses q1 instead of user as it should.
Here is how your code should look:
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
if q_1 == "yes":
user = str(input("Great, select Rock Paper or Scissors:"))
if user == comp:
print("Oh No, a Tie!")
elif user == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif user == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
print("I played:",comp)
else:
print("Ok :(")

Categories