1

I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this

for i in range(0,5):
    number(i) = int(input("what is the number"))

I realise that this code docent actually work but that is kind of what I want to do.

martineau
  • 112,593
  • 23
  • 157
  • 280
N G
  • 23
  • 2
  • 2
    Try a dictionary, use the keys for the variable names, and the values for the values. – Yuval.R Nov 22 '20 at 16:06
  • You can also use a list. i.e. `numbers = []`, and `number.append(int(input("what is the number")))` — which might be more appropriate in this case. – martineau Nov 22 '20 at 17:18

4 Answers4

1

What your code is, cannot be done per se but it can be done using lists like this:

number_list = []

for i in range(5);
    number = int(input("What is the number?"))
    number_list.append(number)

// Now you can access the list using indexes

for j in len(number_list):
    print(number_list[j])
1

Code:

number = []
for i in range(5):
    number.append(int(input("what is the number ")))
print(number)
Aaj Kaal
  • 1,080
  • 1
  • 7
  • 8
1

The easiest I could think at the top of my had way would just to create a list and append the items:

numbers = []
for i in range(0,5):
    numbers += [int(input("what is the number"))]

user107852
  • 44
  • 2
0

If you want to save also variable names you can use python dictionaries like this:

number = {}
for i in range(0,5):
  number[f'number{i}'] = int(input("what is the number "))
print(number)

output:

{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
Patrik
  • 501
  • 1
  • 6
  • 22