Nested structures question

DevPlayer devplayer at gmail.com
Thu Jan 13 01:57:33 EST 2011


looping = True
while looping:
    guess = int(raw_input("Take a guess: "))
    tries += 1
    if guess > the_number:
        print "Lower..."
    elif guess < the_number:
        print "Higher..."
    else:
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"
        break

    if  tries >= 7:
        print "Wow you suck! It should only take at most 7 tries!"
        looping = False


# Alternatively while learing while looping use the continue statement

looping = True
while looping:
    guess = int(raw_input("Take a guess: "))
    tries += 1

    if guess > the_number:
        print "Lower..."
    elif guess < the_number:
        print "Higher..."
    else:
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"
        break

    if  tries < 7:
        continue

    print "Wow you suck! It should only take at most 7 tries!"
    looping = False




# In a while loop I recommend to NOT end loops using the
# conditional test of == but instead use >, <, >= or <= or !=.
# In a complex while loop the exit condition may be skipped
# by mistake and you'll loop forever.

# In while loops I get less bugs by putting the incrementor as
# the last statement in the while block;
# this helps follow precedence like range(7) is - zero to 6
# as well as index 0 in a list is the first item. However
# while index: where index == 0 will exit the loop before
# it even starts as 0 == False (0 is not False but equals False)

# Use the while loop for looping an undetermined number of
# iterations or conditional iterations.
# Use for loops for an explicid number of iterations.

for tries in range(7):
    guess = int(raw_input("Take a guess: "))
    if guess > the_number:
        print "Lower..."
    elif guess < the_number:
        print "Higher..."
    else:
        print "You guessed it! The number was", the_number
        print "And it only took you", tries, "tries!\n"
        break
    if  tries >= 7:
        print "Wow you suck! It should only take at most 7 tries!"

# I'm guessing the chapter's test is to see if you remember the for
loop.

# start using print() to get into a good habit for Python 3.0+


# I haven't seen the book but often one part of while that is
# left off in tutorials is the "else" statement.
while condition:
    "block"
else:
    "block"

# you can use else for when the condition never happens.



More information about the Python-list mailing list