-
Integers, Floats and Strings 3
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
-
If Statements 3
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
-
Lists, Sets and Tuples 5
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
Lecture3.5
-
-
Loops 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Functions 3
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
-
Dictionaries 3
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
-
Assertions 2
-
Lecture7.1
-
Lecture7.2
-
-
Classes 3
-
Lecture8.1
-
Lecture8.2
-
Lecture8.3
-
-
Matplotlib 2
-
Lecture9.1
-
Lecture9.2
-
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)
15
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)))
Count of 1: 3
Count of 2: 2
Count of 3: 2
Count of 4: 1
Count of 5: 2
Count of 7: 1
Count of 8: 5
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))
0
2
4
6
8
The total is: 20
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
0
1
2
3
4
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)
16