-1

Based on the code below, I am trying to create a for loop that has a variable in it but the variable name changes based on counter number. What should I do? I want the final product of this for loop to be 3 variables X1 = user input, X2 = user input, X3 = user input (without needing to define an Array).

for i in range(3):
   X[I want i counter to come after this X] = int(input(f"How many apple in basket number {i + 1}? "))
  • 2
    (1) Decide which Python version you want to use and remove one tag. (2) Why don't you want to use a list? – Michael Butscher Dec 04 '21 at 05:18
  • Don't do that. Use a list. – DYZ Dec 04 '21 at 06:11
  • Thank you for your response. I am fairly new to programming and I feel like object oriented programming should not have lists in them. I might be wrong but that's the main reason I dont want to use list. Is my assumption wrong? – Adel Badiee Dec 04 '21 at 20:18
  • 1
    Lists are objects, too: "_Here are all of the methods of list objects..._" ([reference](https://docs.python.org/3/tutorial/datastructures.html)). Is there a specific source/citation behind your assumption? – andrewJames Dec 04 '21 at 20:26
  • 1
    Thank you! no just online research! if that's the case, I am actually going to use lists as dealing with them is much easier for me. – Adel Badiee Dec 04 '21 at 21:43

1 Answers1

-2

Use the exec() method to create a dynamic variable name.

for i in range(3):
    exec(f'X{i+1} = int(input(f"How many apple in basket number {i + 1}? "))')

print(X1, X2, X3)

I hope you are expecting values are stored in dynamic variables X1, X2, X3 will solve your problem.