【问题标题】:I need only the result of selected choice but it displays all other results with any choice我只需要所选选择的结果,但它会显示所有其他结果以及任何选择
【发布时间】:2021-01-27 04:32:54
【问题描述】:
#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)

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

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

【问题讨论】:

  • 没有区分选项的代码,只检查输入是否是选项之一。不完整(?)
  • 如何区分选择?
  • 您的 If 语句没有嵌套在一起。使其成为一个嵌套的If。示例If choice == 1 and something is True: do something elif choice 1 and something is False: do something elif choice 2....

标签: python loops if-statement while-loop


【解决方案1】:

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

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")

...等等

【讨论】:

    【解决方案2】:

    不要将测试选择与测试相应条件的结果结合起来。请改用嵌套的if

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

    按照您编写的方式,如果他们做出了不同的选择或该选择的条件不正确,则会执行 else: 块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      相关资源
      最近更新 更多