python: How can I print y as a function of x?

  • A+

I have a larger Code and for that i need to solve a small problem so i made a test script only consisting of that problem.

How can I change it that it prints 4 9 16 25 36 right now it prints 4 4 4 4 4

x = 2 y = x**2  for i in range(5):     print(y)     x += 1 


Create a function!

x = 2  def y(x):     return x**2  for i in range(5):     print(y(x))     x += 1 

If you want something more elaborate, more verbose, but a little bit unreadable (although in this case I'd recommend it because of how short the function is), you can also use a lambda:

y = lambda x: x**2 

The statements are equivalent


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: