在for循环中验证raw_input

时间:2017-07-06 15:59:30

标签: python

我试图创建一个验证循环来根据定义的列表检查用户输入,但由于某种原因,代码卡在一个循环中,永远要求用户重新输入值。我通过在循环中添加一个print命令进行测试,输入数据被存储到属性字典中,但似乎从来没有满足==标准来触发for循环的中断。

到目前为止,这是我的代码,我真的很感激任何有关我的错误的建议:

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'])

3 个答案:

答案 0 :(得分:1)

or的工作方式与您的想法不同。 它为您提供了第一个真实值。在Python中,非空字符串始终为true。因此:

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

将您的代码更改为:

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

检查输入的输入是否在元组中的名称中。如果没有,它会要求新的输入,否则它会停止要求输入。

答案 1 :(得分: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

答案 2 :(得分: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.')