Reputation: 65
HI I wonder if you can help me with this
I want to print the values between 1 and 2 starting from 1 and add x to it until the value reaches 2.
I try to do it but it only prints 1.0625
x = 1/16
for i in range(1,2):
b = i + x
print(b)
I want it to print
1.0625
1.125
1.1875
1.25
1.3125
1.375
1.4375
1.5
1.5625
1.625
1.625
1.75
1.8125
1.875
1.9375
Thank you very much
Upvotes: 0
Views: 2139
Reputation: 39354
You have to increment i
in each loop iteration, instead of redeclaring the i
value.
x = 1/16
i = 1 + x
while i < 2:
print(i)
i += x
Upvotes: 0
Reputation: 109546
If you run your code as:
for i in range(1, 2):
print(i)
then you will see that it only loops once and prints 1
. As you can see in the documentation for range sequence types, it only deals with integers.
Rather than using a for
loop over a range, you may want to use a while
loop:
x = 1 / 16
i = 1
while i < 2 - x:
i += x
print(i)
# Output:
1.0625
1.125
1.1875
1.25
1.3125
1.375
1.4375
1.5
1.5625
1.625
1.6875
1.75
1.8125
1.875
1.9375
Upvotes: 1
Reputation: 9197
You do not need to add the steps between 1 and 2 seperately, the third argument of the range function lets you the the step size, here 1/16.
The steps between 1 and 2 are not integers, they are float numbers. Unfortunately Pythons .range()
is unable to handle that natively. One option is to use numpys arange() which can handle float steps.
To print each value of a list you can use a *
in front of the list. This tells the print command that it shall print each value in the list instead of the whole list.
since you want a new line for each value you can also set the seperator parameter of the print function: sep="\n"
. This means each line is seperated by "\n" which is a linebreak in python console.
import numpy as np
print(*np.arange(1, 2, 1/16), sep="\n")
output:
1.0
1.0625
1.125
1.1875
1.25
1.3125
1.375
1.4375
1.5
1.5625
1.625
1.6875
1.75
1.8125
1.875
1.9375
Upvotes: 2
Reputation: 71454
Using a range
doesn't work well here because ranges work with integers, and you want to work with fractions. You could coerce it by mapping your fractional range to an integer range via multiplication and division, but that seems unnecessarily complex to me.
Just taking your statement:
starting from 1 and add x to it until the value reaches 2.
and phrasing it literally as code, we have a very simple approach:
b = 1
while b < 2:
b += x
print(b)
Upvotes: 0
Reputation: 788
You can use numpy's arange function as already suggested, or you can use a while loop like in the example below. The problem with python's range funtions is that it only accepts integers as arguments.
x = 1/16
import numpy as np
for i in np.arange(1,2,x):
print(i)
value = 1.0
while value < 2:
print(value)
value = value + x
Upvotes: 0
Reputation: 4482
You might use np.arrange
:
import numpy as np
np.arange(1,2,x)
Output
array([1. , 1.0625, 1.125 , 1.1875, 1.25 , 1.3125, 1.375 , 1.4375,
1.5 , 1.5625, 1.625 , 1.6875, 1.75 , 1.8125, 1.875 , 1.9375])
Upvotes: 0