Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop in Python
#1

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!
Reply
#2
https://wiki.python.org/moin/ForLoop
Reply
#3
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)
Reply
#4
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.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020