Example 5: Summing Non-Negative Numbers
Using continue to skip negative numbers and sum the non-negative ones.
numbers = [10, -5, 20, -10, 30]
total = 0
for num in numbers:
if num < 0:
continue # Skip negative numbers
total += num
print(f"Total sum of non-negative numbers is: {total}")
#clcoding.com
Total sum of non-negative numbers is: 60
Example 4: Finding the First Negative Number
Using break to find and print the first negative number in a list.
numbers = [10, 20, -5, 30, -10]
for num in numbers:
if num < 0:
print(f"First negative number is: {num}")
break
#clcoding.com
First negative number is: -5
Example 3: Skipping a Specific Number and Stopping at Another
Combining continue and break to skip the number 3 and stop at 7.
for i in range(1, 11):
if i == 3:
continue # Skip the number 3
if i == 7:
break # Stop the loop when i is 7
print(i)
#clcoding.com
1
2
4
5
6
Example 2: Stopping at a Specific Number
Using break to stop the loop when encountering the number 5.
for i in range(1, 11):
if i == 5:
break
print(i)
#clcoding.com
1
2
3
4
Example 1: Skipping Even Numbers
Using continue to skip even numbers in a loop.
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
#clcoding.com
1
3
5
7
9
0 Comments:
Post a Comment