Control Flow: The for Loops

for Loop Statement

The for loop will assign the next number in the given list to the variable _ and execute the statements in the loop body until the given list is exhausted. Try the next one as a practice:

number_sequence_list = [0, 2, 15, 34, 456, 73, 42]

for _ in number_sequence_list : 
    print("value of _ is ", _)

To sum a list of consecutive numbers in range(n) :

sum = 0

for i in range(5):    
    sum = sum + i

print(sum)

Yes, n(n+1)/2 is also applicable in the form (n-1)n/2 for this example, but that is not the discussion at the moment.

Similar example with user input is as follows:

n = int ( input("Enter a number please: ") )  

sum = 0

for i in range(n):    
    sum = sum + i
    
print(sum)

We can also define a function for doing the sum and call it whenever we need, fixing the sum to include the input number n :

def sum_function(number):

    total = 0

    for i in range(number): 
        total = total + i

    return total


n = int ( input("Enter a number please: ") )  

print(sum_function(n+1))