keeping changed data global variables - python

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()

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)

assigning values to global variables in python [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 1 year ago.
Sorry for the beginner question. In the below code, the output I'm getting is "Original" and not "Function". Doesn't the value of name change after passing through the function? Thanks
global name
name = "Original"
def test():
name = "Function"
test()
print(name)
Use the global keyword in the function.
name = "Original" # define name
def test(): # define our function
global name # this function can now change name
name = "Function" # change the value
test() # run the function
print(name) # returns Function
I'd assume global needs to be in the function so you could do something like this, where a function can use text without effecting the text var:
text = "Original"
def test():
global text
text = "Function"
def printText(text):
textToPrint = text # use text var without any issues in this function
print(textToPrint)
test()
print(text)
global declarations go inside the function you want to apply them to, not at the top-level.
name = "Original"
def test():
global name
name = "Function"
test()
print(name)
name = "Original" #global variable
def test():
#to update the global value you have to declare it here
global name
name = "Function"
test()
print(name)
you can read more about it here, https://www.programiz.com/python-programming/global-keyword

Player not defined

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

Python Function Errors

I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))

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

Categories

Resources