[Tutor] While Loop Help
James Chapman
james at uplinkzero.com
Thu Dec 11 12:18:09 CET 2014
While Alan has given you a far better solution, I feel someone should
mention the break statement as you will likely come across it a lot, and it
is quite an important flow control statement.
You could add a break statement to the else which would break out of the
while loop.
https://docs.python.org/3.4/reference/simple_stmts.html#break
Refactored to include a break
--------------------------------------------------
...
the_number = random.randint(1, 100)
win = false
tries = 0
guess = int(input("Take a guess: "))
while tries < 10:
guess = int(input("Take a guess: "))
tries += 1
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
win = true
break
if win:
print("You win")
else:
print("You fail! The number was {0}".format(the_number))
input("\n\nPress the enter key to exit.")
--------------------------------------------------
More information about the Tutor
mailing list