这段代码应该按照执行顺序做一些重要的事情:
1.打开并读取文件"Goods“
2.将文件"Goods“中的任意一行分配给字典"goods”
3.遍历if块,该代码块将为字典"cost“分配一个随机值,前提是goodsx等于要比较的字符串。
4.打印“货物”和“成本”
5.重复步骤2-4,再重复2次。
from random import randint
print("You search for things to buy in the market, and find:")
f = open('Goods', 'r') #Opens file "Goods"
lines = f.readlines() #Loads all lines from "Goods"
goods = {1:"", 2:"", 3:""}
cost = {1:"", 2:"", 3:""}
x = 0
while x < 3:
x += 1
goods[x] = lines[randint(0, 41)].strip()
#Checks to see if goods[x] is equal to the string on the right, if it is, it assigns cost[x] to a random integer
if goods[x] == "Lumber":
cost[x] = randint(2, 3)
elif goods[x] == "Rum":
cost[x] == randint(3, 4)
elif goods[x] == "Spices":
cost[x] = randint(4, 5)
elif goods[x] == "Fruit":
cost[x] == randint(2, 4)
elif goods[x] == "Opium":
cost[x] == randint(1, 5)
findings = '%s for %s gold.' %(goods[x], cost[x])
print(findings)这段代码的问题是,当goodsx等于: Rum、Fruit或Opium时,字典:“cost”不能从if块中获得赋值。
有人能告诉我这是怎么回事吗?
The file "Goods"
发布于 2016-08-19 01:43:11
你的问题是你使用的是两个等号。cost[x] == randint(3, 4)你只需要使用一个。希望这能有所帮助!
https://stackoverflow.com/questions/39024200
复制相似问题