replace while loop with range function - python

Can I replace while loop with range function. I am using following code
check = 0
while check<5:
print check
check+=2
I am writing in following way
for _check in range(0,5,2):
print _check
is it correct way?
> Editing My question
if I am not using _check variable inside for loop. Can I avoid to declare also

Yes, you are using range() correctly, but you may want to use xrange() instead here:
for check in xrange(0, 5, 2):
print check
xrange() produces the same results when iterated over, but doesn't build a whole list of all possible indices first, and as a result uses less memory:
>>> range(0, 5, 2)
[0, 2, 4]
>>> xrange(0, 5, 2)
xrange(0, 6, 2)
Since the end-point is not included in the values, it doesn't matter if you use 5 or 6 here as the endpoint, it is just calculated for you from the input parameters.
If you are not using the loop variable, you can use _ to indicate that you are ignoring it in the loop. This is just a naming convention:
for _ in xrange(0, 5, 2):
# do something 3 times.
in which case you may as well just calculate how many indices there are between 0 and 5 with a step of two and simplify your loop to:
upper_limit, step = 5, 2
for _ in xrange((upper_limit - 1 + step) // step):
# do something 3 times.

Regarding the original while loop, using check = check + 1
for x in xrange(5):
print x
See the documentation here for more information on control flow tools (like loops).
EDIT
If you want to increment by 2 during each iteration, you can use the above code with the increment specified:
for x in xrange(0,5,2):
print x

Related

for-loop it's not iterating completely when the array has certain size

when I have this array
A = [1,2,3]
i did this basic for-loop to iterate over the entire array except the last position
index = 0
for i in range(1,len(A)-1):
print(i)
if A[i] > A[index]:
index = i
it is suposed to do 2 iterations but when I print "i", this is the output
1
PS. I tried with this array and it worked absolutely fine
B= [7,5,14,2,8,8,10,1,2,3]
any hint about what is happening? thanks for your time
edit = I already put the index declaration
edit 2 = Problem solved
I'm assuming you want to create a list of items bigger than a certain value if so this is how:
a = 5
b = [1, 5, 6, 2, 10, 69, 42, 7]
c = []
for I in b:
if I > a:
c.append(I)
print(*c)
Your question is very unclear, what exactly is your objective?
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Syntax:
range(start, stop, step)
Here, one important thing to note is that the stop is exclusive. So, if you run a loop from 1 to len(A)-1, then actually it will run from 1 to len(A)-2, which is only one iteration in your code.
So, in order to do two iterations replace range(1,len(A)-1) with range(0,len(A)-1) or range(len(A)-1) if you want to start from index 0, or range(1,len(A)) if you want to start from 1 and do two iterations.

How can I code loop in python

I have a problem with the loop in python. I want create a list x[X0,X1,....Xn], with this algorithm:
X1=X0-(5+X0*2); X2=X1-(5+X1*2);.....
I try this but the result is not correct.
a=list(np.empty(10))
a[0]=1
for i in range(10):
a.append(a[i]-(5+a[i]*2))
print (a [i])
If you manually iterating the result gives:
[1,-6,1,-6, ....]
But after loop it gives:
[1,-1.29074375768e-231,2.19254982219e-314,.....]
The loop are easy in C but I did not understand the functioning in Python, if you have an idea ?
The problem is that list(np.empty(10)) doesn't do what you think it does. You expect it to return a list with 10 zeros, but it actually returns a list of 10 "random" numbers (actually, it returns a list of 10 uninitialized values).
From numpy docs:
empty, unlike zeros, does not set the array values to zero, and may
therefore be marginally faster. On the other hand, it requires the
user to manually set all the values in the array, and should be used
with caution.
(emphasize mine)
Instead, you should simply create a list with a single element, 1, and go on from there:
a = [1]
for i in range(10):
a.append(a[i] - (5 + a[i] * 2))
print(a)
# [1, -6, 1, -6, 1, -6, 1, -6, 1, -6, 1]
There's no reason to start your list with anything more than the single element. In C, you have to decide up front how many elements you want in your list, but that's not the case in Python, so doing list(np.empty(10)) creates a list with ten pointless elements in it that are just getting in your way.
a = [1] # This creates a list that starts off with the element 1.
for i in range(10):
a.append(a[i] - (5 + a[i] * 2))
print (a[i])
They way you have arranged your equation will constantly print out -6, and 1, therefore:
a = [1]
iti = 0
while(True):
thing = a[iti]-(5+(a[iti]*2))
a.append(thing)
iti+=1
print(thing)
I chose not to use the for loop to show a more understandable example, but you can still use that if you like.
I suggest you read up on functions, lists and for loops in python, as from your question it appears that you do not understand them very well.
There are several reasons why your code isn't currently working, but they are all easy fixed.
Firstly, you initiate a list with a numpy list, which is unnecessary.
a = list(np.empty(10))
can simply become
a = list()
or even simpler,
a = []
Next up, not an error but a suggestion,
a[0] = 1
can be removed and instead when you initialize the list, place one as the first item
a = [1]
after that, your code should work. So in summary:
n = 10 # or whatever number you want
a = [1]
for i in range(n - 1):
a.append(a[i] - (5 + a[i] * 2))
and if you want it as a function:
def formula_list(n):
a = [1]
for i in range(n - 1):
a.append(a[i] - (5 + a[i] * 2))
return a

Is this code for a for loop odd numbers generator in python valid?

a = 0
for a in range(1,99):
a = (a + 2)
y = a
print(y)
This is the code I used to try and generate odd numbers between 1 to 99.However it does not show any results. The problem is ,I wanna keep the same structure of the code , with any problems in it being rectified and I might want to add to it but I dont wanna write new code altogether as I might not understand it due to me being new at Python. Thanks in advance guys.
PS - The problem I get in this is that it prints all the numbers in the range instead of only odd ones.
Edit : 31/03/21 : Thanks to all of the people who helped me with the solution :D I asked this question when I was way younger so I apologise if it sounds really weird :D
this is more concise:
for a in range(1, 100, 2):
print(a)
The problem is that you shouldn't be modifying a inside the loop, since it is being set automatically by the range line.
a = 0 #unneeded
for a in range(1,99): #first time sets a to 1
a = (a + 2) # sets a to 3
y = a # sets y to 3
print(y) # prints y
# loop back to beginning
for a in range(1,99): #sets a to 2
a = (a + 2) # sets a to 4
y = a # sets y to 4
...
You can either change the loop iterator to a different variable: for _ in range(50):
Or you can do something more pythonic by using the range function to set a and not modify it in the loop body: for a in range(1,100,2): print(a)
In your code
a = (a + 2)
only increase value of "a".
You can get odd numbers from any type of numeric sequences in this way:
for a in range(1,100):
if a % 2 != 0:
print(a)
You could use range for this!
>>> l=1 # start
>>> r=20 # end
>>> range(l if l % 2 else l+1, r+1, 2)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Output of for loop code snippet in python

i, j, k, u = 0, 5, 1, 3
for l in range(i, j, k):
if l == u:
print(l)
u = 8
i = 12
j = 7
k = -1
else:
print(l)
OUTPUT is :
0
1
2
3
4
Why do we get this output?
When Python first encounters the for loop, it builds the range object you requested: range(0, 5, 1). Once constructed, it controls the loop, and will not be reevaluated. Changing the variable values during loop execution will not change the loop operation.
This means that, as far as the loop (or a sufficient optimizer) is concerned, your code looks like this:
i,j,k,u=0,5,1,3
for l in range(i,j,k) :
print(l)
u=8
i=12
j=7
k=-1
Not sure what output you expect. But since you change the values of the parameters used for generating the range I assume that you expect the output to be longer. At that point the list is already generated however and will not be affected.
In order to achieve the possibility of increasing the loop range during the looping I suggest you avoid the range function and consider using while instead of for.
https://docs.python.org/3/tutorial/controlflow.html
Edit: Prune was both faster and better than me.

Counting down and then up

I'm new to python and trying to run a function that will, given one variable, count down to zero and then up to the original variable. the output should look something like this:
>>> functionname(5)
5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5
so far I've written the code below, but this doesn't count up all the way to the original variable. I guess I need to somehow save the variable in order to refer to it later, but I have no idea how to do that, since python automatically changes n as the function goes on.
def functionname(n):
n = orginal
while n > 0:
print n
n=n-1
print n
if n==0:
print n
n=n+1
I would be very grateful for some pointers, as I seem to be completely stuck at the moment.
Just count from negative to positive and use math:
def fn(n):
print ', '.join(str(abs(i)) for i in range(-n, n+1))
fn(5)
# 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5
Pointers:
If you already know the range you want to iterate over, it's much cleaner and more direct to use a for loop instead of a while.
You can use the range function to generate number sequences.
You can convert simple for loops into list-comprehensions as I did above.
The "simple" clean implementation of your requirements would look something like this:
def fn(n):
for i in range(n, 0, -1):
print i,
for i in range(n + 1):
print i,
Other notes:
range can count backwards too
The end argument to range isn't included in the range itself, that's why the second loop specifies n + 1 as the limit (instead of just n)
Adding a trailing comma on your print makes it add a space at the end instead of a line-break.
Your second block is an if n == 0: (which you know it is since the while loop terminated when n hit 0); presumably you want while n <= 5.
Note that there are nicer ways to accomplish the same thing in Python. For example, using a pair of ranges with itertools.chain to iterate each range one after another allows you to simplify to:
import itertools
def functionname(n):
for i in itertools.chain(range(n, 0, -1), range(n+1)):
print i
Personally, I'd do something like...
def count(n):
for x in range(n, -n, -1):
print(str(abs(x)) + ",")
At the suggestion of dlewin, here's a list comprehension of the same...
def count(n):
print(','.join(str(abs(x)) for x in range(n, -n, -1)))
You need a second while loop that starts at 0 and goes back up to "original".
Do you know about "for" loops yet? Those are better for counting.
Your idea about having original is correct however you are using the assignment operator the wrong way 'round. Also the if n==0 line should be another loop (while or for as suggested by other answers), counting back up to original.
So I'd start with copying the value from n to original like this:
original = n
Hope that helps!
You got some bad formatting there. Remember to indent properly for functions and while and if statements.
So first, set n to 5. Then count down from there until you reach 0 with a while loop:
while n != -1:
print n
n -= 1
Then after the loop breaks, count back up again and reset n to 0:
n = 0
while n < 6:
print n
n += 1

Categories