我无法弄清楚这段关于python的问题,需要帮助

时间:2011-08-07 18:58:27

标签: python xhtml

我要创建一个游戏,用户输入名称和下注号码,我的程序将显示下注数量大于5个随机骰子的总和并显示它们的每张图片。我知道有什么不对,但我不知道在哪里

import cgi
import random

formData = cgi.FieldStorage()
playerName = formData["name"].value
playerGuess = int(formData["guess"].value)
theLength = 5
index =1
print "Content-type: text/html"


print "<p>Thanks for playing, " + playerName + ",</p>"
for die in range(theLength):
    die%i = random.randint(1,6)%index
    if int(die) == 1:
        print "<img src = "Images/dice-1.gif" alt="1" width="107" height="107" />"
    elif int(die) == 2:
        print "<img src = "Images/dice-2.gif" alt="2" width="107" height="107" />"
    elif int(die) == 3:
        print "<img src = "Images/dice-3.gif" alt="3" width="107" height="107" />"
    elif int(die) == 4:
        print "<img src = "Images/dice-4.gif" alt="4" width="107" height="107" />"
    elif int(die) == 5:
        print "<img src = "Images/dice-5.gif" alt="5" width="107" height="107" />"
    elif int(die) == 6:
        print "<img src = "Images/dice-6.gif" alt="6" width="107" height="107" />"
    index = index + 1
    total = die%i + die%i

print "<p>You bet the total would be at least " + playerGuess + ". The total rolled was " + sum + ".</p>"

if int(guessNumber) >= total:
    print "<p>You won!</p>"
else:
    print """<p>Sorry, you lose!</p>

3 个答案:

答案 0 :(得分:2)

该行

die%i = random.randint(1,6)%index

是无效的python语法。这是下面几行的表弟:

total = die%i + die%i

不会给你你期望的结果; %将被视为mod运算符。那个循环应该更像是:

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 = 0
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)
    total = total + val

答案 1 :(得分:1)

您没有发送正确的HTTP答案;在最终标题之后,应该会出现换行符,所以你正在寻找:

print("Content-Type: text/plain")
print("")


此外,

中的第一个%i
die%i = random.randint(1,6)%index

是语法错误;左侧必须是对变量的引用。


而不是total = die%i + die%i,您可能希望total += die%indextotal = 0位于最顶层。


顺便说一句,您可以通过编写

来大大简化大if .. elif
print "<img src = "Images/dice-%s.gif" alt="1" width="107" height="107" />" % die

答案 2 :(得分:0)

该行无效,因为您要分配操作的结果。

die%i = random.randint(1,6)%index

例如,如果说die是5而i是1则会导致:

0 = random.randint(1,6)%index

这没有任何意义。