如何以小写形式输入?输入为小写时程序正在运行,但输入为大写/大写时显示错误

时间:2020-05-28 11:26:44

标签: python-3.x

available_cars = {
'swift': 'Rs. 5.19 lakh',
'creta': 'Rs. 9.99 lakh',
'brezza': 'Rs. 7.34 lakh', 
'i20': 'Rs. 5.60 lakh.', 
'baleno': 'Rs. 5.64 lakh', 
'seltos': 'Rs. 9.89 lakh', 
'nexon': 'Rs. 6.95 lakh', 
'verna': 'Rs. 9.31 lakh'
} 

asked_car = input('Please enter (only name) the desired car:') 
if asked_car.lower() in available_cars.keys(): 
    print(f"The {asked_car.title()} is available and will cost you 
      {available_cars[asked_car]}.") 
else : 
    print(f"Please recheck the name enter!") 

我想使用用户输入并显示carname(key)和price(value),它在小写输入中起作用,但是不接受小写输入并打印出来

Please enter (only name) the desired car:Swift
Traceback (most recent call last):
  File "Rental_Car.py", line 13, in <module>
    print(f"The {asked_car.title()} is available and will cost you 
{available_cars[asked_car]}.") 
KeyError: 'Swift'

***Repl Closed***

1 个答案:

答案 0 :(得分:0)

您忘记在f字符串中.lower()字典available_cars[asked_car]的键。

替换此行:

 print(f"The {asked_car.title()} is available and will cost you {available_cars[asked_car]}.")

与此:

 print(f"The {asked_car.title()} is available and will cost you {available_cars[asked_car.lower()]}.")

将解决此问题。


似乎更符合问题标题的另一个选项是在.lower()之后紧跟input()

asked_car = input('Please enter (only name) the desired car:').lower()
相关问题