I’ve been learning some lists lately and I wanted to make program that asks for x nubmer of elements that should list contain and then ask for elements in lists and if there is x elements in list while loop breaks and print out elements and how much elements there are so thats my code:
num = input("How many numbers you want to put into a list?: ") while True: list = [input()] if len(list) == num: break def get_number_of_elements(list): count = 0 for element in list: count = count + 1 return count print(get_number_of_elements(list)) print(list)
and when i run code it still asks for elements in list and i dont know what to do.
If you want to stick with how you coded it yourself:
# make the input into an int because you want to compare it with a length in the while loop num = int(input("How many numbers you want to put into a list?: ")) # don't name your variables after a type. 'list' is already the name of a type l = [input("Enter number: ")] # while the length of the list is not equal to the num, keep prompting while len(l) != num: # add on to the list 'l'. Before you were creating a new list every loop l.append(input("Enter next number: ")) def get_number_of_elements(l): count = 0 for element in l: count = count + 1 return count print(get_number_of_elements(l)) print(l)
Instead, you can just do this:
l =  for _ in range(int(input("How many numbers you want to put into a list?: "))): l.append(int(input("Enter number: "))) print("Number of elements:", len(l)) print("Here's your list:", l)