2

Sorry the title is a bit vague, I'm not entirely sure what it is I'm asking for...

Basically, I'm asking for user input which can be from one to five entries (e.g. 2 entries could be as simple as 1 2, or five entries could be This Is My 5 List).

I'd like to assign each entry to a variable; obviously I don't need to 5 variables if only 2 entries are input.

I'd then like to be able to call the variables individually IF they have been entered.

So far I've been playing around with;

    if len(UserInput) >1 and len(UserInput) <= 5:
    count = 0
    for i in UserInput:
        count = count + 1
        print("Input"+str(count))

This will output what the user enters but I'm not sure how to dynamically assign the amount of entries in to a dynamic amount of varaibles.

Darren
  • 31
  • 5
  • 4
    [Don't.](https://stackoverflow.com/q/1373164/1639625) Instead, store the input in a list or dict, not in 2-5 different variables. Or _do_ use different variables, but leave some of them as `None` (there's really no problem with that either if the max number of vars is small and they all have a different purpose). – tobias_k Sep 08 '21 at 08:11

2 Answers2

0

You can take the input and split the values in it to store it in a list. Then all you have to do is traverse through the list to access your value.

inp = list(input().split(" "))
for i in inp:
    print(i)

vnk
  • 1,060
  • 1
  • 6
  • 18
0

I'd just a list as mentioned in the comments, i.e. inputs = input('> ').split().

But you could do this:

>>> x1, x2, x3, x4, x5, *_ = input('> ').split() + [None]*5
> a b # user supplies two values
>>> print(x1, x2, x3, x4, x5)
a b None None None
>>> x1, x2, x3, x4, x5, *_ = input('> ').split() + [None]*5
> # empty user input 
>>> print(x1, x2, x3, x4, x5)
None None None None None
>>> x1, x2, x3, x4, x5, *_ = input('> ').split() + [None]*5
> a b c d e # user supplies 5 values
>>> print(x1, x2, x3, x4, x5)
a b c d e
timgeb
  • 76,762
  • 20
  • 123
  • 145