여기에 사전 my_dictionary={“Potato”:12, “Onion”:16, “Ginger”:15, “Garlic”:12, “Tomato”:15
이 주어진 프로그램이 있습니다 . 이제 사용자의 입력으로 식료품 이름을 가져와 식료품의 총 가격을 보여주는 파이썬 프로그램을 작성해야합니다. 그러나 처리 할 몇 가지 예외가 있습니다 .
입력이 감자, 양파, 생강 인 경우 출력은 다음과 같아야합니다. 43
그리고 입력 인 경우 : 감자, 양파, 생강, 쇠고기 출력은해야한다 : 일부 식료품은 사전에 사용할 수 없습니다.
나는 이것을 시도했다 :
user_input = input("Enter grocery names: ")
user_input = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
try:
for items in user_input:
if items in my_dictionary.keys():
total_price = total_price + my_dictionary[items]
print(total_price)
except ValueError:
for items in user_input:
if items not in my_dictionary:
break
print("Some groceries are not avaiable in the dictionary.")
출력은 다음과 같습니다.
Enter grocery names: Potato,Onion,Ginger,Beef
43
어떻게해야합니까?
질문에 대한 해결책 :
user_input = input("Enter grocery names: ")
user_input = user_input.split(',')
my_dictionary={"Potato":12, "Onion":16, "Ginger":15, "Garlic":12, "Tomato":15}
total_price = 0
for items in user_input:
try:
total_price = total_price + my_dictionary[items]
except:
total_price = "Some groceries are not avaiable in the dictionary."
break
print(total_price)
출력을 다음과 같이 인쇄합니다.
Enter grocery names: Potato,Onion,Ginger,Beef #Input
Some groceries are not avaiable in the dictionary. #Output
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다