首页 > 解决方案 > 如何在我的问题中定义更多选项?

问题描述

a1=str(input("4.Name one neighbouring country of India."))
if a1.lower()== ("pakistan"):                  
    print("correct +20 Score")
    score+=20
if a1.lower()== ("china"):                  
    print("correct +20 Score")
    score+=20
if a1.lower()== ("nepal"):                  
    print("correct +20 Score")
    score+=20
if a1.lower()== ("bhutan"):                  
    print("correct +20 Score")
    score+=20
if a1.lower()== ("bangladesh"):                  
    print("correct +20 Score")
    score+=20    
if a1.lower()== ("myanmar"):                 
    print("correct +20 Score")
    score+=20
if a1.lower()== ("sri lanka"):                  
    print("correct +20 Score")
    score+=20
if a1.lower()== ("maldivs"):                  
    print("correct +20 Score")
    score+=20    
else:
    print("incorrect +0 Score")

我这样做是因为我的问题包含 8 个答案,但在输出中,它同时打印“正确 +20 分数”和“不正确 +0 分数”。我想修复它请帮助我。

标签: python

解决方案


比较时需要使用else语句,而不是多个ifs. 如果你需要多个ifs,你应该使用elif.

https://www.tutorialspoint.com/python/python_if_else.htm

但是,将您的答案存储在列表中并检查用户的响应是否存在于列表中会更加清晰和简洁,否则没有分数。

neighbouring = ['pakistan', 'china', 'nepal', 'bhutan', 'bangladesh', 'myanmar', 'sri lanka', 'maldivs']

a1=str(input("4.Name one neighbouring country of India."))

if a1.lower() in neighbouring:
    print('correct 20 score')
    score += 20
else:
    print('incorrect')

推荐阅读