使用IF子句时,我在显示某个图像时遇到问题。当生成的随机数等于“1”时,想法是显示骰子“1”面的图片,等等。
我也难以将获胜结果加倍。例如,下注10美元并赢得20美元。我一直得到1010美元
import cgi
form = cgi.FieldStorage()
name = str(form.getvalue("name"))
bet = str(form.getvalue("bet"))
print """Content-type: text/html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Lab 10</title>
</head><body>
"""
import random
die1 = str(random.randint(1,6))
die2 = str(random.randint(1,6))
print "<p>Thanks for playing, "+name+" . You rolled "+die1+".</p>"
print "<p> Your opponent rolled "+die2+".</p>"
if die1==die2:
print "You win $"+bet+"!</p>"
if die1>die2:
print "You win $"+bet*2+"!</p>"
if die1<die2:
print "You lose $"+bet+"! Try again.</p>"
if die1==int("1"):
print "<img src='dice-1.png' alt='1' width='107' height='107' />"
print "</body>"
print "</html>"
答案 0 :(得分:0)
您正在将字符串和整数相互更改并进行比较,这些比较不会在Python 2中引发错误,但也无法正常工作。在某些东西是字符串还是数字时要保持一致。使用str.format
将值插入到字符串中,而不必担心连接。
name = str(form.getvalue("name"))
bet = int(form.getvalue("bet"))
print """Content-type: text/html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Lab 10</title>
</head><body>
"""
import random
die1 = random.randint(1,6)
die2 = random.randint(1,6)
print "<p>Thanks for playing, {}. You rolled {}.</p>".format(name, die1)
print "<p> Your opponent rolled {}.</p>".format(die2)
if die1 == die2:
print "You win ${}!</p>".format(bet)
if die1 > die2:
print "You win ${}!</p>".format(bet*2)
if die1 < die2:
print "You lose ${}! Try again.</p>".format(bet)
print """<img src="dice-{}.png" alt="{}" width="107" height="107" /><br />
<img src="dice-{}.png" alt="{}" width="107" height="107" />""".format(
die1, die1, die2, die2)