Reputation: 153
I'm trying to return the result of an operation in a function but I can't, I'm very sure the error it's pretty clear but I can't see it and I think this is the normal structure to make a return on a function.
This is the code:
#coding=utf-8
def sum_function(num1, num2):
result=num1+num2
return result
num_1=int(input("Please type a number: "))
num_2=int(input("Please type another number: "))
sum_function(num_1, num_2)
print(result)
This is the script running:
Please type a number: 1
Please type another number: 2
This is the error:
Traceback (most recent call last):
File "functions_practice.py", line 13, in <module>
print(result)
NameError: name 'result' is not defined
shell returned 1
I've seen some videos and blogs but I still don't understand.
Upvotes: 0
Views: 74
Reputation: 110
everything you have is correct except for one small thing. When you define a function and want to get something back as a return value, you need to set a variable in your main code equal to the function call. Think of it like the function itself being a variable. For example:
function_result = sum_function(num1, num2)
when you declare this, whatever the value is you want to return from "sum_function(num1, num2)" will be passed into the new variable "function_result".
You are then able to use "function_result" to print, or manipulate however you like! So, your solution would look like this:
def sum_function(num1, num2):
result=num1+num2
return result
num_1=int(input("Please type a number: "))
num_2=int(input("Please type another number: "))
function_result = sum_function(num_1, num_2)
print(function_result)
Upvotes: 1
Reputation: 11
Your issue is that "result" is a local variable. You can only access it from within the sum_function
function. If you want to print the result, try print(sum_function(num1, num2))
.
Upvotes: 1
Reputation: 1
The variable "result" is a local variable and it can be used just inside the function sum_function()
Upvotes: 0