CMPSC 100 Computational Expression
Repeating actions
Without a loop:
With a loop:
range()
Functionrange()
creates a sequence of numbersExamples:
Structure:
Example:
Output:
Count is: 0
Count is: 1
Count is: 2
Example:
Output:
Day 1 of training
Day 2 of training
Day 3 of training
Example:
Output:
Adding 1, total is now 1
Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final total: 15
Example:
Output:
Letter: C
Letter: M
Letter: P
Letter: S
Letter: C
range()
with the length of the stringstring[index]
Example:
Output:
Position 0: P
Position 1: Y
Position 2: T
Position 3: H
Position 4: O
Position 5: N
Structure:
Example:
Output:
Count is: 1
Count is: 2
Count is: 3
Loop finished!
For loop - when you know how many times:
While loop - when you have a condition:
Both print “Hello!” 5 times, but use different approaches!
Structure:
Example:
Output:
Position (1, 1)
Position (1, 2)
Position (1, 3)
Position (2, 1)
Position (2, 2)
Position (2, 3)
Example:
Output:
*
**
***
****