Chapters 5&6: Iteration and Strings Flashcards
Increment/decrement
Updating the value of a variable bu increasing/drecreasing by 1 (or another fixed amount?) eg x=x+1
while
statement saying “if this condition is met (ie True), execute the body. If False, skip rest of body and execute subsequent lines. Method of looping.
n=10 while n>0: print(n) n=n-1 print('Blastoff!') #number ofiterations?
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Blastoff!
10 interations
iteration variable
variable which is changed each iteration and controls when the loop finishes, n above. If there isnt one, it’s an infinite loop.
while True
A way of making a controlled infinite loop, which will repeat (if user input is part of it, ie. x=input(‘type Hi\n’)) until broken eg by user entering sought-for value, ie if x==’Hi’//[tab]break.
while True: line=input('> ') if line[0]=='#' continue if line=='done' break print(line) print('Done!')
line[0] means first character of value of line; hence if it starts with #, start loop again without finishing.
if it’s ‘done’, loop breaks and final line occurs. Else, loops back.
Definite loop
A loop which goes through a set of values, and ends with the last value. Often with ‘for’ statement, rather than ‘while’ for an indefinite loop.
friends=[‘Joseph’, ‘Glenn’, ‘Sally’]
for friend in friends:
print(‘Happy New Year: ‘, friend)
print(‘Done!’)
the ‘for’ makes it cycle through 3 times, on per friend in set ‘friends’, before executing final line. Friend is iteration variable.
itervar
iteration variable, eg: total=0 for itervar in [3, 41, 12, 9, 74, 15]: total=total+itervar print('Total: ', total) #this would summate the numbers in set. (can just use sum() though)
fruit=’banana’
letter=fruit[1]
print(letter)
Returns ‘a’. first letter is [0], b, etc. Must be integer
len()
length of string, number of characters in a string (not other types)
length=len(fruit)
last=fruit[length]
error - out of range! [6] would be 7th letter, only 6. hence last=fruit[length-1] to get last letter, a. OR, count back, letter=fruit[-1] returns a, [-2] b etc.
spell out “fruit” letter by letter with “while” statement - traversing through a string
index=0
while index
spell out “fruit” letter by letter with “for” statement - traversing through a string
for char in fruit:
print(char)
String slices
assigning segments of a string for something, eg. s=’Ben Nouhan’, print(s[0:5]) returns Ben NB, it inludes first (0) but excludes last (5). [:5] is start to 5, [3:] is 3 to last. [:] is whole thing.