Get value from function python

How does return() in Python work?

In order to get a value from a function in any programming language, we use the return() statement. Likewise, in Python, the return() statement is used to exit a function and returns a value from a function. In this tutorial, we will read about various ways to use the return() statements in Python.

Table of contents

  1. Introduction to return() statement
  2. Returning Multiple Values in Python
  3. Argument in return() function
  4. Function returning another function
  5. Closing thoughts

return() in Python

The return() statement, like in other programming languages ends the function call and returns the result to the caller. It is a key component in any function or method in a code which includes the return keyword and the value that is to be returned after that.
Some points to remember while using return():

  • The statements after the return() statement are not executed.
  • return() statement can not be used outside the function.
  • If the return() statement is without any expression, then the NONE value is returned.

Syntax of return() in Python:

 def func_name(): statements. return [expression] 

Using a return() statement for returning multiple values in Python

Python also gives an option to return multiple values from a function and in order to do that the user just needs to add multiple return values separated by commas. Also known as a tuple, can be created with or without using the ().

Input:

 def statFun(a, b): difference = a-b percent_diff = (difference/a)*100 return difference, percent_diff; difference, percent_diff = statFun() print (difference) print (percent_diff) 

Here, the function statFun() gives to values and by using tuple we return both of the values.

Output:

return() in Python with an argument

In Python, arguments can be used with a return statement. To begin with, arguments are the parameter given by the user and as we know, the argument is the value(s) as input, which is given by the user to the function.

Input:

 def divNum(a, b): if b != 0 return a/b; else: return 0; print (divNum(4, 2)) print (divNum(2, 0)) 

Here, the function divNum() accepts two arguments and if the second argument is non zero it divides them otherwise returns 0.

Читайте также:  INS

Output:

Function returning another function in Python

As we know functions are treated as first-class objects in Python, therefore we can return a function from another function. A first-class object is an object that can be assigned to a variable, passed as an argument to a function, or used as a return value in a function.
A function that takes a function as an argument, returns a function as a result, or both is known as a higher-order function.

Input:

 def func_1(a): def func_2(b): return a-b return func_2 x = func_1(100) print ("The value of a-b is", x(50)) def another_func(a): return a*10 def func(): return another_func y = func() print ("\nThe value of a*b is" y(10)) 

Output:

 The value of a-b is 50 The value of a*b is 100 

Closing thoughts

The return statement sends any object from the function back to the caller code. Since the return statement is a key part of any function or method, if you learn how to use it correctly, you can move to complex codes. One can learn about more Python concepts here.

Источник

Get Variable from Function in Python

A function is a reusable piece of code that can be called at different places in a program. A function can execute some statements when called and return some value if desired. Any variable declared within the function cannot be accessed from the outside.

We will discuss how to get variable from function in Python.

Using the return statement to get variable from function in Python

The return statement in Python is used to return some value from a function in Python. Since we cannot access the variable defined within the function from the outside, we can return it using the return statement to get variable from function in Python.

We can also return multiple variables. For this, we can use objects like lists, dictionaries, and more. We will store the variables in one such object and return it from the function.

In the above example, we return a dictionary from the function. We access the variable values using the variable’s key from the dictionary and print it.

Using attributes to get variable from function in Python

Everything is an object in Python, even functions. We can assign functions with some arbitrary values that can work as attributes. These values can be accessed from outside a function. This way, we can get variable from function in Python.

In the above example, we assign an attribute value to the function. We first call this function and then we can use this variable using the function name.

Further reading:

Get variable name as String in Python
Check if variable is String in Python

Conclusion

In this tutorial, we discussed how to get variable from function in Python. There is no direct way to access a variable declared within the function from outside. So, to get variable from function in Python, we can directly return the value. We discussed how to return single and multiple variables. Another way to get variable from function in Python is by assigning them as attributes of the function. This way, we can access the attribute values after calling the function.

Читайте также:  Java stream sort by string

Источник

Python return Statement

Understanding The Python Return Statement

In Python, the return statement exits a function and returns the specified value to the caller. Multiple return statements may exist in a function, but only the one that fulfils the specified condition first is executed.

The return keyword is one of the built-in keywords in Python which is also used for increasing readability and writing clear code in Python.

This tutorial will cover all the fundamental things you should know about return statements in Python.

Understanding the Python return Statement in Functions

  • The Python return statement is used in a function to return something to the caller program.
  • We can use the return statement inside a function only.
  • In Python, every function returns something. If there are no return statements, then it returns None.
  • If the return statement contains an expression, it’s evaluated first and then the value is returned.
  • The return statement terminates the function execution.
  • A function can have multiple return statements. When any of them is executed, the function terminates.
  • A function can return multiple types of values.
  • Python functions can return multiple values in a single return statement.

Syntax of Python return Statement

The syntax is straightforward, it consists of the keyword return followed by an expression.

Here the expression can be anything like an expression that can be evaluated to a value, the actual value, or even a function that we want to return to the caller.

Python return Statement Example

Let’s look at a simple example of a function that takes two numbers to perform a calculation and return the total to the caller.

def add(x, y): total = x + y return total

We can optimize the function by having the expression in the return statement.

Let’s do a function call by passing two arguments, then print the result we got.

result = add(5, 3) print(result)

See, here we got the sum, meaning the function successfully returned the total value.

Every Function in Python returns Something

Let’s see what is returned when a function doesn’t have a return statement.

>>> def foo(): . pass . >>> >>> print(foo()) None >>>

We got “None”, so if we didn’t pass a return statement and try to access the function value, by default it returns None.

Python return Statement without any Value

When the return statement has no value, the function returns None.

>>> def return_none(): . return . >>> print(return_none()) None >>>

So, either you have used a return statement with no value, or there is no return statement, and the function returns None.

Читайте также:  Среднее значение stream java

Python Functions can have Multiple return Statements

A function can have multiple returns, the one that satisfies the condition will be executed first and the function will exit.

def type_of_int(i): if i % 2 == 0: return 'even' else: return 'odd' result = type_of_int(7) print(result)

Python Functions return Multiple Types of Values

Unlike other programming languages, Python functions are not restricted to returning a single type of value. If you look at the function definition, it doesn’t have any information about what it can return.

Let’s look at an example where the function will return numbers of values having multiple types.

def get_demo_data(object_type): if 'str' == object_type: return 'test' elif 'tuple' == object_type: return (1, 2, 3) elif 'list' == object_type: return [1, 2, 3] elif 'dict' == object_type: return else: return None print(get_demo_data('str')) # Output: 'test' print(get_demo_data('tuple')) # Output: (1, 2, 3) print(get_demo_data('list')) # Output: [1, 2, 3] print(get_demo_data('dict')) # Output: print(get_demo_data('set')) # Output: None

Returning Multiple Values from a Function in a Single return Statement

A function can have multiple return values in a single statement. These values are separated by a comma and returned to the caller program as a tuple.

def return_multiple_values(): return 1, 2, 3 print(return_multiple_values()) print(type(return_multiple_values()))

Python return Statement with finally block

When the return statement is executed inside a try-except block, the finally block code is executed first before returning the value to the caller.

def hello(): try: return 'hello try' finally: print('finally block') def hello_new(): try: raise TypeError except TypeError as te: return 'hello except' finally: print('finally block') print(hello()) print(hello_new())
finally block hello try finally block hello except

If the finally block has a return statement, then the earlier return statement gets ignored and the value from the finally block is returned.

def hello(): try: return 'hello try' finally: print('finally block') return 'hello from finally' print(hello())
finally block hello from finally

Summary

A return value in a function is the value that it sends back to the caller after it is finished executing. In other words, we can say that the return statement is the last statement that a function or method executes before it terminates. We can even return a function from another function. A function without a return statement or a return statement without a value returns None by default.

The return statement is certainly not an essential aspect of writing valuable functions because the main purpose of creating a function is to encapsulate a block of code in order to reuse that code. But it is the most important part of creating a function as it makes the function more feature-full and readable, so the next time you are creating a function, try using return instead of using the print statement.

Источник

Оцените статью