You can even return several values from one function and then store these in separate variables:
def get_profile():
firstname = input("What is your first name? ")
lastname = input("What is your last name? ")
age = int(input("What is your age? "))
return firstname, lastname, age
fname,lname,user_age = get_profile()
In this example, I have used different variable names when calling the function from the variable names inside the function. While this is good practice, as it helps the programmer distinguish between them, it is not actually necessary in Python. In other words, I could have called the function like this:
firstname,lastname,age = get_profile()
Variables defined inside a function, like firstname, exist in isolation from other variables and only whilst the function is run. This is their scope. Variables defined in the main program, rather than within functions, exist for the duration of the program and are said to be global in scope. If you want a function to have access to variables outside its own scope, best practice would be to add them as parameters to the function:
am = "Good Morning"
pm = "Good Evening"
def get_profile(msg):
print (msg)
firstname = input("What is your first name? ")
lastname = input("What is your last name? ")
age = int(input("What is your age? "))
return firstname, lastname, age
#Function called passing in variable from global scope
fname,lname,user_age = get_profile(am)
Once you’ve got to grips with creating your own functions, you can begin to add more structure to your programs, taking each component of the program and creating a reusable function from it.
For example, imagine you wanted to create a program that could send Morse code messages by blinking a single LED. This problem can be broken down into a hierarchy of functions.
The highest or most abstract function might be morseMessage(), whose job is to take a given string and turn it into a Morse sequence. To do this, it will call charLookup() for each character in turn, and then the relevant dot, dash, and pause functions.
The charLookup() function looks up a given character and determines the correct sequence of dots, dashes and pauses for that character. This sequence is returned as a string to the morseMessage() function.
The dot(),dash(), and pause() functions receive no input, and simply turn the LED on and off for the appropriate lengths of time to represent dots and dashes.
You could represent this as a diagram, like this: