break the loop in one object and then return

Juho Schultz juho.schultz at pp.inet.fi
Mon Jun 26 15:52:25 EDT 2006


Alex Pavluck wrote:
> I am trying to write the following code to block up evaluation and
> prompting for entering new information.  However, when I break the loop
> in one object and then return it does not start at the beginning again
> but rather at the point where it exited.  Can someone look at the
> following code and give me some feedback.
>
If you want a loop, write a loop.

eval() is a built-in function. Better leave the names of builtins as
they are.

>
> yournum = input("I am thinking of a number between 1 and 100.\n  Guess
> which number: ")
> mynum = (yournum-5)
>
If the users first guess is 2, mynum becomes -3...

Better use this - to ensure 100 >= mynum >= 1, and the user can guess
right on 1st try.
import random
mynum = random.randint(1,100)

input evaluates a user-supplied string, and is a bit dangerous.
(Run your original program, and give "mynum" as your second guess.)
So use yournum = int(raw_input("I am thinking...

you could use one while loop instead of two functions and one global
variable.

while (yournum != mynum):
    if yournum < mynum:
        print "Too low."
    else:
        print "Too high."
    yournum = int(raw_input("Guess again:"))
print "You got it!"




More information about the Python-list mailing list