I am trying to create a program and get user data then pass it on to another function, but I keep getting a NameError, even though I (appear) to be passing the parameters properly and calling the function with that parameter too.
here is an example of my code:
#Define prompt to get player name
def welcomePrompt():
print("Welcome to my beachy adventure game!")
name=(input("Before we start, you must check-in, what is your name?:"))
return name
#Define dictionary to access all player data
def dataDict(name):
name=name
print(name)
def main():
welcomePrompt()
dataDict(name)
main()
could someone please help? thanks
You don't use the name value returned from welcomePrompt(); a local variable in a function is not going to be visible in another function, so the only way to pass on the result is by returning and then storing that result:
def main():
name = welcomePrompt()
dataDict(name)
Note the name = part I added. This is a new local variable. It may have the same name as the one in welcomePrompt(), but because it is a different function, the two are independent. You can rename that variable in main() to something else and not change the function of the program:
def main():
result = welcomePrompt()
dataDict(result)
Related
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).
def make_album(artist, album_name):
entry = {'name' : artist, 'album' : album_name}
return entry
while True:
print("\nPlease, write your fav artist and title: ")
print("\nType 'q' to quit.")
band_name = input('Artist name: ')
if band_name == 'q':
break
title_name = input('Title name: ')
if title_name == 'q':
break
comp_entry = make_album(band_name, title_name)
print(comp_entry)
The code runs perfectly. But there are two points that I can not understand:
Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?
Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:
make_album(band_name, title_name):
print(entry)
I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.
entry is defined inside the function, so it cannot be accessed outside of it.
Check this article about closures
http://www.trytoprogram.com/python-programming/python-closures/
What you have to understand is the concept of scope in python. This article is a good place to start.
You can directly print the value this way too
print(make_album(band_name, title_name))
The variable comp_entry is used to store the value returned from the make_album function. So, if you want a function to return back a value on calling the function, provide a return statement
It will print None if no return is provided.
I am unsure of why the variable totalspeed variable is not being passed correctly to the function startgame as the startgame function is called after the gettotalspeed function.
Exerpt from call function:
gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)
Functions
def gettotalspeed(party_ids):
#Get selected party members IDS
print(party_ids)
#Obtain Speeds
ids_string = ','.join(str(id) for id in party_ids)
mycursor.execute("SELECT startspeed FROM characters WHERE CharID IN ({0})".format(ids_string))
myspeeds=mycursor.fetchall()
totalspeed=0
for speedval in myspeeds:
totalspeed=totalspeed + speedval[0]
print("totalspeed is: ",totalspeed)
return totalspeed
def startgame(party_ids,totalspeed,distance,NoOfEvents):
#Check if game end
print(totalspeed)
while distance!=0:
#Travel...
distance=distance-totalspeed
NoOfEvents=NoOfEvents+1
#Generate Random Encounter
genevent(NoOfEvents)
return NoOfEvents
Error Produced:
NameError: name 'totalspeed' is not defined
Outputs (ignoring party_ids)
totalspeed is: 15
I suspect that your problem is self-evident from the main program:
gettotalspeed(party_ids)
NoOfEvents=0
startgame(party_ids,totalspeed,distance,NoOfEvents)
Of the variables you pass to your functions, only NoOfEvents is defined. party_ids, totalspeed, and distance have no definitions.
Work through a tutorial on Python scoping rules. Most of all, note that a function defines a scoping block. Variables inside the function are reclaimed when you leave the function; their names do not apply outside of that block. Your posted program has three independent totalspeed variables.
You forgot to make totalspeed a global variable like global totalspeed in your gettotalspeed() function. You might also be confused about what return does. If you wanted to do it the "proper" way, you could do totalspeed = gettotalspeed(party_ids). Hope this helps!
While writing a program in python i noticed that if one puts a function like print("hello world") inside a variable it will not be stored like expected, instead it will run. Also when i go and call the variable later in the program it will do nothing. can anyone tell me why this is and how to fix it?
If mean something like:
variable = print("hello world")`
then calling the function is the expected result. This syntax means to call the print function and assign the returned value to the variable. It's analogous to:
variable = input("Enter a name")
You're surely not surprised that this calls the input() function and assigns the string that the user entered to the variable.
If you want to store a function, you can use a lambda:
variable = lambda: print("hello world")
Then you can later do:
variable()
and it will print the message
All, I have this request but first I will explain what I'm trying to achieve. I coded a python script with many global variables but also many methods defined inside different modules (.py files).
The script sometimes moves to a method and inside this method I call another method defined in another module. The script is quite complex.
Most of my code is inside Try/Except so that every time an exception is triggered my code runs a method called "check_issue()" in which I print to console the traceback and then I ask myself if there's any variable's value I want to double check. Now, I read many stackoverflow useful pages in which users show how to use/select globals(), locals() and eval() to see current global variables and local variables.
What I would specifically need though is the ability to input inside method "check_issue()" the name of a variable that may be defined not as global and not inside the method check_issue() either.
Using classes is not a solution since I would need to change hundreds of lines of code.
These are the links I already read:
Viewing all defined variables
Calling variable defined inside one function from another function
How to get value of variable entered from user input?
This is a sample code that doesn't work:
a = 4
b = "apple"
def func_a():
c = "orange"
...
check_issue()
def check_issue():
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
# I need to be able to enter "c" and print the its value "orange"
print(func_a.locals()[var_to_review ]) # this doesn't work
Could somebody suggest how to fix it?
Many thanks
When you call locals() inside check_issue(), you can only access to the locals of this function, which would be : ['var_to_review'].
You can add a parameter to the check_issue function and pass locals whenever you call it.
a = 4
b = "apple"
def func_a():
c = "orange"
check_issue(locals())
def check_issue(local_vars):
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
print(local_vars[var_to_review])
def program(n):
name = input("What is your name? >")
return name
print(name)
I have a code that i am trying to execute very similar to this. When executing it, it will not return the variable 'name' i used in the function in order to use that variable outside the function. Why is this?
I am super new to coding by the way so please excuse me if i made a stupid mistake.
When you run your program, you need to assign the result (i.e. whatever is returned in your program, to another variable). Example:
def get_name():
name = input('Name please! ')
return name
name = get_name()
print('Hello ' + name)
Pssst.. I took your function parameter n away since it was not being used for anything. If you're using it inside your actual program, you should keep it :)
For a bit of a more in-depth explanation...
Variables that are declared inside your neat little function over there can't be seen once you come out of it (though there are some exceptions that we don't need to get into right now). If you're interested in how this works, it's known as "variable scope."
To execute the content of a function you need to make a call to the function and assign the return value to some variable. To fix your example, you would do:
def get_name():
name = input("What is your name? >")
return name
name = get_name()
print(name)
I have changed the function name from program() to get_name() seeing as program() is a ambiguous name for a function.
This snippet will make a call to the get_name() function and assign the return value to the variable name. It is important to note, that the name variable inside the function is actually a different variable to the one that we are assigning to outside the function. Note: I have removed the argument n from get_name() since it was not being used.