943,864 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 2911
  • Python RSS
You are currently viewing page 1 of this multi-page discussion thread
Nov 2nd, 2006
0

Loops in Python

Expand Post »
When do you use a for loop and when to use a while loop. Are there other loop types in Python? Some of the slicing examples almost look like loops.
Similar Threads
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Nov 2nd, 2006
0

Re: Loops in Python

for loops are specifically helpful for going through a string or list or tuple... the for loop executes using whatever variable you say as the current item (does that make sense?)

[php]
nums = [1,2,3,4]
for number in nums:
print item,
[/php]

Here, for each iteration the "item" variable changes...to 1, then 2, then 3, and finally 4.

If you did this with a while statement, it might look like this:

[php]
nums = [1,2,3,4]
i = 0
while i < len(nums):
print nums[i],
i = i + 1
[/php]

Now, not only does this code (using while) longer, it's more abstract. Someone who may not understand what exactly it's doing has to walk through each iteration and understand what's happening. With the for loop, it's so much more like english that you can possibly understand it just reading it.
Featured Poster
Reputation Points: 83
Solved Threads: 39
Posting Whiz in Training
LaMouche is offline Offline
263 posts
since Oct 2006
Nov 2nd, 2006
0

Re: Loops in Python

For and While loops serve different functions, you can actually make a For loop using a while loop (though I don't reccomend it.)

Here's a useful function for text-based games:

[php]
def ask_yes_no_question(question):
"""Asks a yes or no question for the user"""
response = "None"
while response not in "yn":
response = raw_input(question).lower()
return response
ask_yes_no_question("Would you like to play again?(y/n): ")

[/php]

An example of the for loop, this one removes all vowels from your word or phrase.

[php]
word = raw_input("Please enter a word or phrase")
for letter in word:
if letter not in "aeiouAEIOU":
print letter
[/php]
Reputation Points: 10
Solved Threads: 3
Newbie Poster
Zonr_0 is offline Offline
16 posts
since Oct 2006
Nov 2nd, 2006
0

Re: Loops in Python

The "for loop" loops (iterates) through the items of a sequence (string, list, tuple, dictionary, set ...). The "while loop" loops until a condition is met. Though the two loops are different beasts, they can overlap in functionallity. You can break out of either loop on a conditional statement.

If you want to loop a fixed number of times, it is easier to use a "for loop" ...
Python Syntax (Toggle Plain Text)
  1. for k in range(100):
  2. print "I should not cuss!"
Yes, there are other loops in Python. For instance a recursive function (a function that calls itself) is a loop for special purposes ...
Python Syntax (Toggle Plain Text)
  1. # a recursive function to print n newlines
  2. def new_lines(n):
  3. if n > 0:
  4. print
  5. new_lines(n-1)
  6.  
  7. print "-----"
  8. new_lines(20)
  9. print "-----"
This is of course a silly application for a recursive function, just a demo. Below is a more common application of a recursive function ...
python Syntax (Toggle Plain Text)
  1. def gcd2(x, y):
  2. """greatest common denominator, recursive"""
  3. if x > y:
  4. return gcd2(x-y, y)
  5. if x < y:
  6. return gcd2(x, y - x)
  7. if x == y:
  8. return x
  9.  
  10. x = 14
  11. y = 63
  12. print gcd2(x, y) # 7
Interestingly the above recursive function can be replaced with a function containing a while loop and is much faster ...
python Syntax (Toggle Plain Text)
  1. def gcd3(x, y):
  2. """greatest common denominator, non-recursive"""
  3. while y:
  4. x, y = y, x % y
  5. return x
  6.  
  7. x = 14
  8. y = 63
  9. print gcd3(x, y) # 7
I am digressing as usual!
Last edited by vegaseat; Nov 2nd, 2006 at 10:41 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 3rd, 2006
0

Re: Loops in Python

I think I am getting a feeling in which case to use 'for' or 'while'. Never looked at a recursive fuction as a loop, but I guess it is and can be used for that purpose. Almost looks like a limited goto!

With the loops there is also continue, break and else. Why and how are they used in a loop?
Last edited by sneekula; Nov 3rd, 2006 at 2:19 pm.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Nov 4th, 2006
0

Re: Loops in Python

Here is an example of continue and else ...
python Syntax (Toggle Plain Text)
  1. for k in range(10):
  2. # skip values > 3 or < 6
  3. if 3 < k < 6:
  4. continue
  5. print k, # 0 1 2 3 6 7 8 9
  6. else:
  7. # works only if there is no break statement in the loop
  8. print
  9. print "final k =", k # final k = 9
Last edited by vegaseat; Nov 4th, 2006 at 1:17 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 4th, 2006
0

Re: Loops in Python

Click to Expand / Collapse  Quote originally posted by sneekula ...
I think I am getting a feeling in which case to use 'for' or 'while'. Never looked at a recursive fuction as a loop, but I guess it is and can be used for that purpose. Almost looks like a limited goto!

With the loops there is also continue, break and else. Why and how are they used in a loop?
It's mathematically provable that any recursive function can also be accomplished with a for loop, and vice-versa.

continue is used when you need to go back to the top of the loop. That typically happens when you've processed enough to know that it's time to start over.

break is used when it's time to exit from the loop. That should happen when you've met an exit conditions. One of my favorite idioms:

[php]
while True: <---
answer = raw_input("What's your answer? ")
if is_correct(answer):
print "You got it!"
--> break
else:
print "Try again!"
[/php]
This is used in cases where you are certain that you want the block inside the loop to execute at least once.

else with loops is mostly silly, AFAIK. Any code after the while or for block is called "fallthrough" and is effectively equivalent to an "else."

[php]
>>> def test(a):
for i in range(a):
print i,
else: <--- else
print "Empty list!"


>>> test(5)
0 1 2 3 4 Empty list!
>>> test(0)
Empty list!
>>>
>>> def test2(a):
for i in range(a):
print i,
print "Empty list!" <--- fallthrough


>>> test2(5)
0 1 2 3 4 Empty list!
>>> test2(0)
Empty list!
>>>
[/php]

Perhaps you might want to include an else just for clarity for human readers, but human readers are used to the idea of "fallthrough."

Jeff
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Nov 6th, 2006
0

Re: Loops in Python

So, if the fallthrough is due to a 'break' statement, the 'else' associated with a 'while' or 'for' will not kick in? Might be useful sometimes.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Nov 6th, 2006
0

Re: Loops in Python

Click to Expand / Collapse  Quote originally posted by sneekula ...
So, if the fallthrough is due to a 'break' statement, the 'else' associated with a 'while' or 'for' will not kick in? Might be useful sometimes.
Hey ... you're right about that. Sample code:

[php]
>>> def test3(a):
for i in range(a):
print i,
if (i+1) % 17 == 0:
break
else: print "else reached!"
print "Empty list"


>>> test3(5)
0 1 2 3 4 else reached!
Empty list
>>> test3(21)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Empty list
>>>
[/php]

Apparently, else protects fallthrough code from break.

Hmm...now for a good way to use that behavior...

Thanks,
Jeff
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Nov 9th, 2006
0

Re: Loops in Python

Found a use in class today!

Tic-tac-toe game. Problem: we need to loop until the board is full *or* until there's a winner. If the board is full, there might be a winner (if the last move is a winning move), or there might be a tie. Solution: use an else on the loop.

[php]
board = [' ']*9 # board contains ' ', 'X', and 'O's

while ' ' in board:
print_board()
player_turn()
if is_winner('X'):
print "You won!"
break

computer_turn()
if is_winner('O'):
print "You lost!"
break

else:
print "A tie!"

print "\nFinal board:\n"
print_board()
[/php]
This works because the break will skip over the else; hence, fallthrough to the else is guaranteed to be a tie.



Jeff
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Guess a word
Next Thread in Python Forum Timeline: Event handling across panels issues...





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC