Reputation: 2791
It keep showing this error
Traceback (most recent call last):
File "/home/zca22/public_html/Lab_Assn_5/Scripts/dice.py", line 7, in <module>
playerGuess = int(formData["guess"].value)
File "/usr/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'guess'
I don't know what's wrong iin my code.
import cgi
import random
formData = cgi.FieldStorage()
playerName = formData["name"].value
playerGuess = int(formData["guess"].value)
theLength = 5
sum = 0
print "Content-type: text/html"
print "<p>Thanks for playing, " + playerName + ",</p>"
for die in range(theLength):
val = random.randint(1,6)
print '<img src = "Images/dice-%i.gif" alt="%i" width="107" height="107" />' % (val, val)
sum = sum + val
print "<p>You bet the total would be at least " + playerGuess + ". The total rolled was " + sum + ".</p>"
if playerGuess >= sum:
print "<p>You won!</p>"
else:
print """<p>Sorry, you lose!</p>
</body>
</html>"""
Upvotes: 0
Views: 586
Reputation: 10129
In the Python dict
dictionary data type, each entry has a key and a value. Your code formData["guess"]
tries to access the dictionary formData
under the key "guess"
to retrieve the underlying value.
Since you're getting a KeyError
, your dictionary has no key called "guess"
. Since the dictionary is populated by your cgi.FieldStorage()
call, this can be interpreted as saying that your cgi form object has no field with the name "guess".
Upvotes: 0
Reputation: 129109
It looks like you're not POST
ing it a guess
value. You should have something like this in the page before:
<form action="/cgi-bin/guess.py" method="post">
<dl>
<dt><label for="name_field">Name:</label></dt>
<dd><input type="text" id="name_field" name="name" required="required" /></dd>
<dt><label for="guess_field">Guess:</label></dt>
<dd><input type="number" id="guess_field" name="guess" min="1" max="6" step="1" required="required" /></dd>
</dl>
<p><input type="submit" value="Guess" /></p>
</form>
Upvotes: 1
Reputation: 288200
There is no "guess"
entry in the formData
, the dictionary of user inputs. Are you sure you have a field like <input name="guess" value="3" />
in the exact form you're submitting?
Upvotes: 0
Reputation: 20664
It means that the form doesn't have a "guess" entry, but it does have a "name" entry.
Upvotes: 0
Reputation: 15722
Your code expects a value for guess
to be in the form data dictionary, but it's not present.
Upvotes: 0