Unit 5 - Loops
i = initialValue # Initialize loop-control variable {{nl}}
while i < endValue: {{nl}}
# Loop body {{nl}}
... {{nl}}
i += 1 # Adjust loop-control variable {{nl}}
A for loop can be used to simplify the preceding loop: {{nl}}
for i in range(initialValue, endValue): {{nl}}
# Loop body {{nl}}
In general, the syntax of a for loop is: {{nl}}
for var in sequence: {{nl}}
# Loop body {{nl}}
|
With user Confirmation
continueLoop == 'Y':
while continueLoop == 'Y' : # Execute the loop body once ... # Prompt the user for confirmation continueLoop = input("Enter Y to continue and N to quit: ") |
|
Sentinel Value
Another common technique for controlling a loop is to designate a special input value, known as a sentinel value, which signifies the end of the input. A loop that uses a sentinel value in this way is called a sentinel-controlled loop.
data = eval(input("Enter an integer (the input ends " + "if it is 0): ")) # Keep reading data until the input is 0 sum = 0 sum += data data = eval(input("Enter an integer (the input ends " + "if it is 0): ")) print("The sum is", sum) |
print(" Multiplication Table")
# Display the number title
print(" |", end = ‘’)
print(" ", j, end = '')
print() # Jump to the new line
print("——————————————————————————————————————————")
# Display table body
print(i, "|", end = ‘’)
# Display the product and align properly
print(format(i * j, "4d"), end = '')
print() # Jump to the new line
1 sum = 0
2 number = 0
3
4 while number < 20:
5 number += 1
6 sum += number
7 if sum >= 100:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
1 sum = 0
2 number = 0
3
4 while number < 20:
5 number += 1
6 if number == 10 or number == 11:
7 continue
8 sum += number
9
10 print("The sum is", sum)
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.