Python Forum
How can i simplify this code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can i simplify this code
#1
shoplist = [" blueberries", " rasberries"," apples", " soda", " diet coke", " coffee beans"]
indicator = int(input(" Which of the shopping list do you want to know?"))

if indicator == 0:
	print(" blueberries")
elif indicator == 1:
	print(" rasberries")
elif indicator == 2:
	print(" apples")
elif indicator == 3:
	print(" soda")
elif indicator == 4:
	print(" diet coke")
elif indicator == 5:
	print(" coffee beans")
elif indicator >= 5:
	print(" you are out of range")
# If the list is longer it will be time consuming to write all of this elif statements is there a ways to make the outcome automatic.
Reply
#2
Why don't you use the value you read as an index into the list? That's how lists work, after all...
Reply
#3
# you can make the process automatic by just doing the following
print(shoplist[indicator])
# this will make the process automatic
Reply
#4
Obviously you still need to take care of the case where the index is out of range.
Reply
#5
It there is existing shoplist then one could do:

>>> shoplist = [" blueberries", " rasberries"," apples", " soda", " diet coke", " coffee beans"]
>>> item_indexes = dict(enumerate(shoplist, start=1))
>>> item_indexes
{1: ' blueberries', 2: ' rasberries', 3: ' apples', 4: ' soda', 5: ' diet coke', 6: ' coffee beans'}
# ask for input, convert into integer, assign name index
>>> if index in item_indexes:
...     print(item_indexes[index])
... else:
...     print('No item with such index')
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,118 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
Thumbs Up [SOLVED] Simplify condition test in if block? Winfried 2 1,710 Aug-25-2021, 09:42 PM
Last Post: Winfried
  How to simplify square finding program? meknowsnothing 3 2,894 Jun-11-2019, 08:20 PM
Last Post: meknowsnothing
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,041 Jun-11-2019, 01:19 AM
Last Post: nholtz
  Dijkstra code - trying to simplify it grandpapa10 1 2,179 Jan-23-2019, 12:43 PM
Last Post: Larz60+
  simplify my excel work on python CodeAyoub 1 2,925 Oct-08-2017, 12:09 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020