Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

while Loop Statements

loop

  • Please log in to reply
9 replies to this topic

#1 Root23

Root23

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 141 posts

Posted 27 January 2010 - 11:08 PM

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:
# 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.

count = 0
while (count < 10):
   count += 1

Is one way better, or preferred, over the other?
  • 0
Posted Image

#2 Bartimäus

Bartimäus

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 128 posts

Posted 27 January 2010 - 11:21 PM

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.
  • 0
[SIGPIC][/SIGPIC]

#3 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 27 January 2010 - 11:26 PM

Depends on what the loop was intended to do. If it's supposed to print the numbers out, just do this:
for i in range(10):
    print i,
print

Edited by ZekeDragon, 27 January 2010 - 11:38 PM.
Working too hard...

  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#4 Root23

Root23

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 141 posts

Posted 27 January 2010 - 11:31 PM

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.
  • 0
Posted Image

#5 Root23

Root23

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 141 posts

Posted 27 January 2010 - 11:33 PM

Depends on what the loop was intended to do. If it's supposed to print the numbers out, just do this:

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.
  • 0
Posted Image

#6 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 28 January 2010 - 05:42 PM

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.

i = 0
while True:
      print i, 

      if i = 10:
           break 

      i = i + 1

This code works also:

count = 0
while (count < 10):
   count += 1

however, I still like to use while true loops.
  • 0

#7 Root23

Root23

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 141 posts

Posted 07 February 2010 - 08:12 PM

I did end up using this method for the assignment:
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.

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.'
  • 0
Posted Image

#8 exicute

exicute

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 146 posts

Posted 07 February 2010 - 08:22 PM

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.
  • 0
Posted Image
My Tutorials|Build A Computer|Cat 5E|

#9 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 07 February 2010 - 11:07 PM

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.
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:
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.

Edited by ZekeDragon, 08 February 2010 - 12:52 AM.

  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#10 Root23

Root23

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 141 posts

Posted 10 February 2010 - 01:05 AM

(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:
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

  • 0
Posted Image





Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download