python number guessing question
import sys
print 'Content-Type: text/html'
print ''
print '<pre>'
# Read the form input which is a single line
guess = -1
data = sys.stdin.read()
# print data
if data == []:
print "Welcome to Josh's number game"
try:
guess = int(data[data.find('=')+1:])
except:
开发者_运维技巧 guess = -1
print 'Your guess is', guess
answer = 42
if guess < answer :
print 'Your guess is too low'
if guess == answer:
print 'Congratulations!'
if guess > answer :
print 'Your guess is too high'
print '</pre>'
print '''<form method="post" action="/">
Enter Guess: <input type="text" name="guess"><br>
<input type="submit">
</form>'''
Right now the program tells you if your guess is too low, too high or right on. I want to add two more messages, one for when someone does not enter any input in the field. And another one for someone who enters invalid input (like a string or something) instead of a number. My field data == [] is meant to show no input in the field, but it doesn't work as I thought. Can you help?
sys.stdin.read()
will give you an empty string if there's no input, so data == []
should be
data == ''
.
The message for invalid input is probably best put inside the except:
clause that you already have (you'll need to rearrange your control flow a bit so that becomes exclusive with the number-checking part).
Also, you may find the cgi
module useful for what it looks like you're doing.
data
is a string and will never equal []
, which is a list. Try data.strip() == ""
.
EDIT: It just occurred to me that you probably meant to use sys.stdin.readlines()
, which does return a list. But instead of "fixing" this, I strongly recommend you follow @Zack's advice regarding CGI.
精彩评论