0

I need to write a program in which user is asked: to select 1 (and only 1) team amongst 3 teams and to select 1 or several products amongst a longer product list.

My code works fine with 1 product only.

Any hint? (I found this useful post related, but not really documented on multiple selection)

Here is my program (Python 3.7)

from itertools import chain, repeat

# User select 1 team, uppercase
teams = {'OTEAM', 'ZTEAM', 'DREAMTEAM'}
prompts = chain(["Enter 1 team: "], repeat("No such team? Try again: "))
replies = map(input, prompts)
valid_response = next(filter(teams.__contains__, replies))
# Show team selected
print(f"you want to configure {valid_response}")

# User select 1 or several product, 
products = {'Aprod', 'Bprod', 'Cprod'}
prompts_prod = chain(["Enter product(s): "], repeat("No such product, try again: "))
replies_prod = map(input, prompts_prod)
valid_response_prod = next(filter(products.__contains__, replies_prod))
print(f"---Result --- \nin {valid_response} you want to configure \n{valid_response_prod}")
jm_her
  • 28
  • 1
  • 6
  • How should the multiple products be entered? One per line until e. g. an empty line is entered or all on one line separated by spaces, commas, both, something else? – Michael Butscher Dec 16 '21 at 14:12
  • That's quite an obfuscated approach for getting user input and checking it against a list.. – JeffUK Dec 16 '21 at 14:17
  • If you were to simply use a loop you could loop while the user continues to provide valid input – JeffUK Dec 16 '21 at 14:23
  • User will normally include its produt list using a space separated format. I can not really use a loop as product list may contain up to 20 different products. – jm_her Dec 16 '21 at 14:58

1 Answers1

1

If the users provide a product list in a space-separated format then change your code to accept that, split it into a set and use set operations to find the products they have entered that are valid, and those that are invalid.

products = {'Aprod', 'Bprod', 'Cprod'}

requested_products = set(input("Enter Space Separated Product List").split())
selected_products = requested_products.intersection(products)
invalid_products = requested_products-selected_products

#Do something with invalid products e.g.
print(f'Accepted products {",".join([p for p in selected_products])}')
print(f'Invalid products {",".join([p for p in invalid_products])}')

Up to you at that point whether you error, loop until there are non invalid, etc.
JeffUK
  • 4,107
  • 2
  • 20
  • 34