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}")
4
  • 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? Commented Dec 16, 2021 at 14:12
  • That's quite an obfuscated approach for getting user input and checking it against a list.. Commented Dec 16, 2021 at 14:17
  • If you were to simply use a loop you could loop while the user continues to provide valid input Commented Dec 16, 2021 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. Commented Dec 16, 2021 at 14:58

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, this is exactly what I need. Thank you for the example.
@jm_her, make sure to accept this answer if it met your needs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.