for Loop in python

for Loop

The control statement for is used when we want to execute a sequence of statements (indented to the right of keyword for ) a fixed number of times. Suppose, we wish to find the sum of first few (say n) positive integer. Further, assume that the user provides the value of n. For this purpose, we need a counting mechanism to count from 1 to n and keep adding the current value of count to the old value of total (which is initially set to Zero). This is achieved using the control statement for.
total = 0
for count in range (1, n + 1):
total += count
n = int(input('Enter number of terms: '))
total = summation(n)
print('Sum of first', n, 'possitive integers: ', total)
On executing the script, Python prompts the user to enter the value of n and responds with the sum of first n positive integers:
Enter number of terms: 5
Sum of first 5 positive integers: 15

In the function summation (script sum,), the variable total is initialized to zero. Next, for loop is executed. The function call range(1,n + 1) produces a sequence of number from 1 to n. This sequence of numbers is used to keep count of the iterations. In general,
range(start, end, increment)
returns an object that produces a sequence of integers from start up to end(but not including end) in steps of increment. If the third argument is not specified, it is assumed to be 1. If the first argument is also not specified, it is assumed to be 0. Values of start, end, and increment should be of type integer. Any other type of value will result in error. Next, we give some examples of the use of range function:
range(1,11) 1,2,3,4,5,6,7,8,9,10
range(11) 0,1,2,3,4,5,6,7,8,9,10
range(1,11,2) 1,3,5,7,9
range(30,-4,-3) 30,27,24,21,18,15,12,9,6,3,0,-3
In the script sum, the variable count takes a value from the sequence 1, 2, ...., n, one by one, and the statement
total +=count
is executed for every value of count. On completion of the loop, the function summation returns the sum of first n positive number stored in the variable total. The value returned is displayed using print function.
Next, we develop a program to read and add the marks entered by the user in n subjects, and subsequently use the total marks so obtained to compute the overall percentage of marks. The number of subjects n is taken as the input from the user. The variable totalMarks is initialized to zero before the for loop.
n = int(input('Number of subjects: '))
totalMarks = 0
print('Enter marks')
for i in range(1, n + 1):
marks = float(input('Subject ' + str(i) + ': '))
assert marks >= 0 and marks <= 100
totalMarks += marks
percentage = totalMarks / n
print('Percentage is: ', percentage)

Number of subjects: 5
Enter marks
Subject 1: 75
Subject 2: 80
Subject 3: 75
Subject 4: 90
Subject 5: 95
Percentage is: 85.0

0 Response to "for Loop in python"

ads