Hi, I'm trying to make a program that prompts for input a certain number of times, like say the user inputs 5, it will prompt for other input five times. I get the number from the user, but how do I make a for loop that uses that variable instead of a number?

This is one of the things I tried, but it doesn't work. Any help please? Thank you!

num = raw_input("Enter a number: ")
list = []

for item in range(num):
    item = input("Enter: ")
    list.append(item)

Dani AI

Generated

Short version: the loop needs a numeric count and some input validation. As hinted and demonstrated, convert the user's “how many” answer to an integer and avoid shadowing built-ins (don't name a variable list). Below is a concise, more robust Python‑3 style pattern that keeps names clear and keeps asking until a valid count is entered.

def read_positive_int(prompt):
    while True:
        s = input(prompt)
        try:
            n = int(s)
            if n > 0:
                return n
            print("Please enter a number greater than zero.")
        except ValueError:
            print("Not a whole number — try again.")

count = read_positive_int("How many entries? ")
entries = []
for _ in range(count):
    entries.append(input("Enter value: "))

print("Collected:", entries)

Extra notes and troubleshooting:

  • If the values you collect should be numbers, convert each inside the loop with try/except and give a clear re-prompt on failure.
  • On very old systems using Python 2, replace input() with raw_input() (or better, upgrade to Python 3).
  • Don’t use names like list, str, or input for your variables — that makes the interpreter behave unexpectedly.
  • To debug, print the type of the count (for example print(type(count))) to confirm you really have an integer before using it with range.

Recommended Answers

All 2 Replies

num = int(raw_input("Enter a Number: "))
for x in range(0, num):
    raw_input()

That should provide a basis for your loop

Also, do not assign variables to built-in functions, such as 'list'. It's a bad idea to do

>>> num = raw_input("Enter a number: ")
>>> l = []
>>> for item in range(int(num)):
...     a = int(raw_input('Enter: '))
...     l.append(a)
...     
>>> l
[5, 6, 3, 4, 7]
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.