Python Forum

Full Version: For loop in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

Hi there,

I am new here, so I don't know if I can post these questions over here.
I am currently working on a course for learning python and I have a question about for loops. It is a basic question, but the exercise is: You already created code with a while loop that asked the user for five numbers, and displayed their total. Create code for this task, but now use a for loop.

This is my code form the previous exercise:

from pcinput import getInteger

total = 0
count = 0
while count < 5:
    total += getInteger( "Please give a number: " )
    count += 1

print( "Total is", total )
print( "Average is", (total/count))
Can someone help me with the for loop exercise, while I don't fully understand the for loops I guess.
Thank you in advance!
A for loop is very similar to a while loop... it executes the block repeatedly until the iterator is exhausted. While loops just force you to manage the iterator manually.

total = 0
for count in range(5):
    total += getInteger("feed me! ")

print(total)
For loops in Python are a bit different to those used in many other programming languages. Some argue it should have been called foreach instead.

One of the best explanations I've seen of the power and options, building from the basics, of for loop is a video featuring Ned Batchelder.