[英]I am having problems reassigning a variable in python
我正在嘗試用python創建一個文字冒險游戲。 我正在使用randint創建一個介於0和2之間的數字,當我使用if語句獲取隨機數並將biome變量分配給biome類型時,它將取變量的原始版本並將其用作biome。
#Defines game()
print ('''You are in a %s biome.'''%(biome))
biome='placeholder'
import random
trees=random.randint(0,50)
biomes=random.randint(0,2)
animals=random.randint(0,3)
wolves=random.randint(0,5)
if biomes == "0":
biome='Forest'
if biomes == "1":
biome='Taiga'
if biomes == "2":
biome='Mountain'
print ('''You are in a %s biome.'''%(biome))
biomes
是int價值。 "0"
是字符串值。
這兩個值永遠不能相等。
>>> 0 == "0"
False
使用int文字。
if biomes == 0:
biome = 'Forest'
elif biomes == 1:
biome = 'Taiga'
elif biomes == 2: # else
biome = 'Mountain'
我建議您使用random.choice作為其他建議。 簡單,易於閱讀。
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Mountain'
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Mountain'
>>> random.choice(['Forest', 'Taiga', 'Mountain'])
'Taiga'
random.randint(...)
返回一個整數。 您正在將值與字符串進行比較。
>>> type(randint(0, 2))
<type 'int'>
您的if
語句應重寫為-
if biomes == 0:
biome='Forest'
elif biomes == 1:
biome='Taiga'
else:
biome='Mountain'
PS-您不需要三個if
語句,因為如果值為0
,則永遠不能為1
或2
,因此無需檢查條件。 您可以改用if-elif-else
構造。
這是一種更容易理解的方式:
from random import choice
biomes = ['Forest', 'Tiaga', 'Mountain']
biome = choice(biomes)
然后,如果生物群落數量增加或減少,則不必擔心更新隨機數的范圍,也不必擔心if
語句正確無誤。
您需要比較0
而不是字符串值"0"
, if biome == 0:
但是,可以使用random.choice
從列表中隨機選擇一個生物群系進行簡化。
biome = random.choice(['Forest', 'Taiga', 'Mountain'])
並消除你的if
完全秒。
我認為您應該嘗試使用if語句biome == 1代替biome ==“ 1”,並且對biome == 2和biome == 3相同。
這是因為您正在將整數值與字符串(永遠不會相等)進行比較。 這將起作用:
import random
trees=random.randint(0,50)
biomes=random.randint(0,2)
animals=random.randint(0,3)
wolves=random.randint(0,5)
# Compare biomes (which is an integer) to another integer
if biomes == 0:
biome='Forest'
# Use elif for multiple comparisons like that
elif biomes == 1:
biome='Taiga'
# Use an else here because the only other option is 2
else:
biome='Mountain'
print ('''You are in a %s biome.'''%(biome))
另請注意,我刪除了腳本的第一行和第二行。 第一個因為沒有定義biome
被炸毀,而第二個則什么也沒做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.