Loops in Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Oct 2006
Posts: 2,284
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 177
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Loops in Python

 
0
  #1
Nov 2nd, 2006
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.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 128
Reputation: LaMouche is on a distinguished road 
Solved Threads: 19
LaMouche's Avatar
LaMouche LaMouche is offline Offline
Junior Poster

Re: Loops in Python

 
0
  #2
Nov 2nd, 2006
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.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 16
Reputation: Zonr_0 is an unknown quantity at this point 
Solved Threads: 3
Zonr_0 Zonr_0 is offline Offline
Newbie Poster

Re: Loops in Python

 
0
  #3
Nov 2nd, 2006
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]
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,070
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Loops in Python

 
0
  #4
Nov 2nd, 2006
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" ...
  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 ...
  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 ...
  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 ...
  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.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,284
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 177
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Loops in Python

 
0
  #5
Nov 3rd, 2006
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.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,070
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 938
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Loops in Python

 
0
  #6
Nov 4th, 2006
Here is an example of continue and else ...
  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.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Loops in Python

 
0
  #7
Nov 4th, 2006
Originally Posted by sneekula View Post
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
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,284
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 177
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Loops in Python

 
0
  #8
Nov 6th, 2006
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.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Loops in Python

 
0
  #9
Nov 6th, 2006
Originally Posted by sneekula View Post
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
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Loops in Python

 
0
  #10
Nov 9th, 2006
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
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC