Python 3.4掷骰子模拟器代码错误
所以我这里有一个掷骰子模拟游戏的代码,我正在Eclipse Neon Python 3.4中使用PyDev创建这个游戏。你猜一个数字和一个1-6之间的数字会随机生成,如果你猜对了数字,你就继续前进,等等Python 3.4掷骰子模拟器代码错误,python,eclipse,python-3.4,Python,Eclipse,Python 3.4,所以我这里有一个掷骰子模拟游戏的代码,我正在Eclipse Neon Python 3.4中使用PyDev创建这个游戏。你猜一个数字和一个1-6之间的数字会随机生成,如果你猜对了数字,你就继续前进,等等 guess1 = input("Enter your first guess as to which side the dice will roll on (1-6): ") import random dice_side = ['1','2','3','4','5','6'] game =
guess1 = input("Enter your first guess as to which side the dice will roll on (1-6): ")
import random
dice_side = ['1','2','3','4','5','6']
game = print(random.choice(dice_side))
if guess1 == game:
print("Congrats that's the correct guess!")
else:
print("That's the wrong guess!")
我测试了代码,每次我输入一个数字,控制台总是打印“猜错了!”。即使我猜的数字与生成的数字匹配。我不太明白这是怎么回事。我在想也许我应该用一个while循环来代替。然而,我想知道我是否可以这样做,以及这个特定代码有什么问题。我是Python新手,因此非常感谢您的帮助。提前谢谢 print()
返回None
。如果在该行之后打印game
,您将看到它的值。要修复:
game = random.choice(dice_side)
为了理解为什么你的游戏不起作用,你应该首先试着理解这一行有什么问题
game=print(random.choice(dice_side))
。这是你的游戏的一个修改版本,它会给你一些线索,试着运行它并理解它,然后检查你的脚本:
import random
dice_side = ['1', '2', '3', '4', '5', '6']
game = random.choice(dice_side)
print("Dice has been rolled... :D {0}".format(game))
guess = -1
number_attempts = 0
while True:
guess = raw_input("Which side the dice has rolled on (1-6): ")
number_attempts += 1
if guess == game:
print("Congrats that's the correct guess! You've tried {0} times".format(
number_attempts))
break
print("That's the wrong guess!")
一个建议是,一旦你发现了为什么不起作用,就尝试添加越来越多的新功能,直到你的游戏变得真正上瘾和有趣。。。但最重要的是,尽情享受:)想想
print
会返回什么。