But first, a quick digression on abbreviating expressions
like: a = a + 1. In Python and many other languages, it can
be abbreviated: a += 1. Note: there must be no space
between the + and the =. This abbreviation can be applied to the other 3 arithmetic operators as well: a += 15 → a = a + 15 a -= 8 → a = a - 8 a *= 3 → a = a * 3 a /= 12.5 → a = a / 12.5 |
But second, another digression on the function
range()... Remember slicing? The 1, 2, or 3 arguments given to range() work the same way...
|
Printing using while 1 2 3 |
i = 1 while i <= 3: print(i) i += 1 |
Print the values of a list: | L = [5,1,18] i = 0 while i < 3: print(L[i]) i += 1 |
A function designed to print the values of a list | def printlist(Q): i = 0 while i < len(Q): print(Q[i]) i += 1 |
Print a list backwards | def printtsil(Q): i = len(Q)-1 while i >= 0: print(Q[i]) i -= 1 |
Print the characters of a string | def printstring(S): i = 0 while i < len(S): print(S[i]) i += 1 |
Add up all the even numbers from 2 to 10 | answer = 0 n = 2 while n <= 10: answer += n n += 2 |
break: This command will
exit the body of a loop immediately, going on to the statements after the end of the loop. Adding up all the number from 1 onwards until the first number that is divisible by both 3 and 5 |
# Way 1: answer = 0 i = 1 while i < 15: answer += i i += 1 print(answer) # way 2, using break and # an "infinite loop" (usually dangerous) answer = 0 i = 1 while True: if i%3 == 0 and i%5 == 0: break answer += i i += 1 print(answer) |
Printing using for 1 2 3 |
for i in range(1,4): print(i) # range(start,end,skip): # begin iteration with start, # go up to but not including end, skip by skip |
Print the values of a list | Q = [2, 'hi', True] for i in range(len(Q)): print(Q[i]) |
A function to print the values of a list or string | def printSequence(list_or_string): for i in range(len(list_or_string)): print(list_or_string[i]) |
...but here's an easier way: | def printSequence(list_or_string): for fred in list_or_string: print(fred) |
...or backwards: | def printBack(l_or_s): for i in range(len(l_or_s)-1::-1): print(l_or_s[i]) |
... or backwards, an easier way: | def printBack(l_or_s): for fred in l_or_s[::-1]: print(fred) |
Print some elements in interesting positions... | for i in [2,5,-1,10]: print(Q[i]) |
Print every other character in a string or every other element in a list |
def printAlternates(l_or_s): for i in range(0,len(l_or_s),2): print(l_or_s[i]) def printAlternates(l_or_s): for fred in l_or_s[::2]: print(fred) |
add up the numbers from 1 to 15: | answer = 0 for i in range(1,16): answer += i |
add up the numbers from 1 to ?? but stop when the total gets just above 100 |
answer = 0 for i in range(1,100000): answer += i if answer > 100: break |