Want to skip number while performing for loop - python-2.7

While using for loop in python whatever range we initially define that is fixed.
In any case can we skip at some step like.code give i={0,1,2,3,4,5,6,7,8,9)
I want
i={0,1,2,3,4,8,9}
for i in range(0,10):
print i
if(i==4):
i=i+3

you can use list and in the loop check the list.
listinfo = [0,1,2,3,4,8,9]
for i in range(0,10):
if i in listinfo:
#do your stuff

The reason your code doesn't work is that every iteration of the for-loop begins by setting the value of i to the next item in the range, meaning that it doesn't matter how you set i during the loop's body.
Instead, you can have the loop body only execute for certain values like this:
for i in range(10):
if i not in range(5, 8):
print(i)

Related

How to check through an entire list in Python for a condition fulfillment

So I'm trying to make a single line to check if a single element in Python list fits the criteria, but my current code will keep the loop going even if it hits a "True" -mark and thus only the last element counts for the check:
if [[CheckStatus(value, outsidevalue)] for value in valuelist] is True:
magic
(CheckStatus returns either True or False for every single value compared to outsidevalue and is supposed to accept is as true if a single value returns True)
that will always be false:
if [[CheckStatus(value, outsidevalue)] for value in valuelist] is True:
because you're comparing a list with a boolean.
What you want is any:
if any(CheckStatus(value, outsidevalue) for value in valuelist):
any iterates on the generator comprehension, calling your function on all elements until True is found (note that the inside square brackets have been removed, and we don't need to create a list comprehension, just a generator comprehension, which is faster)

Could not exit a for .. in range.. loop by changing the value of the iterator in python [duplicate]

This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 6 years ago.
I have the following script:
for i in range (10):
print i
i = 11
When i execute this script, I was expecting to print out only 0, but instead, it prints out 0 to 9. Why i=11 did not stop the for loop?
changing i inside the for-loop have no effect how many iterations are performed because that is controlled by how many elements are inside range or in whatever you are looping in, likewise it don't have any effect in which value i will have in the next iteration.
Internally a for loop like this
for elem in iterable:
#stuff
#other stuff
is transformed to something like this (for any stuff and for any iterable)
iterator = iter(iterable)
while True:
try:
elem = next(iterator)
#stuff
except StopIteration:
break
#other stuff
the iterator constructed by iter will trow a StopIteration exception when there are no more elements inside it, and to get the next element you use next. break is used to end a for/while loop and the try-except is used to catch and handled exceptions.
As you can see, any change you do elem (or i in your case) is meaningless to how many iteration you will have or its next value.
To stop a for-loop prematurely you use break, in your case that would be
for i in range(10):
print i
break

Finding length of list without using the 'len' function in python

In my High school assignment part of it is to make a function that will find the average number in a list of floating points. We can't use len and such so something like sum(numList)/float(len(numList)) isn't an option for me. I've spent an hour researching and racking my brain for a way to find the list length without using the len function, and I've got nothing so I was hoping to be either shown how to do it or to be pointed in the right direction. Help me stack overflow, your my only hope. :)
Use a loop to add up the values from the list, and count them at the same time:
def average(numList):
total = 0
count = 0
for num in numList:
total += num
count += 1
return total / count
If you might be passed an empty list, you might want to check for that first and either return a predetermined value (e.g. 0), or raise a more helpful exception than the ZeroDivisionError you'll get if you don't do any checking.
If you're using Python 2 and the list might be all integers, you should either put from __future__ import division at the top of the file, or convert one of total or count to a float before doing the division (initializing one of them to 0.0 would also work).
Might as well show how to do it with a while loop since it's another opportunity to learn.
Normally, you won't need counter variable(s) inside of a for loop. However, there are certain cases where it's helpful to keep a count as well as retrieve the item from the list and this is where enumerate() comes in handy.
Basically, the below solution is what #Blckknght's solution is doing internally.
def average(items):
"""
Takes in a list of numbers and finds the average.
"""
if not items:
return 0
# iter() creates an iterator.
# an iterator has gives you the .next()
# method which will return the next item
# in the sequence of items.
it = iter(items)
count = 0
total = 0
while True:
try:
# when there are no more
# items in the list
total += next(it)
# a stop iteration is raised
except StopIteration:
# this gives us an opportunity
# to break out of the infinite loop
break
# since the StopIteration will be raised
# before a value is returned, we don't want
# to increment the counter until after
# a valid value is retrieved
count += 1
# perform the normal average calculation
return total / float(count)
def length_of_list(my_list):
if not my_list:
return 0
return 1+length_of_list(my_list[1:])

returning to a loop when it doesn't meet a certain condition

So I have a while loop that calculates the value of a variable for me.
If that variable does not reach the condition that I want to, is it possible to return to the while loop and insert new variables, and keep returning to the loop until I get the condition that i want.
balance=3329
annualInterestRate=0.2/12
month=0
min_pay=10
while month<12:
new_bal=balance+(balance*annualInterestRate)-min_pay
balance=new_bal
month=month+1
if balance>0:
min_pay+=10
So if by the end of the loop the balance>0 then I want to add 10 to min_pay and go through the loop with the original values. And I want it to keep going until balance<=0
Yes, you can use a nested while loop:
min_pay=10
while True:
balance=3329
annualInterestRate=0.2/12
month=0
while month<12:
new_bal=balance+(balance*annualInterestRate)-min_pay
balance=new_bal
month=month+1
if balance>0:
min_pay+=10
else:
break

Python loop with condition: using same code whether condition is met or not

I have a dict and a list:
main = {"one": "apple", "two":"pear", "three":"banana", "four":"cherry"}
conditional_list = ["one", "four"]
The conditional list may be empty or contain values (like in the case now). I would like to iterate over the dict "main". BUT: if the conditinal list is not empty, I would like to iterate only over the items that match the conditional list. So:
for key, val in mainlist:
if conditional_list:
if key in conditional_list:
do something
else:
do exactly the same thing
I it possible to set up the iteration in such a way, that I don't have to copy+paste the whole code of "do something" to "else" (the line where it says "do exactly the same thing")? Or to put it in another way: Is there a way to ignore the line "if key in conditional_list" if the condition is NOT met (i.e. the list is empty)?
The thing is, the code "do something" is huge and needs to be updated from time to time, copy+pasting it would make things extremly complicated. Thanks in advance!
What about this:
for key, val in mainlist:
if not conditional_list or key in conditional_list:
do something
My suggestion would be to pass the key to a doSomething() function
Also, you may have a reason, but it looks like the dictionary is being used backwards; given the context, this may be an apt solution for you:
for i in conditional_list:
doSomething(i,d(i),(i in mainlist))