【发布时间】: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