简体   繁体   中英

How would I add something to a number over and over again in Python

I am trying to add numbers in python. I know that it would be x + 3 when you are adding it, but when I try to do it with the program I am writing, it doesn't work out how I want it to be! Here is the code:

x = 0 

list = []

for i in range (1,100):
  y = x + 3 
  list.append(y)
print (list)

and the output we get is :

[3,3,3,3,3,3...]

When I want it to be:

[3,6,9,12,15]

Can someone please tell me what I am doing wrong?

Thanks!

You need to assign the result back to x so that it accumulates the values. You keep adding to the original value of x , since x never changes.

x = 0
l = []
for i in range(1, 100):
    x += 3
    l.append(x)

print(l)

BTW, don't use list as the name of a variable. It's the name of a Python built-in function.

x is always 0, so you keep running y = 0 + 3 , then adding that to the list

You dont need a y variable at all, you can run this in your loop

x += 3
lst.append(x)

Or, maybe simpler

lst = [x*3 for x in range(1, 100)]

Your not increasing or incrementing the variable x. So after the statement list.append(y), in a new line, add x+=3

You can do this: you are not updating the x so you keep adding the original x value. so x have to be updated. but since you have y you can do this.

y = 0
mylist = []
for i in range (1,100):
  y += 3
  mylist.append(y)
print (mylist)

or do this you can just update the x value, then it works.

x = 0
mylist = []
for i in range (1,100):
  y = x + 3
  x += 3 #update the x variable
  mylist.append(y)
print (mylist)

And don't use list as the name of a variable. It's the name of a Python built-in function. In python so use another word like mylist or something.

this will help

x = 0 

list = []

for i in range (1,100):
    y= x+i*3
    list.append(y) 
print(list)

You don't need the variable x,

Change the line y=x+3 to y=i*3

In your script you are not redefining the value of x each time so you are doing 0+3 countless times. I is the index of the loop so will increase after each iteration, allowing you to have an increasing value in the list output

You can write it in one line like this:

[x for x in range(1, 100) if x % 3 == 0]

or:

[x*3 for x in range(1, 100)]

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