[Tutor] Beginners question

Christian Witts cwitts at compuscan.co.za
Thu Oct 8 15:40:16 CEST 2009


gary littwin wrote:
>
> Hi all -
>
> Just started on "Python Programming for Absolute Beginners" and I've 
> got a question:
>
> The program called 'Guess my Number' goes like this:
> # 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 too high, too low
> # or right on the money
>
> #import random
>
> print "\tWelcome to 'Guess My Number'!"
> print "\nI'm thinking of a number between 1 and 15."
> print "Try to guess it in as few attempts as possible.\n"
>
> import random
>
>
> # set the initial values
> the_number = random.randrange(15) + 1
> guess = int(raw_input("Take a guess: "))
> tries = 1
>
> # guessing loop
> while (guess != the_number):
>    if (guess > the_number):
>        print "Lower..."
>    else:
>        print "Higher..."
>
> guess = int(raw_input("Take a guess: "))
> tries += 1
>
> print "You guessed it! The number was", the_number
> print "And it only took you", tries, "tries!\n"
>
> raw_input("\n\nPress the enter key to exit.")
>
> So here's the question - the original code has parentheses around the 
> lines of code with *(guess !=the_number)* and *(guess* *> the_number)* 
> .  I tried to run the program without the parentheses and it runs just 
> fine.  So what are the parentheses for??
>
> Thanks a lot for your time - 
>
>              Gary
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>   
Some use the parentheses for code clarity as it reads easier when it's 
grouped by ().
Your code as written won't run as it should, your while loop needs to 
change to include your `guess = int(raw_input("Take a guess: "))` as 
without it if your first guess is incorrect it would just loop 
infinitely (it's currently 1 level of indentation out, as well as your 
`tries += 1`).

Welcome to Python and hope you enjoy your stay. :)

-- 
Kind Regards,
Christian Witts




More information about the Tutor mailing list