Aug-30-2022, 03:22 PM
(Aug-30-2022, 01:02 PM)JonWayn Wrote: given the code snippet:
i = 0 for key, value in quiz.items(): i += 1 print(f"Question {str(i)} : {key['question']}")Line 5 fails with the error code,
The variable named 'i' is clearly an integer. Can someone explain why it fails with this error?
Error:TypeError: string indices must be integers
full code:
quiz = { "question1": { "question": "What is the capital of France?", "answer": "Paris" }, "question2": { "question": "What is the capital of Germany?", "answer": "Berlin" }, "question3": { "question": "What is the capital of Italy?", "answer": "Rome" }, "question4": { "question": "What is the capital of England?", "answer": "London" }, "question5": { "question": "What is the capital of Norway?", "answer": "Oslo" }, "question6": { "question": "What is the capital of Switzerland?", "answer": "Bern" }, "question7": { "question": "What is the capital of Austria?", "answer": "Vienna" }, "question8": { "question": "What is the capital of Spain?", "answer": "Madrid" }, "question9": { "question": "What is the capital of Portugal?", "answer": "Lisbon" }, "question10": { "question": "What is the capital of Belgium?", "answer": "Brussels" }, "question11": { "question": "What is the capital of Sweden?", "answer": "Stockholm" }, "question12": { "question": "What is the capital of Denmark?", "answer": "Copenhagen" }, "question6": { "question": "What is the capital of Holland?", "answer": "Amsterdam" }, } score = 0 i = 0 for key, value in quiz.items(): i += 1 print(f"Question {str(i)} : {value['question']}") answer = input("Answer? ") if answer.lower() == value['answer'].lower(): score += 1 print('Correct!') else: print("Incorrect :{") print("The correct answer is: " + value['answer']) print(f"Your score is {score}")
Error:TypeError: string indices must be integers
I did get it resolved with the help of another reply but thank you for pointing me to the proper usage of the interface. It's pretty awesome