2017-07-06 42 views
1

我試圖創建一個驗證循環來檢查用戶輸入與定義的列表,但由於某種原因代碼卡在循環永久要求用戶重新輸入值。我通過在循環中添加打印命令進行測試,並將輸入數據存儲到屬性字典中,但它似乎不符合==標準來觸發for循環的中斷。驗證for循環中的raw_input

這裏是我到目前爲止的代碼,會很感激在我要去哪裏不對勁任何建議:

attributes = {'Name': 'None', 'Class': 'None', 'Strength': 3, 'Agility': 3, 'Wounds': 3, 'Intelligence': 3} 

attributes['Name'] = raw_input('What is your character\'s name?') 
attributes['Class'] = raw_input('Choose your character\'s class, enter Warrior, Mage, Ranger or Thief.') 

#this is the section I am struggling with! 
for values in attributes: 
    if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief": 
     attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.') 
     continue 
    elif attributes['Class'] == "Warrior" or "Mage" or "Ranger" or "Thief": 
     break 

if attributes["Class"] == "Warrior": 
    attributes["Strength"] += 1 
    attributes["Wounds"] += 1 
elif attributes["Class"] == "Mage": 
    attributes["Intelligence"] += 2 
elif attributes["Class"] == "Ranger": 
    attributes["Strength"] += 1 
    attributes["Agility"] += 1 
elif attributes["Class"] == "Thief": 
    attributes["Agility"] += 1 
    attributes["Intelligence"] += 1 

print 
print 'Name: ' + attributes['Name'] 
print 'Class: ' + attributes['Class'] 
print 'STR: ' + str(attributes['Strength']), 'AGI: ' + str(attributes['Agility']), 'WOU: ' + str(attributes['Wounds']) ,'INT: ' + str(attributes['Intelligence']) 

回答

0

if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief": 

將始終解析爲True因爲bool("Mare") == True所以你的循環永遠不會打破。

我認爲你正在尋找的是更接近於:

if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"): 

如果你只是想檢查attributes['Class']值,下面的循環可能更合適:

while attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"): 
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.') 
1

or不同的工作比你想象的。 它給你的第一個值是真實的。在Python中,非空字符串總是如此。因此:如果輸入的輸入是在你的元組的名稱

if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"): 
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.') 
    continue 
else: 
    break 

此檢查:

>>> "Warrior" or "Mage" or "Ranger" or "Thief" 
'Warrior' 

更改您的代碼。如果不是,它要求新的輸入,否則它會停止詢問輸入。

1

您的OR應該在第一個IF中爲AND。你將不得不做他們爲:

if attributes['Class'] != "Warrior" and attributes['Class'] != "Mage" and attributes['Class'] != "Ranger" and attributes['Class'] != "Thief" 

更簡單的方法來做到這一點會尋找他們的列表:

for values in attributes: 
    if attributes['Class'] not in ["Warrior", "Mage", "Ranger", "Thief"]: 
     attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.') 
     continue 
    elif attributes['Class'] in ["Warrior", "Mage", "Ranger", "Thief"]: 
     break