Python测验代码问题:输入正确答案仍执行else分支求助
代码问题排查与解决
问题根源:你在字典里定义的answer值末尾带有\n换行符(比如'Delhi\n'),但input()函数获取的用户输入不会包含换行符,所以即便输入正确内容,两者对比也永远不相等,导致程序一直执行else分支。
解决方法
有两种可行的修正方式:
方式1:直接移除答案里的换行符
修改字典中answer的定义,去掉末尾的\n:
quizz = { 'Question1':{ 'question':'what is the capital of India ', 'answer':'Delhi' }, 'Question2':{ 'question':'what is the capital of germany ', 'answer':'Berlin' } } score = 0 for key,value in quizz.items(): print(value['question']) answer = input('Enter your answer ') if answer.lower() == value['answer'].lower(): print('Thats correct answer') score += 1 print('your score is '+ str(score)) else: print('wrong') print('your score is: ' + str(score) )
方式2:用strip()处理后再对比(更健壮)
通过strip()方法去除字符串首尾的空白字符(包括换行、空格、制表符等),可以兼容用户输入时不小心多打空格、答案里有多余空白的情况:
quizz = { 'Question1':{ 'question':'what is the capital of India ', 'answer':'Delhi\n' }, 'Question2':{ 'question':'what is the capital of germany ', 'answer':'Berlin\n' } } score = 0 for key,value in quizz.items(): print(value['question']) answer = input('Enter your answer ') # 去除两边空白后再做大小写不敏感对比 if answer.strip().lower() == value['answer'].strip().lower(): print('Thats correct answer') score += 1 print('your score is '+ str(score)) else: print('wrong') print('your score is: ' + str(score) )
内容的提问来源于stack exchange,提问作者ALEXANDER ABRAHAM
相关产品推荐
相关产品推荐

