Python Forum
I'm having trouble printing a return value in my main function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I'm having trouble printing a return value in my main function
#1
I'm missing something very basic here. The following code:
#!/usr/bin/env python3
#QuickTest.py
def summ(numThree,numFour):
    result = numThree + numFour
    return result

def main():
    numThree = 3
    numFour = 4
    summ(numThree,numFour)
    print(result)

main()
Gives this error:
Error:
========== RESTART: I:/Python/Python36-32/SamsPrograms/QuickTest.py ========== Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/QuickTest.py", line 13, in <module> main() File "I:/Python/Python36-32/SamsPrograms/QuickTest.py", line 11, in main print(result) NameError: name 'result' is not defined >>>
I was expecting it to print 7. What's wrong?
Reply
#2
!/usr/bin/env python3
#QuickTest.py
def summ(numThree,numFour):
    result = numThree + numFour
    return result
 
def main():
    numThree = 3
    numFour = 4
    result = summ(numThree,numFour)
    print(result)
 
main()
summ returns a value but it is not assigned to anything. The 'result' variable is local to summ function and it exists as long as the function is running. However you can create another 'result' variable in main function which is local to main. Both are not in conflict.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
result is not a global variable. It is defined inside of summ(), but main() has no idea what it is. You either need to define it in main() and then pass it into summ(), or just define it globally.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  nested function return MHGhonaim 2 624 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  Printing the variable from defined function jws 7 1,337 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,312 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  function return boolean based on GPIO pin reading caslor 2 1,193 Feb-04-2023, 12:30 PM
Last Post: caslor
  Run a Function?: Trouble with Online Python Course webmanoffesto 3 1,012 Aug-18-2022, 10:14 PM
Last Post: deanhystad
  Function global not readable by 'main' fmr300 1 1,357 Jan-16-2022, 01:18 AM
Last Post: deanhystad
  return vs. print in nested function example Mark17 4 1,757 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  How to invoke a function with return statement in list comprehension? maiya 4 2,867 Jul-17-2021, 04:30 PM
Last Post: maiya
  Function - Return multiple values tester_V 10 4,470 Jun-02-2021, 05:34 AM
Last Post: tester_V
  Get return value from a threaded function Reverend_Jim 3 17,156 Mar-12-2021, 03:44 AM
Last Post: Reverend_Jim

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020