简体   繁体   中英

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

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

you can wrap it in list comprehension

x = 2
[(x+i) ** 2 for i in range(5)]
[4, 9, 16, 25, 36]

I think you want like this.

x=2

def Square(x):

y=x**2

print(y)

for i in range(5):

Square(x)

x+=1

You used mathematical equation, but make y as a global variable. So if you want to insert a value and get a new result each time, you should define function(s) of your own. It is also good to use what has already been created.

I hope this helps anyway.

An alternative approach could be:

Define a function with two arguments. The down and upper limit of your list's range. Then return a list with those numbers squared.

def squared(start, upper):
    return [n**2 for n in range(start, upper)]

print squared(2, 10)

But if you just need a function to return a given input squared, then:

def squared(x):
    return x**2

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

Explanation: you have calculated y at once only. Based on your requirement, the calculation should be done whenever x is changed. So added in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM