views:

72

answers:

2
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?

A: 

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.

Marcelo Cantos
A: 

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.

Zack
I've never heard of a cgi module. Can you explain it a little more?
Josh
I linked to the documentation for it. Basically, it'll parse the HTTP POST data for you.
Zack
Can you tell me what the command is to validate code to make sure that it is a valid input. Should I use data.strip() for that as well?
Josh
Also, thank you for the first post that you made. I still haven't gotten it to work but I think I'm headed in the right direction.
Josh