首页 > 解决方案 > 我只需要所选选择的结果,但它会显示所有其他结果以及任何选择

问题描述

#purpose - program to perform some list operations
list1 = []
list2 = []
print("Select operation.")
print("1.Check Length of two list's are Equal")
print("2.Check sum of two list's are Equal")
print("3.whether any value occur in both ")
print("4.Display Lists")

while True:
    choice = input("Enter any choice ")
    if choice in ('1', '2', '3', '4'):
        list1Len = int(input("Enter the number of elements in list 1 : "))
        for i in range(0, list1Len):
            print("Enter the element ", i+1, ":")
            item1 = int(input())
            list1.append(item1)
        list2Len = int(input("Enter the number of elements in list 2 : "))
        for j in range(0, list2Len):
            print("Enter the element ", j+1, ":")
            item2 = int(input())
            list2.append(item2)
        if choice == '1' and len(list1) == len (list2):
         print(" Length are Equal")
        else :
         print(" Length are Not Equal")
        
        if choice == '2'and sum(list1) == sum (list2):
         print(" Sums are Equal")
        else :
         print("  Sums are Not Equal")
      
        if choice == '3':
         list3 =[x for x in list1 if x in list2][enter image description here][1]
         print("Common elements in both list are \n", list3) 
      
        if choice == '4':
         print( "List 1 is :\n",list1 ,"List 2 is :\n", list2)

我只需要选定选项的结果,但它显示所有其他结果,任何选项它显示我包含在代码中的所有操作,如何修复它,我提供了一个图像。

希望我说得足够清楚......

标签: pythonloopsif-statementwhile-loop

解决方案


该代码完全按照您的要求执行:检查四个选项中的每一个。即使它不是正确的选择,您也会打印失败消息。您需要将逻辑嵌套在两个级别:一个用于确定正确的选择,另一个用于确定正确的响应。

if choice == '1':
    if len(list1) == len (list2):
        print(" Length are Equal")
    else:
        print(" Length are Not Equal")

elif choice == '2':
    if sum(list1) == sum (list2):
        print(" Sums are Equal")
    else:
        print("  Sums are Not Equal")

... 等等


推荐阅读