0

Here is what I have:

names1 = ['bob', 'jack', 'adam', 'dom' ]


num = int(input('Please select a number? ')) # select number 1

for name in names + num: # This is where my problem is
    print (s)

I want the names + num part to refer to the names1 list. How would you do that?

Any help would be much appreciated!

4
  • 3
    "How would you do that?" Answer: We would not do that. AFK now, but I'm sure someone will explain it in short time. Commented Jun 3, 2015 at 14:01
  • 2
    XY Problem There is a better way to do this! Commented Jun 3, 2015 at 14:02
  • This question is nonsense without a second list. The comment #select number 1 is... ...what you are hoping? Commented Jun 3, 2015 at 14:37
  • This was marked as duplicate of an existing question. However, it should be noted that what you're asking how to do is not a good way to solve your problem, and some of the answers already given suggest some better ways to think about it using the right data structures. Happy hacking! Commented Jun 3, 2015 at 14:38

4 Answers 4

3

There are two options, either you can use, nested list structure or a dictionary.

Nested list:

parent_list = [['bob', 'jack', 'adam', 'dom'], ["alpha", "beta", "gamma"], ["India", "USA"]]
num = int(input('Please select a number? '))
#Checking if the value entered can be accessed or not.
if num<3:
    for name in parent_list[num]:
        print name
else:
    print "Please enter a number between 0-2"

Dictionaries:

parent_dict = {0:['bob', 'jack', 'adam', 'dom'], 1:["alpha", "beta", "gamma"], 2:["India", "USA"]}
num = int(input('Please select a number? '))

if num<3:
    for name in parent_dict[num]:
        print name
else:
    print "Please enter a number between 0-2"

If you already have variables created in your script then you may choose to create a dictionary or nested list of variables:

names1 = ['bob', 'jack', 'adam', 'dom' ]
names2 = ["alpha", "beta", "gamma"]
names3 = ["India", "USA"]

#For nested list part
parent_list = [names1, names2, names3]

#For dictionary part
parent_dict = {0:names1, 1:names2, 2:nmaes3}
Sign up to request clarification or add additional context in comments.

Comments

1

The correct way to do this is to use either a list or dict data structure to store a set of choices, then write a simple function that prompts the user for input and validates it against "valid choices".

Example:

from __future__ import print_function

try:
    input = raw_input
except NameError:
    input = raw_input  # Python 2/3 compatibility

names = ["bob", "jack", "adam", "dom"]

def prompt(prompt, *valid):
    try:
        s = input(prompt).strip()
        while s not in valid:
            s = input(prompt).strip()
        return s
    except (KeyboardInterrupt, EOFError):
        return ""

choices = list(enumerate(names))
print("Choices are: {0}".format(", ".join("{0}:{1}".format(i, name) for i, name in choices)))

try:
    s = prompt("Your selection? ", *(str(i) for i, _ in choices))
    i = int(s)
except ValueError:
    print("Invalid input: {0}".format(s))
else:
    print("Thanks! You selected {0}".format(choices[i][1]))

Demo:

$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? 0
Thanks! You selected bob

$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? foo
Your selection? 1
Thanks! You selected jack

This also correctly handles the scenario of invalid inputs and int() throwing a ValueError as well as silencing ^D (EOFError) and ^C (KeyboardInterrupt) exceptions.

Note: That you could do for name in eval("names{0:d}".format(num)): however DO NOT do this as it's considered evil and quite dangerous to arbitrarily evaluate input using eval(). SeE: Is using eval() in Python bad pracice?

Comments

0
names1 = ['bob', 'jack', 'adam', 'dom' ]

num = int(input('Please select a number? ')) # select number 1
name_array = "names" + str(num)
for name in name_array: # This is where my problem is
    print(name)

Here we have just concatenated the name_array value. Hope it works for you too.

Comments

-2

Use This Source

names1 = ['bob', 'jack', 'adam', 'dom' ]


num = int(input('Please select a number? ')) # select number 1
for counter in range (num,4):
   print(names1[counter]);

1 Comment

This doesn't answer the question asked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.