[Tutor] while loops
Prasad, Ramit
ramit.prasad at jpmorgan.com
Wed Dec 14 23:48:11 CET 2011
-----Original Message-----
From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of rog capp
Sent: Wednesday, December 14, 2011 4:41 PM
To: tutor at python.org
Subject: [Tutor] while loops
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is to high, to low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("I'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1,100)
guess = int(input("Take a guess: "))
tries = 1
# Guessing loop
while guess != the_number:
if guess > the_number:
print("Lowere...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("good job")
input("\n\nPress the enter key to exit.")
This is a program from "Python for the absulute beginner(which I am).
End of the chapter is a challenge that asks me to limit the number of
guesses the player gets.
If he/she fails to guess the number after a certain number of attempts
then it displays a message
about his failure.It needs to be a while loop cause it the topic I'm
at.Can anyone give me some help
on where to put the loop.When i put it in with the "if
guess>the_number" loop, the program either
prints higher or lower continuously(continuous loop I imagine) or it
gives me the answer whether its
right or wrong after a couple guesses.Any help will be appreciated.
=============================================================
If you want to stop after a certain number of attempts, then your
loop should compare the number of tries (you are storing this correctly)
against the number of max allowed attempts (you are not
storing this part so that needs to be done first). You can use the
current loop, just change the conditions (this part is
second)d. Hopefully that makes sense to you.
Ramit
Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list