In: Computer Science
On Python perform the following operations on numbersList = [-11, -4, 5, 12, 13, 14, 19]
a) Ask the user to enter a number to add to the list. Append the number to the list if the number does not already exist in the list. If the number already exists in the list notify the user.
b) Improve your code by using a loop. Keep asking the user for a new element to add to the list until they enter a number which is not in the list.
c) Improve your code further by adding an outer loop. Ask the user if they want to continue adding an element to the list. When the user is done with adding elements, print the number of the elements in the final list.
a)
numbersList = [-11, -4, 5, 12, 13, 14, 19]
print(numbersList)
N=int(input(" Enter a number to add to the list: ")) #integer number input by user
if N in numbersList: #check if the number is present in list or not
print("Number already exist in the list")
else:
numbersList.append(N) #apeend number to the given list
print(numbersList)
b)
numbersList = [-11, -4, 5, 12, 13, 14, 19]
print(numbersList)
while True: #iterating loop until the break keyword appear
N=int(input(" Enter a number to add to the list: "))
if N in numbersList:
print("Number already exist in the list")
break
else:
numbersList.append(N)
print(numbersList)
c)
numbersList = [-11, -4, 5, 12, 13, 14, 19]
print(numbersList)
k="y"
while k.lower()=="y":#iterating outer loop until user entetred y
while True:
N=int(input(" Enter a number to add to the list: "))
if N in numbersList:
print("Number already exist in the list")
break
else:
numbersList.append(N)
print(numbersList)
k=input("If you want to continue press 'y': ")
print("Number of elements in the final list = ",len(numbersList))