How to Loop Through a Range in Python


In this example we will show how to loop through a given range in Pyhton.

2. Parameters

The range function has 3 parameters:

Start: starting index. The default is from 0. For example, range(5) is equivalent to range(0, 5);
Stop: ending index. For example, range(0, 5) is [0, 1, 2, 3, 4] excluding 5;
Step: step size, The default is 1. For example: range(0, 5) is equivalent to range(0, 5, 1).

3. Codes

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

Min = int(input('Please input start index: '))
Max = int(input('Please input end index: '))

tmp = 0
for i in range(Min , Max+1):
    tmp += i
print('The sum of numbers between {} and {}: {}'.format(Min, Max, tmp))
Please input start index: 1
Please input end index: 100
The sum of numbers between 1 and 100: 5050
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments