Python字典;接收用户输入;超出范围时输入错误代码

Python dictionary; receive user input; enter error code when out of range

我在编字典!我试图让用户 select 一个介于 1 - 10 到 为它生成韩语单词。 我能够让用户输入以打印出正确的翻译,但我希望我的代码 如果 1 - 10 之间的数字未 selected,请告诉用户重试。求助.

#1 is key
#all keys need to be unique
#Hana is value
print ("Welcome to the Korean Converter!")

user = int(input("Enter a number between 1 and 10: "))
        
koreanConversion = {
    1: "Hana",
    2: "Tul",
    3: "Set",
    4: "Net",
    5: "Ta Sut",
    6: "Yuh Sut",
    7: "Il Jop",
    8: "Yu Dulb",
    9: "Ah Hop",
   10: "Yul"

}


print (koreanConversion[user])


#else: 
 #   user = int(input("Please try again: "))
 #if (koreanConversion[user]) != [user]
  #   print("Please try again.")

当您的输入有一些未发现的情况时,使用 [] 通常不是一个好主意,因此对字典使用 .get 方法:

print(koreanConversion.get(user, ""))

这意味着如果项目不存在则获取带有用户密钥的项目打印“”这是空的,这应该可以解决您的问题

检查这个


koreanConversion = {
    1: "Hana",
    2: "Tul",
    3: "Set",
    4: "Net",
    5: "Ta Sut",
    6: "Yuh Sut",
    7: "Il Jop",
    8: "Yu Dulb",
    9: "Ah Hop",
    10: "Yul"
}


print("Welcome to the Korean Converter!")

while True:
    _input = input("Enter a number between 1 and 10: ")
    number = int(_input)
    if koreanConversion.get(number, None):
        print(koreanConversion[number])
        break
    else:
        print('Try again.')
        continue

我建议您尝试使用列表:

def KoreanConverter():
    koreanConversion = ["Hana", "Tul", "Set", "Net", "Ta Sut", "Yuh Sut", "Il Jop", "Yu Dulb", "Ah Hop", "Yul"]

    print("Welcome to the Korean Converter!")
    i = int(input("Enter a number between 1 and 10: ")) - 1
    if not i in range(0, 9):
        return "Please provide a valid number between 1 and 10!"
    
    return koreanConversion[i]
        
playing = True
while playing: 
    print(KoreanConverter())
    playing = ("y" == input("Keep converting ? y/N")

几个人建议使用 .get() 和默认 and/or 提前检查以查看该项目是否在字典中。另一种选择是使用 try/except:

while True:
    try:
        print(koreanConversion[
            int(input("Enter a number between 1 and 10: "))
        ])
        break
    except (KeyError, ValueError):
        print('Try again.')

以这种方式使用异常处理的一个好处是您可以在一个地方处理两种异常:

  • ValueError 如果 int() 转换失败
  • KeyError 如果它是有效的 int 但不在你的字典中