While Loop
Examples¶
We could get the sum of a list by iterating over it with a for loop easily.
#Example: Summing values of a list
total = 0
l = [1,2,3,4,5]
for x in l:
total+=x
print(total)
By combining a set and a for loop, we could list out the unique values and their counts.
#Example: Finding the count of each unique number in a list
l = [1,1,1,2,2,3,4,3,5,7,8,5,8,8,8,8]
unique = set(l)
for x in unique:
print("Count of "+str(x)+": "+str(l.count(x)))
By combining an if statement and a for loop over a range, we can get the sum of even numbers in a range.
#Example: Getting the sum of even numbers
total = 0
for x in range(10):
if x%2==1:
continue
print(x)
total+=x
print("The total is: "+str(total))
While Loop¶
A while loop is one which runs until a condition is false or break is called within it. The format of it is:
while condition:
execute code
These are very helpful when you have a loop that will need to run for a variable amount of time (based on some conditions). It is dangerous sometimes because it could go on forever if you the conditon never changes to false. Below, we start with i=0, and print i and add 1 to it during each loop. Once i is no longer less than 5 it will stop. You can imagine, if you were to forget to put the part where you add 1 to i, it would never terminate because i would always be equal to 0! So be careful!
#A while loop does something until the condition is not true
#So the below code will keep printing i until it is not less than 5
#Be careful, this could run forever if there isn't a way for the condition to one day not be false
i = 0
while i<5:
print(i)
i+=1
Example¶
If you need the next integer that is divisible by 8, you could use a while loop checking that the number divided by 8 has no remainder and adding 1 each time.
#Example: Keep adding one until the value of i is divisible by 8
i = 9
while i%8 != 0:
i+=1
print(i)