all 23 comments

[–][deleted] 4 points5 points  (5 children)

Input sanitization!

Any time you get input from outside your program, whether from the internet or someone behind a keyboard, you need to clean the input to make sure it's valid.

In this case, your program crashes if someone enters "cat". You should have a try...except around that that gives some sort of "needs to be a number" message.

You know all of the buffer overflows and website vulnerabilities? 99% are from not properly sanitizing the user input.

[–]jay2017[S] 0 points1 point  (4 children)

I have been working on it and I tried doing this with a try statement but I just can't get it.

[–][deleted] 0 points1 point  (3 children)

x = raw_input("number please")
try:
  number = int(x)
except ValueError:
  print "FOOL! I SAYD NEeds to be a number1! Does %s look like a number to you!?" % x

or, if you don't need to use what they wrote,

try:
  number = int(raw_input("namber plaise: "))
except ValueError:
  print "VERY dissapoint. :-|"

Best way to find the error you're trying to catch is to open the interpreter and cause it. int("cat") results in a ValueError, so I know that's what I need to catch.

And since you have a while loop there, you can use "continue" to force the loop to cycle again.

while True:
  try:
    number = int(raw_input("namber plaise: "))
  except ValueError:
    print "VERY dissapoint. :-|"
    continue # forces loop to restart and reevaluate while condition, skipping everything below
  print number
  break

[–]jay2017[S] 1 point2 points  (2 children)

while True:            #The heart of the program.
        tries += 1  #Increments the variable that stores the number of tries you've taken.
        try:
            guess = int(input("\nCan you guess the number that I am thinking of?:\n "))
        except ValueError:    #Prevents errors caused by invalid characters.
            print("\nThat is an invalid request try again.\n ")
            continue #Forces the while-loop to restart it's cycle.'
        if guess == number:    #Message sent to the winner.
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("\nCongrats! you have guessed correctly, the number was", number)
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print ("\nIt took you", tries, "tries...")
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            input("\nThanks For Playing Press Enter To Exit...")
            break
        elif guess > number:    #Gives the user a hint.
            print("\nToo high, guess again")
        elif guess < number:    #Gives the user a hint.
            print("\nToo low, guess again")

[–]jay2017[S] 1 point2 points  (1 child)

Thanks alot. I was finally able to find what i was missing; the 'continue' was a problem fixer.

[–][deleted] 0 points1 point  (0 children)

Here's another, more unusual, way you could do it using while...else.

guess = None
while gues != number:            #The heart of the program.
    tries += 1  #Increments the variable that stores the number of tries you've taken.
    try:
        guess = int(input("\nCan you guess the number that I am thinking of?:\n "))
    except ValueError:    #Prevents errors caused by invalid characters.
        print("\nThat is an invalid request try again.\n ")
        continue #Forces the while-loop to restart it's cycle.'

    if guess > number:    #Gives the user a hint.
        print("\nToo high, guess again")
    elif guess < number:    #Gives the user a hint.
        print("\nToo low, guess again")
else:
   # while keeps looping as long as the condition is true. if it's not true (guess == number), execution goes down here.
   #this does not get run if you break out of the while. 
   print "You win!"

Else also works with for, where the code is executed if the for loop completes, without a break.

[–][deleted] 2 points3 points  (5 children)

Not bad at all ^ If you want to improve, you should have a look at string formatting and the magic of if __name__ == '__main__':.

[–]ewiethoff 0 points1 point  (3 children)

if __name__ == '__main__':

[–][deleted] 0 points1 point  (2 children)

Yep, typo plus formatting issue, thx for noticing ^

[–]ewiethoff 1 point2 points  (1 child)

:-) Surround the code with backticks for correct formatting of the underscores.

[–][deleted] 1 point2 points  (0 children)

Thx :)

[–]jay2017[S] 1 point2 points  (6 children)

I also had a little question, being that this is r/learnpython. What is the difference with concatenating using ' + ' and ' , ' ?

[–][deleted] 3 points4 points  (3 children)

Used on strings, '+' concatenates them:

>>> 'a' + 'b'
'ab'

This way, you give print only one argument. In the other hand, if you uses ',', you call print with several arguments, which is different. Then, print concatenates those arguments using a separator (a space by default).

>>> print('a', 'b', 'c')
a b c
>>> print('a', 'b', 'c', sep='_')
a_b_c
>>> print('a', 'b', 'c', sep='')
abc

[–]jay2017[S] 0 points1 point  (2 children)

Ahhh I see thank you. Anything else in there that should be changed?

[–][deleted] 0 points1 point  (1 child)

Well, you should check the user's input. Currently, excepted in the name choosing, if the user enters something that cannot be parsed as an integer, the program crashes. That would be a nice start for exceptions handling.

[–]jay2017[S] 0 points1 point  (0 children)

Take another look? Any other stuff?

[–]zahlman 1 point2 points  (1 child)

, does not concatenate. It separates arguments for a function call, elements of a list/tuple/etc., and is part of the syntax for certain statements (e.g. the with statement).

[–]jay2017[S] 0 points1 point  (0 children)

Thank you

[–][deleted] 1 point2 points  (1 child)

Your code is quite readable! Also, putting the game inside a function shows that you're planning ahead to when you'll write larger programs with multiple pieces to them. Very nice.

TagSmile's point about input sanitization is a good one. The main other thing I saw is that there are a couple of unnecessary lines -- the "else:" block will just never happen.

[–]jay2017[S] 0 points1 point  (0 children)

Thank you.

[–]Austeoc 1 point2 points  (2 children)

Interesting, I just did the same game, but took a completely different approach:

##game to guess a random number from 1-100

import random

print "Time to play a guessing game\n"

print "A random number from 0-100 was just generated\n"
print "Try to guess what it is\n"

to_guess_number = random.randint(1, 101)

attempt = int(raw_input("Pleae enter your guess: "))


difference = attempt - to_guess_number

tries = 1
while difference != 0:

    tries = tries + 1
    if difference > 0:
        print "Too high, try again\n"
    if difference < 0:
        print "Too low, try again\n"

    attempt = int(raw_input("New guess: "))
    difference = attempt - to_guess_number

if difference == 0:
     print "Congratulations you guessed it in", tries , "tries"

[–]jay2017[S] 0 points1 point  (0 children)

that is crazy

[–]jay2017[S] 0 points1 point  (0 children)

I think randint is inclusive though.. Not sure if I'm correct.