Horribly noobful string question
Fredrik Lundh
fredrik at pythonware.com
Tue Dec 13 12:28:51 EST 2005
"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!"
...
isdigit returns true if the string contains nothing but digits:
>>> help(str.isdigit)
isdigit(...)
S.isdigit() -> bool
Return True if there are only digit characters in S,
False otherwise.
if you're using some other way to read user input, let us know.
</F>
More information about the Python-list
mailing list