此代码按执行顺序排列的重要事项:
1.打开并阅读文件"商品"
2.从文件中选择一个随机行" Goods"到字典"货物"
3.通过if块,将随机值分配给字典" cost"如果goods [x]等于它被比较的字符串。
4.Print" goods"," cost"
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)
这段代码的问题在于字典:&#34; cost&#34;当货物[x]等于:朗姆酒,水果或鸦片时,不会从if块分配值。
有人可以告诉我这里发生了什么吗?
答案 0 :(得分:0)
你的问题是你使用两个相同的标志。 cost[x] == randint(3, 4)
您只需要使用一个。希望这有帮助!