Home > Software design >  Transferring variables between functions Python
Transferring variables between functions Python

Time:10-07

def name():
        name=input("what is your name?")
        print()
def print():
        print(name)

Hello new to programming!

I'm making a simple game and need to transfer names and scores through different functions much like the code displayed. Is there a way to make this work (Python)

CodePudding user response:

If you want a value from a function the clearest and most standard way to do it is to return the value:

def ask_name():
    name = input("what is your name?")
    return name # this gives the value back to the calling function

def another_function():
    name = ask_name() # this assigns the returned value to the variable "name"
    print(name)

Also, don't define functions with the same name as built-in functions like print():

def print(name_to_print):
    print(name_to_print)

If you call this function it will not print anything. Rather, when it calls print(name_to_print) it will call itself, not the built-in print(). Then that will call it self again over and over again until your program fails with the error "RecursionError: maximum recursion depth exceeded".

CodePudding user response:

Don`t name your function print() because like this you will overwrite print() function in standard python library.

you can make name global like this:

def name():
        global name
        name = input("what is your name?")
        PrintName()

def PrintName():
        print(name)

or you can return and pass args like this:

def name():
        name=input("what is your name?")
        PrintName(name)

def PrintName(name):
        print(name)
  • Related