Loops: “for” loop – “range” function

The range function and the for loop
visualizing
The range function:

###################################################################
# Mrs. Elia
# 10/25
# python 3.x
# Description: the range function
#
###################################################################

print ("This program demonstrates how to use the range function from python")

print ("range(10) creates a sequence or list of integers from 0 to 10-1 \n", list(range (10)))


This program demonstrates how to use the range function from python
range(10) creates a sequence or list of integers from 0 to (10-1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print ("These are both equivalent")
print("range(0,10): ", list(range (0,10)))
print( "and range(0,10,1): ", list(range(0,10,1)))

These are both equivalent
range(0,10): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
and range(0,10,1): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The for loop

a. numbers from 1 to 10 in increments of 1

###################################################################
# Mrs. Elia
# 10/25
# python 3.x
# Description: some uses of the for loop
#
#  The for loop
#
###################################################################

for counter in range (1,11):
    print ("value containded in counter is ",counter)   # counter --> 1 2 3 4 ... 10
    

value containded in counter is 1
value containded in counter is 2
value containded in counter is 3
value containded in counter is 4
value containded in counter is 5
value containded in counter is 6
value containded in counter is 7
value containded in counter is 8
value containded in counter is 9
value containded in counter is 10

b. from 10 to 2 in increments of -1 (decrement of 1)

for counter in range (10,1, -1):
    print (counter) # counter takes on the value of each item on the list

c. from 7 to 77 in steps of 7

for counter in range (7,78,7):
    print (counter)  # counter takes on the value of each item on the list

d. Summation

suma = 0
for number in range (1,11):
    suma += number
print ("The sum of all integers from 1 to 10 is ", suma)

The sum of all integers from 1 to 10 is 55

e. Summation

suma = 0
for number in range (2,101,2):
    suma += number
print ("The sum of all even integers from 2 to 100 is ", suma)

The sum of all even integers from 2 to 100 is 2550

Python Data Structures

Assignment: Write a program, factorial_YI.py. Use the “for” loop to calculate the factorial of a given number. Prompt the user for a number. (Look for the post)