Blank Blank
Blank Blank

Reputation: 129

How to print out values in steps of 10 using a for loop?

this code prints out the values from -30 up to 40, but I need it to print out the values from -30 to 40 in steps of 10.

for x in range(-30, 40):
        print(x)

Can someone help me? I wasn't able to find anything when googeling this problem.

Upvotes: 0

Views: 1587

Answers (3)

Joe Iddon
Joe Iddon

Reputation: 20434

Following the documentation:

The documentation defines range as taking three arguments:

range(start, stop[, step])

The last argument, step, is the interval for each loop. So, to loop x in intervals of 10, we can set the step argument to 10:

for x in range(-30, 40, 10):
   print(x)

which prints out the following values for x:

-30
-20
-10
0
10
20
30

N.B. that as range stops when it reaches the stop argument (exclusive), 40 is not included.

Upvotes: 1

dalonlobo
dalonlobo

Reputation: 503

Since print in python 3+ is a function, you can achieve the same result using:

Code:

print(*range(-40, 41, 10), sep="\n")

output

-40
-30
-20
-10
0
10
20
30
40

Basically print will unpack the range and use separator \n.

Upvotes: 0

MSeifert
MSeifert

Reputation: 152775

The third argument for range is the step, so just use:

for x in range(-30, 40, 10):
    print(x)

However note that the stop is exclusive, so if you wanted to include 40 it should be:

for x in range(-30, 41, 10):
    print(x)

Upvotes: 3

Related Questions