在过去的几天里,我一直在尝试自学Python和CS。这个问题是很基本的,但是我觉得了解问题的根源很重要。有问题的程序是一个简单的madlibs生成器模板。
import random
name1 = input("Please enter a name.\n")
verb1 = input("Please enter a verb.\n")
noun1 = input("Please enter a noun.\n")
noun2 = input("Please enter another noun.\n")
adjective = input("Please enter an adjective.\n")
verb2 = input("Please enter an verb.\n")
game1_running = False
game2_running = False
game3_running = False
while((game1_running == False) and (game2_running == False) and (game3_running == False)):
chance = random.randint(1, 3)
if chance == 1:
game1_running == True
break
if chance == 2:
game2_running == True
break
if chance == 3:
game3_running == True
break
while game1_running == True:
print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game1_running = False
break
while game2_running == True:
print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game2_running = False
break
while game3_running == True:
print(name1 + "Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game3_running = False
break
当我运行该程序时,一切运行顺利,但没有打印出游戏1、2或3。我相信这是因为if语句未检测到随机数(因为我只是遇到了类似的问题)用骰子模拟器)。任何关于改进或更好的方法的建议都将不胜感激,并对当前代码中发生的事情进行解释。
答案 0 :(得分:0)
您的代码没有按照您的要求做的原因在这里:
if chance == 1:
game1_running == True
break
if chance == 2:
game2_running == True
break
if chance == 3:
game3_running == True
break
==
用于测试是否相等,但是您想分配一个值,因此应改用=
。
不过,更一般而言,在您可能希望多次重复一组操作直到某个条件成立之前,最好使用while
循环。如果您只想重复一次操作,则使用if
/ else
更合适。设置完后,第一个while
循环可能会完全消除,因此只能执行一次。
您的游戏主体可以这样重写:
game1_running = False
game2_running = False
game3_running = False
chance = random.randint(1, 3)
if chance == 1:
game1_running = True
elif chance == 2:
game2_running = True
elif chance == 3:
game3_running = True
if game1_running == True:
print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game1_running = False
elif game2_running == True:
print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game2_running = False
elif game3_running == True:
print(name1 + "Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2)
game3_running = False
设置一个条件(gameX_running
,然后稍后对其进行测试也代表了不必要的额外步骤,因此您可以组合以下if
/ else
个条件集:>
chance = random.randint(1, 3)
if chance == 1:
print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2)
# do other game 1 runtime stuff here
elif chance == 2:
print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2)
# game 2 runtime stuff
elif chance == 3:
print(name1 + "Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2)
# game 3 runtime stuff
在这样的游戏情况下,while
循环的适当用法可能是连续执行许多游戏,例如:
n = 0
while n < 10:
chance = random.randint(1, 3)
if chance == 1:
print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2)
elif chance == 2:
print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2)
elif chance == 3:
print(name1 + " Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2)
n += 1