Closed Thread
Results 1 to 10 of 10

Thread: while Loop Statements

  1. #1
    Root23 is offline Programmer
    Join Date
    Jan 2010
    Posts
    144
    Rep Power
    8

    while Loop Statements

    What is the best way to accomplish a while Loop counter?

    Our teacher wants us to create a while loop that counts 1-10 with increments of 1, then one that goes 1-100 with increments of 10, and one that counts backwards from 1,000 that decreases by 100 each increment.

    I accomplished the counter this way:
    Code:
    # This counts from 1 to 10 with increments of 1.
    count = 0
    while True:
        count += 1
        if count > 10:
            break
        print count
    print "\n"
    Then I found this tutorial on the web that produces the same thing, but looks simpler.

    Code:
    count = 0
    while (count < 10):
       count += 1
    Is one way better, or preferred, over the other?

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Bartimäus's Avatar
    Bartimäus is offline Programming Expert
    Join Date
    Dec 2009
    Location
    Germany
    Posts
    490
    Rep Power
    11

    Re: while Loop Statements

    Code:
    count = 0
    while (count < 10):
       count += 1
    I think this code is better than the first one because they do the same and this code
    is much clearer and shorter than the other one.

  4. #3
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    Re: while Loop Statements

    Depends on what the loop was intended to do. If it's supposed to print the numbers out, just do this:
    Code:
    for i in range(10):
        print i,
    print
    Last edited by ZekeDragon; 01-27-2010 at 11:38 PM. Reason: Working too hard...
    Wow I changed my sig!

  5. #4
    Root23 is offline Programmer
    Join Date
    Jan 2010
    Posts
    144
    Rep Power
    8

    Re: while Loop Statements

    Quote Originally Posted by Bartimäus View Post
    I think this code is better than the first one because they do the same and this code
    is much clearer and shorter than the other one.
    That's what I was thinking. I took the first code from 'Guide to Programming with Python' by Michael Dawson, and adapted it to be a counter.

  6. #5
    Root23 is offline Programmer
    Join Date
    Jan 2010
    Posts
    144
    Rep Power
    8

    Re: while Loop Statements

    Quote Originally Posted by ZekeDragon View Post
    Depends on what the loop was intended to do. If it's supposed to print the numbers out, just do this:
    Code:
    for i in range(10):
        print i,
    print
    Yeah, that would def. work too, but for this assignment we have to use the while Loop. I think the for Loop is next in the book.

  7. #6
    Join Date
    Mar 2008
    Posts
    7,145
    Rep Power
    86

    Re: while Loop Statements

    Code:
    i = 0
    
    while i in range(10):
        print i,
        i = i + 1
    print
    I usually like to use while true loops and immediately test for break out conditions. This allows me to control exactly when I break out of the loop.

    Code:
    i = 0
    while True:
          print i, 
    
          if i = 10:
               break 
    
          i = i + 1
    This code works also:

    Code:
    count = 0
    while (count < 10):
       count += 1
    however, I still like to use while true loops.

  8. #7
    Root23 is offline Programmer
    Join Date
    Jan 2010
    Posts
    144
    Rep Power
    8

    Re: while Loop Statements

    I did end up using this method for the assignment:
    Code:
    count = 0
    while (count < 10):
       count += 1
    The teacher pointed out during the next class period that he wouldn't dock us point for using 'breaks,' but he did discourage it. Since then I've used a the while True method for a few small assignments.

    The last assignment we did was a small login script. This time I assigned a variable to be True, and then broke the loop by turning it false. After reading a small section from "A Byte of Python" I learned that each variable can be separated by commas, instead of each having to be on different lines.

    Code:
    userName, userPass, attempts, success = "john doe", "fopwpo", 0, True
    while success:
        login = raw_input("Username: ")
        password = raw_input("Password: ")
    
        if (login == userName and password == userPass) and attempts < 3:
            print "Login successful."
            success = False
        elif (login != userName or password != userPass) and attempts < 2:
            print "Invalid username or password. Try again."
            attempts += 1
        else:
            attempts == 3
            print "Login failed."
            success = False
    For those of you that are working in the field, what are your views on using a break to stop a loop? Our teacher said, more or less, that it's generally frowned upon to use a break, although it is 'legal.'

  9. #8
    exicute's Avatar
    exicute is offline Programming Expert
    Join Date
    Jan 2010
    Location
    Ohio
    Posts
    398
    Rep Power
    10

    Re: while Loop Statements

    I'm not totally sure on how python works, but here's a quote from C - How to program.
    Some programmers feel that break and continue violate the norms of structured programming. Because the effects of these statements can be achieved by structured programming techniques.
    And from the programming that I have done, I can say I agree with that.

    My Tutorials|Build A Computer|Cat 5E|

  10. #9
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    Re: while Loop Statements

    I think it's ridiculous to dislike how break/continue works. The reason structured programming was developed was to control the problem of spaghetti code, having flow of execution jump around unpredictably in a program. Control structures provide this predictable flow of execution, and break/continue statements are equally predictable and understandable for any decent programmer.

    Consider your while loop you have there, it's quite unusual.
    Code:
    userName, userPass, attempts, success = "john doe", "fopwpo", 0, True
    while success:
        login = raw_input("Username: ")
        password = raw_input("Password: ")
    
        if (login == userName and password == userPass) and attempts < 3:
            print "Login successful."
            success = False
        elif (login != userName or password != userPass) and attempts < 2:
            print "Invalid username or password. Try again."
            attempts += 1
        else:
            attempts == 3
            print "Login failed."
            success = False
    This control structure will first get two sets of user input, the user name and the password. The first if statement compares login with userName and password with userPass, which is what you want it to do. The problem is the next part, the elif statement, where it checks if login is not equal to userName or password is not equal to userPass. Considering that IF the first if statement check return false, then the second one MUST return true, so performing this check is pointless. Further, the continuous checking of whether attempts is greater than 2 or 3 is unnecessary and obfuscates the code, why is the first if statement a check for less than 3, and the second a check for less than 2? Is it obvious why? Do what's obvious. Finally, the statement "attempts == 3" doesn't even do anything. It'll return True or False, but since nothing checks whether it is True or False it doesn't do anything. This loop can be dramatically simplified, consider this following code:
    Code:
    userName, userPass, successful = "john doe", "fopwpo", False
    for attempts in xrange(3):
        if ((userName, userPass) == (raw_input("Username: "), 
                                     raw_input("Password: "))):
            print "Login successful."
            successful = True
            break
    
        print "Invalid username or password. Try again." if attempts != 2 else \
              "Login Failed."
    Well yes, I did shrink your loop considerably, consider how the break statement is being used. If I didn't have the break statement, I'd have to put the second print statement into an else statement and have a conditional check for whether or not successful is set to True, then perform math on the attempts similarly to how you did, which all takes more code. I've made the loop shorter, simpler to understand, and easier to maintain and write simply because I used a break statement, which is NOT confusing. That's my case for the break statement, without it in some loops the loop can become much more complicated when the operation should be very simple. What's more, this particular loop does better since after the loop you can check if attempts == True, and if it does, then login the user, else close the program or perform some other failure action.
    Last edited by ZekeDragon; 02-08-2010 at 12:52 AM.
    Wow I changed my sig!

  11. #10
    Root23 is offline Programmer
    Join Date
    Jan 2010
    Posts
    144
    Rep Power
    8

    Re: while Loop Statements

    (ZekeDragon)I personally agree with you on using break/continue statements.

    Per your comments I did remove "attempts == 3." I did also remove the less than 3 part of the code, but left the less than 2 in the elif statement. Until looking over the code after reading your comments I didn't realize that they were not needed for the code to work as intended.

    The end result is:
    Code:
    userName, userPass, attempts, success = "john doe", "fopwpo", 0, True
    while success:
        login = raw_input("Username: ")
        password = raw_input("Password: ")
    
        if login == userName and password == userPass:
            print "Login successful."
            success = False
        elif (login != userName or password != userPass) and attempts < 2:
            print "Invalid username or password. Try again."
            attempts += 1
        else:
            print "Login failed."
            success = False

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Help with my IF statements...
    By wolfman in forum General Programming
    Replies: 5
    Last Post: 09-27-2011, 06:27 AM
  2. loop:{ if(true) {goto:loop;}}//PHP 5.3
    By BlaineSch in forum PHP Development
    Replies: 22
    Last Post: 09-12-2009, 06:07 AM
  3. for statements
    By kumamako in forum C and C++
    Replies: 4
    Last Post: 08-02-2009, 10:27 AM
  4. c++ statements
    By kumamako in forum C and C++
    Replies: 5
    Last Post: 07-22-2009, 07:16 AM
  5. if statements help
    By pablo25 in forum Java Help
    Replies: 1
    Last Post: 12-13-2007, 09:49 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts