-1

I want to take user input and square it by using lambda function

why doesn't this code work?

def my():
    x = int(input('Please enter a number: '))
    y = lambda x: x**2
    print(y)
wkl
  • 77,184
  • 16
  • 165
  • 176
ana
  • 1
  • A lambda is just a shortcut way to define a function right at the point it is used - it's rather silly to assign one to a name, you might as well just use an ordinary `def` and not have to deal with the limitations of a lambda. Anyway, you never actually called the function; printing the function itself is unlikely to be useful. – jasonharper Sep 01 '22 at 02:24
  • I think your problem here is you created a `lambda` that has its own `x` in scope, it's not referencing the `x` you assigned to the `input`. So instead, `y` is now a lambda that takes an argument, so doing `print(y(x))` would do what you want. However, I don't know why you'd do this compared to just doing `x ** 2` directly and not via a lambda (for this example, at least). – wkl Sep 01 '22 at 02:24
  • Does this answer your question? [How are lambdas useful?](https://stackoverflow.com/questions/890128/how-are-lambdas-useful) – TheFungusAmongUs Sep 01 '22 at 04:34
  • thanks for these suggestions. the assignment asks to use lambda and user input together and I struggle to combine them. I agree that assigning a name to lambda is silly... can you suggest a different approach? – ana Sep 01 '22 at 14:53

1 Answers1

0

y is the function, rather than the value the function returns;

def my():
    x = int(input('Please enter a number: '))
    y = lambda i: i**2
    print(y(x))
bn_ln
  • 1,648
  • 1
  • 6
  • 13