Player not defined - python

Im having some issues with player not defined errors this is the error and the codes i have putten links to the pictures of it.Im pretty new at python and i don't understand most of the errors,i will be happy if someone could help.
Player not defined errors
Code
Code

I have created a minimal working code about your attached pictures. Mostly your global variable handling was not correct. You can find my comments in the below code as comments.
Code:
# Define global variable
current_player = None
class Player(object):
def __init__(self, name):
self.name = name
self.other = 100
def main():
option = input("Option: ")
if option == "1":
start()
def start():
# Use the global variable inside the function.
global current_player
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1()
def start1():
# Use the global variable inside the function.
global current_player
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player.name))
main()
Output:
>>> python3 test.py
Option: 1
Name: Bill
Hello my friend: Bill
>>> python3 test.py
Option: 1
Name: Jill
Hello my friend: Jill
Note:
I suggest to get rid of the global variable usage. Pass the required variables as parameters. I have implemented a version which doesn't contain global variables.
def start():
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1(current_player)
def start1(current_player_info):
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player_info.name))
PS:
In your next question, do not attach or link pictures. Please add a minimal code and your issue (traceback). Please read it: https://stackoverflow.com/help/how-to-ask

Related

How to accept user input from within a function?

I am new to Python. This code snippet is supposed to define a function getinput(), which is supposed to accept user input and put that value into variable stuff. Then I call the function, and print the value of the variable stuff.
def getinput():
stuff = input("Please enter something.")
getinput()
print(stuff)
The problem is that the program is not working as expected and I get the error:
NameError: name 'stuff' is not defined
In contrast, without defining and calling a function, this code works just fine:
stuff = input("Please enter something.")
print(stuff)
And I can't figure out why that should be so.
Please help. I am learning Python to coach my kid through his school course, and I am using Google Colab with Python 3.7.11, I believe.
Variables defined within a function are local in scope to that function, however, you can return values from functions so you can do what you want like this:
def getinput():
sth = input("Please enter something.")
return sth
stuff = getinput()
print(stuff)
There is a lot of possibilities of printing stuff that you could do -
def getinput():
stuff = input("Please enter something.")
print(stuff)
getinput()
You can print it inside function and call it
def getinput():
stuff = input("Please enter something.")
return stuff
print(getinput())
You can return the stuff and print it (BEST Solution)
def getinput():
global stuff
stuff = input("Please enter something.")
getinput()
print(stuff)
Or you could use global keyword
In Python, there is a concept of the scope of a variable. You create a stuff variable inside a function and the variable can only be used there. There is no such variable outside the function. You can do this:
def getinput():
getinput.stuff = input('Please enter something')
getinput()
print(getinput.stuff)
Or you can return value from function:
def getinput():
stuff = input('Please enter something')
return stuff
s = getinput()
print(s)

keeping changed data global variables

I have a global variable that I change in a function but when I call the global variable later in code in a different function, it doesn't store the change when the variable is first called:
name = "noname"
def username():
print ("It would help if I had a name to go by, please enter a name.")
global name
name = input()
def character():
global name
print ("Character overview:\nName:"+name+"")
And the output of character() is noname instead of the input.
Is there a way keeping the change in the first function?
This works for me.
name = "noname"
def user():
global name
name = input()
def char():
# Works with or without global here
print(name)
user()
char()

Python variable passing in functions to a menu

I have a function, menu() which creates a menu to navigate and call functions. here is the function.
def menu():
x = raw_input("WOOF! What can POODLE fetch for you? ('--nothing' to exit): ")
if x == "--nothing":
sys.exit(0)
elif x == "--build":
populateCrawled(toCrawl)
graph = buildGraph(crawled)
index = buildIndex(graph)
ranks = computeRanks(graph)
menu()
elif x == "--dump":
saveFile(index, "index.txt")
saveFile(graph, "graph.txt")
saveFile(ranks, "ranks.txt")
menu()
elif x == "--restore":
index = loadFile("index.txt")
graph = loadFile("graph.txt")
ranks = loadFile("ranks.txt")
menu()
elif x == "--print":
print graph
print index
print ranks
menu()
elif x == "--help":
print "WOOF! POODLE Help Options"
print "--build Create the POODLE database"
print "--dump Save the POODLE database"
print "--restore Retrieve the POODLE database"
print "--print Show the POODLE database"
print "--help Show this help information"
menu()
elif x == "--search":
search(index, rankablePages)
else:
print "Help option not found"
menu()
seed = raw_input("Please enter the seed URL: ")
testSeed = "https://dunluce.infc.ulst.ac.uk/d11ga2/COM506/AssignmentB/test_index.html"
seed = testSeed
toCrawl=[seed]
crawled, graph, index, rankablePages = [], {}, {}, {}
MAX_DEPTH = 10
menu()
these variables and dictionaries are all declared globally but when I say type "--build" it does successfully build but then if I go to type "--print" it shows me
UnboundLocalError: local variable 'graph' referenced before assignment
However if I print these dictionaries immediatly after building then they print fine. It's when menu() is reloaded it loses these values. Should I use a while loop or do I need to do some parameter passing?
The fact that these variables are declared globally doesn't help (although note that you didn't actually define ranks globally…), because they're also declared locally, and the local names hide the global ones.
Whenever you write spam = eggs in the body of a function, that makes spam into a local variable, and anywhere spam appears in the function, it refers to that local variable.
If you want to make something global, but still be able to assign to it, you need a global statement. So:
def menu():
global graph, index, ranks
# the rest of your code
But as usual, a better solution is to stop using global variables.
One option create a class to hold your state, make menu a method of that class, and make graph and friends attributes of the class's instances.
But there's an even simpler option here. The only reason you need these variables to be global is because menu is calling itself recursively to simulate a loop. That's already a bad thing to do in Python, for other reasons. (For example, if you go through the menu about 999 times, you're going to get a recursion error.) If you just use a loop instead of trying to fake it, you can just use local variables:
def menu(graph, index, ranks):
while True:
# the rest of your code except the menu() calls
# ...
crawled, graph, index, rankablePages = [], {}, {}, {}
menu(graph, index, ranks)
You should declare graph (and any other variable that menu should use externally) as a global:
def menu():
global graph
#rest of the code
you can read more about globals here

Same Variable in different Functions. (Python)

Newbie here, I am currently writing a "game" in ex 36 of LearnPythonTheHardWay.
If I wanted to ask for the user's name in one function. How can I recall that persons name in all the other functions without asking for it again, or setting it = to the name again? From my understanding variables in a function don't affect other functions, but what if I want it to?
def room_1():
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
Two ways, first would be to create a class and set an attribute called playername. Something like:
class Game(object):
def __init__(self,playername=None):
if playername is None: self.playername = raw_input("What's your name? ")
else: self.playername = playername
# initialize any other variables here
def run(self):
# all your code goes here, and self.playername
# is always your player's name.
game = Game()
game.run()
The other was is widely (and properly!) frowned upon. You could use a global
global name
name = raw_input("What is your name? ")
Now so long as you don't overwrite name in any of your functions, they can call name and access it as if it were a local variable.
EDIT: It looks like you're trying to build a game that should implement a Finite State Machine which is almost certainly beyond your ability to make right now. You can CERTAINLY do it without one, but the code will always have that "spaghetti" feel to it. class Game is the first step towards the FSM, but there's a long way to go :)
You should declare it as global when asking for the name, so it is available in other functions:
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
print "Hi %s" % name
For now you can define a variable outside of a function, then call it with the global keyword.
Normally you would use a class for this sort of thing, but you'll get there eventually :o)
name = ''
def room_1():
global name
name = raw_input("What is your name?")
print "hi %s" % name
def room_7():
global name
print "Hi %s" % name

Global Name Not Defined in Python

Am new to Python OOP. Please dont be harsh. Here is my code which calculates which is the fastest time of an athlete from a list and displays them. But When Running, I get this error:
z= add.mylist.min()
NameError: global name 'add' is not defined
My Code:
class Athlete:
def add(self):
list=[]
mylist=[]
for i in range(2):
self.name = raw_input("Enter name: ")
self.fastest_time = input("time: ")
list.append(self.name)
mylist.append(self.fastest_time)
print "Names: ",list
print "Fastest times: ",mylist
def display(self):
z= add.mylist.min()
w= add.mylist.index(z)
print "Minimum time: ",z
print "Name of athelte with fastest time: ",list[w]
x = Athlete()
x.add()
x.display()
You need to refer to methods on the instance with the self parameter. In addition, your add() method needs to return the mylist variable it generates, you cannot refer to method local variables as attributes on methods:
def display(self):
mylist = self.add()
z = min(mylist)
w = mylist.index(z)
def add(self):
list=[]
mylist=[]
for i in range(2):
self.name = raw_input("Enter name: ")
self.fastest_time = input("time: ")
list.append(self.name)
mylist.append(self.fastest_time)
print "Names: ",list
print "Fastest times: ",mylist
return mylist
That is what self is for, as a reference point to find instance attributes and other methods on the same object.
You may want to rename list to something that does not shadow the built-in type.
Martijn has already answered your question, so here are some remarks and code style tips:
New-style classes derive from object
You have both athlete names and their times, those belong together as key-value pairs in a dictionary instead of two separate lists
Don't use print statements inside class methods, a class method should return an object that you then can print
what if you have more then 2 athletes for which you want to enter the time? If you make the number of athletes an argument of your function, you can add a variable number of athlethes
give descriptive variable names (not mylist) and don't use names of builtin functions (like list) as variable name
variables that you want to use throughout your class can be initalized in an __init__method.
For printing, use the format function instead of using commas
use if __name__ == '__main__' so that your Python file can act as either reusable modules or as standalone program
Taking these into account, I would rewrite your code to something like this:
from collections import defaultdict
class Athlete(object): # see (1)
def __init__(self): # see (6)
self.athlete_times = defaultdict(str) # see (2)
def add_athletes_and_times(self, n): # see (4)
for i in range(n):
self.name = raw_input("Enter name: ")
self.fastest_time = input("time (in seconds): ")
self.athlete_times[self.fastest_time] = self.name
def get_fastest_time(self):
return min(self.athlete_times) # see (3)
if __name__ == '__main__': # see (8)
x = Athlete()
x.add_athletes_and_times(2)
for fast_time in x.athlete_times:
print "The fastest time of athlete {0} is {1} seconds.".format(
x.athlete_times[fast_time], fast_time) # see (7)
fastest_time = x.get_fastest_time()
print "The overall fastest time is: {0} seconds for athlete {1}.".format(
fastest_time, x.athlete_times[fastest_time])

Categories

Resources