-3

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.

Adanos
  • 3
  • 2
  • You are creating a new list every iteration. You need to initialize the list (and use another name, not `list`) before the loop – DeepSpace Apr 01 '21 at 22:25
  • Your `get_number_of_elements` function is exactly the same as the built-in `len` function. – Tim Roberts Apr 01 '21 at 22:27
  • See also [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers). `len()` returns a number, but `input()` returns a string, so the two can never be `==` – G. Anderson Apr 01 '21 at 22:28
  • "*I wanted to make program that asks for x nubmer of elements*" `list = [input()]` only reads *one* input. You'll probably want a for loop to read multiple input. – TrebledJ Apr 01 '21 at 22:32
  • so anyone has idea what can i change, i # the get_number_of_elements bcs as somebody said its unneeded and made a list outside loop but still not working, and how can i make if function – Adanos Apr 01 '21 at 22:57

1 Answers1

0

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)
ObjectJosh
  • 601
  • 3
  • 14