My function doesn't recognise variables that were created before it is called
Question:
I’m new to python and having trouble with my def’s. I un-nested them because all my functions were nested in eachother, but now the function "percentified" is unable to find the variables "wins" "losses" and "ties". I’m new to python so any help is appreciated and the definition has to be a definition so that I can repeat the question if the user enters and incorrect value for an input.
Here is the code:
# Importing the random module
import random
import time
# The title of the game is printed
print("Rock, Paper, Scissors! - By Max Pearson")
# All user defined functions apart from code() are defined here
# Defining the first Rock Paper Scissors
def rps1():
# Take the users input of RPS
user_choice = input("What is your choice? Rock, Paper, or Scissors?: ")
# Strips and lowers user input
user_choice = user_choice.lower()
user_choice = user_choice.strip()
RPS = ["Rock", "Paper", "Scissors"]
computer_names = ["Computer", "Robot", "Android", "A.I", "PC", "Algorithm", "Laptop", "Alexa", "Windows"]
computer_name = random.choice(computer_names)
# Selecting the computer's choice
computer_choice = random.choice(RPS)
computer_choice = computer_choice.lower()
computer_choice = computer_choice.strip()
# Sets the parameters for when the user inputs Rock
if user_choice == "rock":
print("You have chosen Rock")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "paper":
print("You lose...")
else:
print("You win!")
# Sets the parameters for when the user inputs Paper
elif user_choice == "paper":
print("You have chosen Paper")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You win!")
else:
print("You lose...")
# Sets the parameters for when the user inputs Scissors
elif user_choice == "scissors":
print("You have chosen Scissors")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You lose...")
else:
print("You win!")
# Fallback for an invalid input
else:
print("Please enter a valid choice")
rps1()
# Defining the option for a new round
def newround():
# Take user input
playagain = input("Would you like to play again?(Yes/No): ")
# Stripping and lowering the variable
playagain = playagain.strip()
playagain = playagain.lower()
if playagain == "yes":
rps1()
elif playagain == "no":
print("Okay!")
else:
print("Please enter a valid input(Yes/No)")
newround()
# Defining the function to turn numbers into percentages
def percentage(x):
x = (x / num_sims) * 100
return x
# Gives the user the option to view statistics
def percentified():
# Take user input
percentages = input("Would you like these results in a statistic?: ")
percentages = percentages.lower()
percentages = percentages.strip()
if percentages == "yes":
# Printing and formatting the results
print(
"Here are the percentages to one decimal point:nWins = {:.1f}%nLosses = {:.1f}%nTies = {:.1f}%".format(
percentage(wins), percentage(losses), percentage(ties)))
elif percentages == "no":
print("Okay, enjoy the results")
else:
print("Please enter a valid choice (Yes/No)")
percentified()
# The second gamemode of Rock Paper Scissors
def rps2():
# Defining a list for the random choice
RPS = ["Rock", "Paper", "Scissors"]
results = []
try:
# Takes an input from the user, to define the number of games
num_sims = int(input("Please enter the number of simulated games you would like: "))
# Loops for the number the user entered
if num_sims > 0:
for i in range(0, num_sims):
choice1 = random.choice(RPS)
choice2 = random.choice(RPS)
# Runs a check on every possible choice and adds the result to a list
if choice1 == choice2:
results.append("tie")
elif choice1 == "Rock" and choice2 == "Paper":
results.append("loss")
elif choice1 == "Rock" and choice2 == "Scissors":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Paper":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Rock":
results.append("loss")
elif choice1 == "Paper" and choice2 == "Rock":
results.append("win")
elif choice1 == "Paper" and choice2 == "Scissors":
results.append("loss")
else:
print("Please enter a valid choice")
rps2()
# Count the results and store them in a variable
wins = results.count("win")
losses = results.count("loss")
ties = results.count("tie")
# Print the user their results
print("Here are the results:nWins = {}nLosses = {}nTies = {}".format(wins, losses, ties))
percentified()
else:
print("Please enter a valid number above 0")
rps2()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid number")
rps2()
try:
# Defining the entirety of the body of the code
def code():
time.sleep(0.5)
# Takes the users input
playstyle = int(input("Would you like to play RPS, or simulate a number of games? (1,2): "))
if playstyle == 1:
rps1()
newround()
# Checks if the user wants to simulate games
elif playstyle == 2:
rps2()
else:
print("Please enter a valid choice (1/2)")
code()
code()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid choice (1/2)")
code()
And here is the error:
NameError: name 'wins' is not defined
Answers:
percentified
does not have access to variables defined in rps2
. There are many ways to make wins
available outside of the rps2
function —, best practice would be to either pass the local variable into the percentified
function, or use object oriented programming to share instance variables (ie: self.wins
).
Consider brushing up on Python variable scoping.
References
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
I’m new to python and having trouble with my def’s. I un-nested them because all my functions were nested in eachother, but now the function "percentified" is unable to find the variables "wins" "losses" and "ties". I’m new to python so any help is appreciated and the definition has to be a definition so that I can repeat the question if the user enters and incorrect value for an input.
Here is the code:
# Importing the random module
import random
import time
# The title of the game is printed
print("Rock, Paper, Scissors! - By Max Pearson")
# All user defined functions apart from code() are defined here
# Defining the first Rock Paper Scissors
def rps1():
# Take the users input of RPS
user_choice = input("What is your choice? Rock, Paper, or Scissors?: ")
# Strips and lowers user input
user_choice = user_choice.lower()
user_choice = user_choice.strip()
RPS = ["Rock", "Paper", "Scissors"]
computer_names = ["Computer", "Robot", "Android", "A.I", "PC", "Algorithm", "Laptop", "Alexa", "Windows"]
computer_name = random.choice(computer_names)
# Selecting the computer's choice
computer_choice = random.choice(RPS)
computer_choice = computer_choice.lower()
computer_choice = computer_choice.strip()
# Sets the parameters for when the user inputs Rock
if user_choice == "rock":
print("You have chosen Rock")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "paper":
print("You lose...")
else:
print("You win!")
# Sets the parameters for when the user inputs Paper
elif user_choice == "paper":
print("You have chosen Paper")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You win!")
else:
print("You lose...")
# Sets the parameters for when the user inputs Scissors
elif user_choice == "scissors":
print("You have chosen Scissors")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You lose...")
else:
print("You win!")
# Fallback for an invalid input
else:
print("Please enter a valid choice")
rps1()
# Defining the option for a new round
def newround():
# Take user input
playagain = input("Would you like to play again?(Yes/No): ")
# Stripping and lowering the variable
playagain = playagain.strip()
playagain = playagain.lower()
if playagain == "yes":
rps1()
elif playagain == "no":
print("Okay!")
else:
print("Please enter a valid input(Yes/No)")
newround()
# Defining the function to turn numbers into percentages
def percentage(x):
x = (x / num_sims) * 100
return x
# Gives the user the option to view statistics
def percentified():
# Take user input
percentages = input("Would you like these results in a statistic?: ")
percentages = percentages.lower()
percentages = percentages.strip()
if percentages == "yes":
# Printing and formatting the results
print(
"Here are the percentages to one decimal point:nWins = {:.1f}%nLosses = {:.1f}%nTies = {:.1f}%".format(
percentage(wins), percentage(losses), percentage(ties)))
elif percentages == "no":
print("Okay, enjoy the results")
else:
print("Please enter a valid choice (Yes/No)")
percentified()
# The second gamemode of Rock Paper Scissors
def rps2():
# Defining a list for the random choice
RPS = ["Rock", "Paper", "Scissors"]
results = []
try:
# Takes an input from the user, to define the number of games
num_sims = int(input("Please enter the number of simulated games you would like: "))
# Loops for the number the user entered
if num_sims > 0:
for i in range(0, num_sims):
choice1 = random.choice(RPS)
choice2 = random.choice(RPS)
# Runs a check on every possible choice and adds the result to a list
if choice1 == choice2:
results.append("tie")
elif choice1 == "Rock" and choice2 == "Paper":
results.append("loss")
elif choice1 == "Rock" and choice2 == "Scissors":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Paper":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Rock":
results.append("loss")
elif choice1 == "Paper" and choice2 == "Rock":
results.append("win")
elif choice1 == "Paper" and choice2 == "Scissors":
results.append("loss")
else:
print("Please enter a valid choice")
rps2()
# Count the results and store them in a variable
wins = results.count("win")
losses = results.count("loss")
ties = results.count("tie")
# Print the user their results
print("Here are the results:nWins = {}nLosses = {}nTies = {}".format(wins, losses, ties))
percentified()
else:
print("Please enter a valid number above 0")
rps2()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid number")
rps2()
try:
# Defining the entirety of the body of the code
def code():
time.sleep(0.5)
# Takes the users input
playstyle = int(input("Would you like to play RPS, or simulate a number of games? (1,2): "))
if playstyle == 1:
rps1()
newround()
# Checks if the user wants to simulate games
elif playstyle == 2:
rps2()
else:
print("Please enter a valid choice (1/2)")
code()
code()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid choice (1/2)")
code()
And here is the error:
NameError: name 'wins' is not defined
percentified
does not have access to variables defined in rps2
. There are many ways to make wins
available outside of the rps2
function —, best practice would be to either pass the local variable into the percentified
function, or use object oriented programming to share instance variables (ie: self.wins
).
Consider brushing up on Python variable scoping.
References
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces