Reputation: 69
can someone simply explain functions in python? I just can't get my head around them.
So I have had a go at them, and this is what I've ended up with, but it keeps saying that character is not a global variable
def char_name():
character = input("Enter character name: ")
return character;
def main():
char_name()
print(character)
main()
Can anyone explain functions?
Upvotes: 0
Views: 110
Reputation: 31260
This part is a function:
def char_name():
character = input("Enter character name: ")
return character;
It's important to realize that the variable character
exists only inside the function. Not outside of it. That's a great feature -- it means that if you decide that name
is a better name for the variable after all, then you only need to change the variables inside the function, and guaranteed nowhere else. No assignments to variables elsewhere can influence what happens in your function. It's all there.
The function has a return value equal to the value of the variable at the end of the function.
def main():
char_name()
print(character)
And here's another function, that also tries to have a variable named character
. It happens to have the same name, but that's just a coincedence, it's a different function so it's a different variable. Unfortunately, this variable is only used but never set to any value, and Python can't find it as a global variable either, so it throws an exception. char_name
is called, but its return value is not used for anything, so it's discarded.
What you want to do is this:
def main():
name = char_name() # I picked a different name to make my point
print(name)
The function char_name
is called, and its return value is assigned to the variable name
. Now you can print it.
Upvotes: 1
Reputation: 34698
def char_name():
character = input("Enter character name: ")
return character
def main():
character = char_name()
print(character)
main()
You need to assign returned values.
Upvotes: 0