Issue
I tried running this code in PyCharm and Spyder , but every time wrong output was given . But same program is running perfectly fine in programbiz online python interpreter. I am uable to figure out why this is happening ? 2]2
First image is from programbiz and another one is same image in two parts of spyder IDE . First one is showing correct way , the program should run and other one is giving wrong output , even if I enter correct answer.
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 Spain?",
"answer": "Madrid"
},
"question5": {
"question": "What is the capital of Portugal?",
"answer": "Lisbon"
},
"question6": {
"question": "What is the capital of Switzerland?",
"answer": "Bern"
},
"question7": {
"question": "What is the capital of Austria?",
"answer": "Vienna"
}
}
score = 0
for key, value in quiz.items():
print(value['question'])
answer = input('Answer ?')
if answer.lower() == value['answer'].lower():
print('Correct')
score = score + 1
print('Your score is: ' + str(score))
print(' ')
print(' ')
else:
print('Wrong!')
print('The answer is :' + value['answer'])
print('Your score is:' + str(score))
print(' ')
print(' ')
print('You got ' + str(score) + 'out of 7 questions correctly!')
print('Your percentage is ' + str(score/7 * 100) + '%')
Solution
The problem are leading spaces.
Answer's input prompt('Answer ?') doesn't have space at the end and cursor starts right after question mark.
So to get 'Paris' string answer should be looking: Answer ?Paris
.
When you press space before typing to make it prompt and answer look separated: Answer ? Paris
, you get ' Paris' and it's not equals to 'Paris'. That's why you get error.
Solution:
- Put space at the end of input prompt to make it more intuitive:
input('Answer ? ')
orinput('Answer: ')
- Add
answer.strip()
, it will remove all leading and trailing spaces if there are any.
Answered By - andrewf1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.