Python 3输入和if语句

时间:2013-09-08 02:20:52

标签: validation if-statement python-3.x user-input

我在输入问题上遇到了一些麻烦,该输入问题应该允许玩家从5场首发比赛中选择一个。我使用了以下代码。

def racechoice():
    players.race = input('After you get a chance to think, you choose to be...') #Here race is chosen
    if players.race == "dwarf" or "Dwarf": #Race starting stats
        players.race = "Dwarf"
        players.level = 1
        players.strength = 12
        players.agility = 6
        players.inteligence = 8
        players.vitality = 14
    elif players.race == "Orc" or "orc":
        players.race = "Orc"
        players.level = 1
        players.strength = 14
        players.agility = 10
        players.inteligence = 4
        players.vitality = 12
    elif players.race == "elf" or "Elf":
        players.level = 1
        players.race = "Elf"
        players.strength = 8
        players.agility = 13
        players.inteligence = 12
        players.vitality = 7
    elif players.race == "Human" or "human":
        players.level = 1
        players.race = "Human"
        players.strength = 10
        players.agility = 10
        players.inteligence = 10
        players.vitality = 10
    elif players.race == "gnome" or "Gnome":
        players.race = "Gnome"
        players.strength = 5
        players.agility = 11
        players.intelligence = 17
        players.vitality = 7

调用时显示玩家的统计数据:

def stats():
    print(players.name)
    print(players.race)
    print("Level: "+ str(players.level) +" Strength: "+ str(players.strength) +" Agility: " + str(players.agility) +" Inteligence: "+ str(players.inteligence) +" Vitality: "+ str(players.vitality))
无论玩家选择什么,它都可以作为矮人的矮人统计数据回归。我是Python的新手,我想知道,我没有正确使用if / elif语句吗? ex)在你有机会思考之后,你选择成为...... Orc ECEP 侏儒 等级:1力量:12敏捷:6智力:8活力:14

2 个答案:

答案 0 :(得分:0)

有问题,你应该这样做:

if players.race == "dwarf" or "players.race == Dwarf":

但更好的是,将您的条件改为:

elif players.race.lower() == "orc":

还建议您使用类来封装功能,例如:

class Player(object):
    def __init__(self, race, level, strength, agility, inteligence, vitality):
        self.race = race
        self.level = level
        self.strength = strength
        self.agility = agility
        self.inteligence = inteligence
        self.vitality = vitality

player = Player('Dwarf', 1, 12, 6, 8, 14)

然后你的racechoice函数看起来如此:

def racechoice():
    race = input('After you get a chance to think, you choose to be...')
    if race.lower() == 'dwarf':
        player = Player('Dwarf', 1, 12, 6, 8, 14)
    elif race.lower() == 'orc':
        player = Player('Orc', 1, 14, 10, 4, 12)
    ...
    return player

答案 1 :(得分:0)

您不能以这种方式使用or。您的所有if/elif语句都应采用以下格式:

if players.race == "dwarf" or players.race == "Dwarf":

"Dwarf"本身被Python视为True,空字符串""被视为False,因此您的第一个if始终成功。