Python Forum
Storing whole functions in variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Storing whole functions in variables
#1
When i print y, why does it say none? instead of returning the value from the function called
x = 1

def edr(x):
    x+2
    print(x)
#Here i try to understand variables to store an function in a variable
y = edr(x)
#It says none and i thought it would  either call the function or get the value of x
print(y)
Reply
#2
First, you're not storing the function in the variable, you're storing its return value. You need an explicit return statement in named functions, since there isn't one, the function implicitly returns None.
dedesssse likes this post
Reply
#3
I understand now, thanks
Reply
#4
You can use a lambda expression to bind a function and an argument to be called later.
x = 1

def edr(x):
    return x + 2

y = lambda: edr(x)

print(edr, y, y(), edr(x))
Output:
<function edr at 0x00000193D86AF0D0> <function <lambda> at 0x00000193D8B94160> 3 3
edr without the () is a function.
y is a lambda expression that will call the function edr with the argument x.
y() evaluates the lambda expression (calls the function) and returns the result.
edr(x) calls the function edr() with the argument x.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using variables with functions imported from different files. Scordomaniac 3 1,262 May-24-2022, 10:53 AM
Last Post: deanhystad
  Storing variables into one file for use in multiple Jupyter notebooks devansing 1 1,722 Feb-05-2022, 10:04 AM
Last Post: ibreeden
  Getting parent variables in nested functions wallgraffiti 1 2,120 Jan-30-2021, 03:53 PM
Last Post: buran
  module to store functions/variables and how to call them? mstichler 3 2,372 Jun-03-2020, 06:49 PM
Last Post: mstichler
  Issues with storing variables outside of a function cerulean747 7 3,694 Apr-30-2020, 08:46 AM
Last Post: DeaD_EyE
  local/global variables in functions abccba 6 3,412 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Python 2.7 passing variables from functions zetto33 1 1,771 Mar-19-2020, 07:27 PM
Last Post: Larz60+
  How to plot implicit functions (with two variables) in scipy python using matplotlib? Jay_Nerella 1 7,917 May-11-2019, 01:17 AM
Last Post: scidam
  Use Variables Generated from Functions in different files to use on the main file AykutRobotics 3 2,920 Jan-01-2019, 04:19 PM
Last Post: AykutRobotics
  How can classes access each other Functions and Variables at the same time PythonOK 4 3,032 Dec-09-2018, 03:46 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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