Using a variable outside of the function (Python) - python

so I've started learning python again and I'm currently making a mini movie-recommendator. I want my code to be a little bit more understandable so I'm always trying to use def to make the code simple. My problem is ;
def welcome():
print("""Welcome to the low budget film recommender!
Here you can tell me what kind of movies do you like or what movie did you watch
and I'll suggest you a movie from my database according to that.""")
name = input("But first I need to learn your name:>> ").capitalize()
print(f"Nice to meet you {name}")
return name
I want to use the name variable outside of the function(inside another function actually) but it gives me NameError and says "name" is not defined. How can I fix this and use the name variable outside of the function?

It's not best-practice to declare it as a global variable (as the other answers have recommended).
You should go to wherever welcome() is called and set a variable with the result (which you are returning inside welcome):
name = welcome()
print(f"This is the result of welcome: {name}")

You can declare the variable name as global variable.
Code -
def welcome():
global name
print("""Welcome to the low budget film recommender!
Here you can tell me what kind of movies do you like or what movie did you watch
and I'll suggest you a movie from my database according to that.""")
name = input("But first I need to learn your name:>> ").capitalize()
print(f"Nice to meet you {name}")
return name
def second_function():
welcome()
print(name) #prints the value of name in this function which was defined in the welcome()
second_function()

I have modified your code a bit and by using the name variable as a global variable you can achieve what you want. Have a look at the code
#name as a global variable
name = input("But first I need to learn your name:>> ").capitalize()
def welcome():
print("""Welcome to the low budget film recommender!
Here you can tell me what kind of movies do you like or what movie did you watch
and I'll suggest you a movie from my database according to that.""")
# name = input("But first I need to learn your name:>> ").capitalize()
print(f"Nice to meet you {name}")
return name
print(welcome())
def message():
return name
print(message())
Let me know if you still need any assistance

Related

Printing a variable with the same name as a string in Python

In my project I have user made variables. What I'm trying to do is print the variable if the user gives a string named the same as the variable. Here's what I think it would look like:
variable = 123
userInput = input("Enter a variable to print: ")
print(userInput)
# Instead of printing userInput, it will check if userInput is the name of a variable,
# and print if it is.
The user will input "variable", and will print 123.
Also note that the variables will have their custom names and data. So if the variable name is something different, user entering "variable" won't cause it to be printed.
And yes, I know that having user-made variables can be a bad idea. I know what I'm doing.
You can access your variables dynamically by their name using globals():
print(globals().get(userInput,"No such variable"))
You can replace "No such variable" with any other default value in case the variable doesn't exist
You can create a userspace for each user with their own variables, i.e
def get_userspace(user):
""" Returns current userspace of user. """
# Here may be Postgres, Redis or just global userspaces
global userspaces
return userspaces.setdefault(user, {})
userspaces = {}
userspace = get_userspace(user)
then place all input of specific user in his/her userspace to not interfere with others and to not redefine locals/globals that can be viable for program execution. An then use your code with little improvements to get variable from that userspace:
user_input = input("Enter a variable to print: ")
print(userspace.get(user_input))
Here you go.
variable = 123
userInput = input("Enter a variable to print: ")
print(globals()[userInput])

Why do I need a 'return' and a new variable?

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.

Python: cannot return a value assigned inside of a function outside of that function to later use

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.

Passing parameters error

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)

Global Function block?

I am currently making a game in Python. Whenever you want help in the game, you just type help and you can read the help section.
The only problem is, I need to add a function block for each level.
def level_01():
choice = raw_input('>>>: ')
if choice=='help':
level_01_help()
def level_012():
choice = raw_input('>>>: ')
if choice=='help':
level_02_help()
So I was wondering if is possible to make a global function block for all the levels?
When you enter help, you get to help(), and then it automatically goes back to the function block you just came from.
I really hope you understand what I mean, and I would really appreciate all the help I could get.
You can actually pass the help function as a paramater, meaning your code can become:
def get_choice(help_func):
choice = raw_input('>>>: ')
if choice == 'help':
help_func()
else:
return choice
def level_01():
choice = get_choice(level_01_help)
def level_02():
choice = get_choice(level_02_help)
Ideally you should have a separate Module for all interface related tasks, so that the game and interface will be two seperate entities. This should make those 2911 lines a bit more legible, and if you decide to change Interfaces (from Command Line to Tkinter or Pygame for example) you will have a much much easier time of it. Just my 2ยข
A really nice way to handle this kind of problem is with the built in python help. If you add docstrings to your function, they are stored in a special attribute of the function object called doc. You can get to them in code like this:
def example():
'''This is an example'''
print example.__doc__
>> This is an example
you can get to them in code the same way:
def levelOne():
'''It is a dark and stormy night. You can look for shelter or call for help'''
choice = raw_input('>>>: ')
if choice=='help':
return levelOne.__doc__
Doing it this way is a nice way of keeping the relationship between your code and content cleaner (although purists might object that it means you can't use pythons built-in help function for programmer-to-programmer documentation)
I think in the long run you will probably find that levels want to be classes, rather than functions - that way you can store state (did somebody find the key in level 1? is the monster in level 2 alive) and do maximum code reuse. A rough outline would be like this:
class Level(object):
HELP = 'I am a generic level'
def __init__(self, name, **exits):
self.Name = name
self.Exits = exits # this is a dictionary (the two stars)
# so you can have named objects pointing to other levels
def prompt(self):
choice = raw_input(self.Name + ": ")
if choice == 'help':
self.help()
# do other stuff here, returning to self.prompt() as long as you're in this level
return None # maybe return the name or class of the next level when Level is over
def help(self):
print self.HELP
# you can create levels that have custom content by overriding the HELP and prompt() methods:
class LevelOne (Level):
HELP = '''You are in a dark room, with one door to the north.
You can go north or search'''
def prompt(self):
choice = raw_input(self.Name + ": ")
if choice == 'help':
self.help() # this is free - it's defined in Level
if choice == 'go north':
return self.Exits['north']
A better solution would be to store the level you are on as a variable and have the help function handle all of the help stuff.
Example:
def help(level):
# do whatever helpful stuff goes here
print "here is the help for level", level
def level(currentLevel):
choice = raw_input('>>>: ')
if choice=='help':
help(currentLevel)
if ...: # level was beaten
level(currentLevel + 1) # move on to the next one
Sure, it's always possible to generalize. But with the little information you provide (and assuming "help" is the only common functionality), the original code is extremely straightforward. I wouldn't sacrifice this property only to save 1 line of code per level.

Categories

Resources