Shark
Shark

Reputation: 21

for loop create a list around "x" based on "n"

Basically trying to figure out how to create a for loop that generates a range around a the main number "x" based on "n"

x = 10                  # x = Actual
n = 5

because

Actual = input("What's the Actual")  # Enter 10
Target = input("What's the Target")  # Enter 15



n = Target - Actual  # 5 = 15 - 10

Since Actual is 10

I would like to see..

5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15 

The code is:

n = 2
def price(sprice):
     for i in range(n*2):
        sprice = sprice + 1
        print(sprice)

price(200)

This code shows 201,202,203,204 and the actual is 200. I want to see 198,199,200,201,202 because n = 2 and when multiply by 2 = 4 which shows a range of 4 values around 200

Upvotes: 0

Views: 46

Answers (2)

Daweo
Daweo

Reputation: 36620

ForceBru has already shown a pythonic solution to your problem. I only want to add that your original code works as intended after some minor tweaks:

n = 2
def price(sprice):
    sprice -= n # short way to say: sprice = sprice - n
    for i in range(n*2+1): # +1 required as in 1-argument range it is exclusive
        sprice = sprice + 1
        print(sprice)
price(200)

Output:

199
200
201
202
203

Note that Python recognizes * is to be executed before + independently from its order. Hence you might write 1+n*2 in place of n*2+1.

Upvotes: 1

ForceBru
ForceBru

Reputation: 44878

According to the docs, range can accept two argument that specify the start (inclusive) and end (exclusive) of the interval. So you can get an interval in the form [start, stop).

You would like to create the interval [Actual - n, Actual + n], so just translate it almost literally to Python, bearing in mind that range excludes the second argument from that range, so you should add one to it:

>>> list(range(Actual - n, Actual + n + 1))
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Upvotes: 3

Related Questions