More about literation Flashcards
1
Q
For loop (extra)
A
# Function definition def sum_to(n): """ Return the sum of 1 + 2 + 3 ... + n """ sum = 0 for num in range(1, n + 1): sum = sum + num return sum
2
Q
While loop
A
while boolean expression:
statements # executed if condition evaluates to True
3
Q
While loop example
A
# Function definition def sum_to(n): """ Return the sum of 1 + 2 + 3 ... + n """ sum = 0 num = 1 while num <= n: sum = sum + num num = num + 1 return sum
4
Q
Choosing between for and while
A
–When you know the number of times to repeat, you can use a for loop
–On the other hand, when you are required to repeat until some condition is
met, you’ll need a while loop