我正在做一个控制台个性测试,我想为玩家输入的黄道十二宫打印报价。我不想使用大量的if
语句,我可以使用字典和循环吗?
其中键是十二生肖,值是特定的引号,然后使用循环和简短的if语句用给定的输入循环键,并打印相应的值,即引号。
这是我的代码:
sign = input("What is your zodiac sign ? (Enter one of these: aries, taurus, gemini, cancer, leo, virgo, libra, scorpio, sagittarius, capricorn, aquarius, pisces ) ---> ")
zodiac_signs = {
"aries": "quote",
"taurus": "quote",
"gemini": "quote",
"cancer": "quote",
"leo": "quote",
"virgo": "quote",
"libra": "quote",
"scorpio": "quote",
"sagittarius": "quote",
"capricorn": "quote",
"aquarius": "quote",
"pisces": "quote"
}
接下来我该怎么办?
答案 0 :(得分:2)
您只需使用以下命令即可从字典中获得十二生肖
sign = input("What is your zodiac sign ? (Enter one of these: aries, taurus, gemini, cancer, leo, virgo, libra, scorpio, sagittarius, capricorn, aquarius, pisces ) ---> ")
zodiac_signs = { "aries": "quote", "taurus": "quote", "gemini": "quote", "cancer": "quote", "leo": "quote", "virgo": "quote", "libra": "quote", "scorpio": "quote", "sagittarius": "quote", "capricorn": "quote", "aquarius": "quote", "pisces": "quote" }
try:
print(zodiac_signs[sign])
except(Exception e):
print("That's not a zodiac sign")
答案 1 :(得分:2)
Python字典具有一个专门解决此问题的get
方法。
print(zodiac_signs.get(sign, "That's not a zodiac sign"))
如果它在dict
中,则通过返回给定键的值来运行,否则返回给定的默认参数。
答案 2 :(得分:1)
加合Challe所说的话,您可能还希望小写输入,以使键匹配,即使它们的首字母使用大写也是如此。