Horribly noobful string question

Xavier Morel xavier.morel at masklinn.net
Tue Dec 13 13:06:16 EST 2005


Fredrik Lundh wrote:
> "SeNTry" wrote:
> 
>> My first post here as I just begin to learn programming in general and
>> python in particular.  I have all the noobie confused questions, but as I
>> work thru the tutorials I'm sure I'll find most my answers.
>>
>> This one is eluding me tho... I am working in the tutorials, writing scripts
>> as presented and then modifying and expanding on my own to try to learn.
>> I'm working with one that asks the user to 'guess a number I'm thinking',
>> and with simple while loop, flow control and operands, returning an answer
>> to guess again or you got it.  I've added a 'playagain' function I've got
>> working, but what I want is to stop the program from crashing when someone
>> enters a string value instead of a int value.  I know strings are immutable,
>> and they can be changed to an int equivalent, but I just want the script to
>> recognize the input as a string and print a simple "that's not a number, try
>> again' type of message.  I can't find the syntax to include in the
>> if/elif/else block to include a line that says something like,
> 
> assuming you're using raw_input() to get the guess, you always
> have a string (in python's sense of that word).
> 
> what you seem to want is to check if the string contains a number
> or not.  here's one way to do this:
> 
>     guess = raw_input("make a guess: ")
>     if guess == secret:
>         print "congratulations!"
>     elif not guess.isdigit():
>         print "that's not a number! please guess again!"
>     ...
> 

that, or just write something like

guess = raw_input("Make your guess > ")
try:
	if int(guess) == secret:
		# ok
except ValueError:
	# no good



More information about the Python-list mailing list