0

作为 Python 的新手,我正在做的一件事是字符生成器。正如您从我整理的代码中看到的那样,我正在尝试进行比赛选择。

 ########Race########
#.racechoose (label)
hero_race = input("What is your hero's race? (Human / Elf / Dwarf / Orc) Don't forget to capitalize! ")
if hero_race == 'Human':
    print ("Humans are well-rounded, average characters. They have a bonus of + 1 to Speed and + 1 to Int.")
    yn = input ("Do you want to be a Human (Y/N)? ")
    if yn == 'y' or yn == 'Y':
        profile['Race'] = "Human"
        print ("Your hero", profile['Name'], "is a human.")
    else:
        #goto racechoose

elif hero_race == 'Elf':
    print("Elves are very fast, and they have a bonus of + 2 to Speed.")
    yn = input("Do you want to be an Elf? (y/n) ")
    if yn == 'y' or yn == 'Y':
        profile['Race'] = "Elf"
        print("Your hero ", profile['Name'], "is an Elf.")
    else:
        #goto racechoose

elif hero_race == 'Dwarf':
    print("Dwarves are small, but strong. Dwarves get a bonus of + 2 Muscle.")
    yn = input("Do you want to be a Dwarf? (Y/N) ")
    if yn == 'y' or yn =='Y':
        profile['Race'] = 'Dwarf'
        print("Your hero ", profile['Name'], "is a Dwarf.")
    else:
        #goto racechoose

else: #orc
    print("Orcs are brute muscle. Orcs get a bonus of + 3 to Muscle, but - 1 to Int.")
    yn = input("Do you want to be an Orc? (Y/N) ")
    if yn == 'y' or yn == 'Y':
        profile['Race'] = 'Orc'
        print("Your hero ", profile['Name'], "is an Orc.")
    else:
        #goto racechoose

请忽略 goto 和 label 注释——我最近刚刚停止使用 blitzbasic,现在正在尝试为 python 查找 label 和 goto 命令。

无论如何,我在 elif hero race Elf 行上得到“预期有缩进块”,我想知道如何正确缩进这段代码。谢谢!

4

3 回答 3

2

出于某种原因,如果您将块(需要语句的块)留空,则在此处pass用作占位符。使用评论是行不通的。

else:
    pass

来自文档

pass是一个空操作——当它被执行时,什么也没有发生。当语法上需要语句但不需要执行代码时,它可用作占位符,例如:

例子:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)

并且if yn == 'y' or yn == 'Y':可以简化为if yn.lower() == 'y':

于 2013-06-25T17:45:14.987 回答
1

你为什么不直接在这样的函数中提取常见的东西:

def get_race_description(race):
    return {
        'human': "Humans are well-rounded ...",
        'elf': "Elves are very fast ...",
         # all the other race descriptions
    }.get(race.lower(), "WTF? I don't know that race")

def confirm_race_selection(race):
    print (get_race-description(race))
    yn = input ("Do you want to be {0} (Y/N)? ".format(race))
    return (yn.lower() == 'y')

while True:
    hero_race = input("What is your hero's race?")
    if (confirm_race_selection(hero_race)):
        profile['Race'] = hero_race
        print ("Your hero {0} is {2}".format(profile['Name'], hero_race))
        break

这个片段可以重写而不使用break,但是我已经做了很多重构,所以现在由你决定

于 2013-06-25T17:51:40.493 回答
0

除了评论之外,您还需要其他内容,如果必须,请使用 pass。

最好使用字典而不是嵌套的 if 语句,即如果您有一个包含配置文件键、文本输出、描述的字典并使用默认为“受害者”的 get,则代码会更简洁。

于 2013-06-25T17:45:10.373 回答