How to Create a Loop to Add in Python?

Estimated read time 2 min read

To create a loop to add in Python, you can use a for loop or a while loop to iterate over a range of numbers or until a condition is met. Here are a few examples of how to create loops to add in Python:

Example 1: Using a for loop to add the numbers from 1 to 10

total = 0
for i in range(1, 11):
    total += i
print(total)

In this example, we define a variable total to keep track of the sum of the numbers. We then use a for loop with the range() function to loop over the numbers from 1 to 10, and add each number to the total variable using the += operator. Finally, we print the total.

Example 2: Using a while loop to add numbers until the total is greater than 100

total = 0
i = 1
while total < 100:
    total += i
    i += 1
print(total)

In this example, we define a variable total to keep track of the sum of the numbers, and a variable i to keep track of the current number. We then use a while loop to add each number to the total variable until the total is greater than 100. Finally, we print the total.

You can modify these examples to add different ranges of numbers or to use different conditions to stop the loop.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply