Reputation: 111
In my Python script I have a menu which accepts user input, then based on that input will print some lines with information. It looks kind of like this:
while True:
# Print the menu
choice = raw_input('Pick an option: ')
if choice == 'item_1':
# Display item_1's contents
elif choice == 'item_2':
# Display item_2's contents
# etc...
The information displayed by each item_
is slightly larger than I want it to be, so I want to split each of them into multiple pages.
To access those different pages I want it to be based on the user input, but rather than having an entirely different input for each page, I want the user to be able to write the page number next to the original input (with a space in between). So if the user inputs item_1
or item_1 1
they get the first page of item_1
, and if they input item_2 2
they get the second page of item_2
, and so on.
How can I break the user input into parts to do the aforementioned?
===========================================================================
EDIT
I was a little bit misleading about each item
and what it does. Earlier in the script I have this:
def item_1():
# Print line 1
# Sleep
# Print line 2
# Sleep
# Print line 3
def item_2():
# Print line 1
# Sleep
# Print line 2
# Sleep
# Print line 3
What I really want to do is define more functions, one for each page, and then call them when the user inputs a number after the `item' (sort of like parsing arguments). Like this:
Input item_1
or item_1 1
>> Output item_1()
Input item_1 2
>> Output item_1_p2()
Input item_3 4
>> Output item_3_p4()
And, as seen in the first input example, I'd like the first page of a given input to be displayed if no pages are mentioned in the input.
Upvotes: 0
Views: 1067
Reputation: 49320
Use a dictionary that holds a list
of strings for each item:
book = {'item_1':['page 1', 'page 2', 'page 3'], 'item_2':['page 1', 'page 2', 'page 3']}
while True:
choice = raw_input('Pick an option: ').split()
if not choice:
break
if len(choice) == 1:
for page in book[choice[0]]:
print page
else:
print book[choice[0]][int(choice[1])-1]
First it splits the input on whitespace. If the user had simply hit Enter with no characters, it'll stop. Otherwise, it'll do the following:
'item_x'
, so print the whole entry'item_x'
and a page number, so print the proper pageUpvotes: 2