Python Forum

Full Version: How do I print a returned variable calculated in another function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all. My comprehension of how to use scope is not clicking. From the following code:

#!/usr/bin/env python3
#PracticePythonExercise01.py

#Create a program that asks the user to enter their name and their age.
#Print out a message addressed to them that tells them the year that they
#will turn 100 years old.

def yearThatYouTurn100():
    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    year = int(input("Enter the current year: "))
    yearsBefore100 = 100 - age
    yearAt100 = year + yearsBefore100
    return yearAt100

def main():
    yearThatYouTurn100()
    print(yearAt100)

main()
I get the error:
Error:
>>> ================================ RESTART ================================ >>> Enter your name: sam Enter your age: 30 Enter the current year: 1988 Traceback (most recent call last): File "F:/Python/Python36-32/SamsPrograms/PracticePythonExercise01.py", line 20, in <module> main() File "F:/Python/Python36-32/SamsPrograms/PracticePythonExercise01.py", line 18, in main print(yearAt100) NameError: name 'yearAt100' is not defined >>>
No I don't want to print yearAt100 in the function that calculated it, because I'm still struggling to learn why I can't get the main function to recognize it.
yearAt100 is local to the function yearThatYouTurn100. Once the function is over (after "return"), the variable ceases to exist for the rest of the program.

So what you should do is store the returned result in a variable, which you can then print:

def main():
    result = yearThatYouTurn100()
    print(result)
result will hold the value returned by the function.
This principle works generally for functions, and for any data types you might want to return.
you can also declare the variable "yearAt100" globally and access it anywhere in the program,

#!/usr/bin/env python3
#PracticePythonExercise01.py
 
#Create a program that asks the user to enter their name and their age.
#Print out a message addressed to them that tells them the year that they
#will turn 100 years old.
yearAt100 = 0
def yearThatYouTurn100():
    global yearAt100
    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    year = int(input("Enter the current year: "))
    yearsBefore100 = 100 - age
    yearAt100 = year + yearsBefore100
    return yearAt100
 
def main():
    yearThatYouTurn100()
    print(yearAt100)
 
main()
(Jul-10-2018, 11:26 AM)Prabakaran141 Wrote: [ -> ]you can also declare the variable "yearAt100" globally and access it anywhere in the program,
Using globals is considered bad practise and generally discouraged. Please, don't suggest that and don't use it in your code. And just for completeness - if you do use globals, your function does not need the return statement. But again, don't do that.