Take the 2-minute tour ×

There are files named: page1.txt, page2.txt, page3.txt, page4.txt. These are all the pages. User input is asked and if user press 1, page number 1 is display. I am able to display the result as user presses the page numbers as:

def read(argu):
    argu = open(argu)
    y = [x for x in argu]
    print y

inp = raw_input('Say: ')

if inp=='1':

if inp=='2':

if inp=='3':

I am stuck in Next and Previous. If user is in page2 and if he presses next I need to display page3 and so on. How do I do that? Thanks in advance.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

In order to move from one page to another, you need to use a variable to show what page the user is currently reading. Previous and Next would then update the page number and display the appropriate page:

file = ['page1.txt', 'page2.txt', 'page3.txt', 'page4.txt']
pagecount = len(file)
page = 1                    # initialize to a default page

if inp == '1':
    page = 1
    read(file[page-1])      # pages are 1-4, subscripts are 0-3

# ... pages 2-4 go here 

elif inp == '+':              # whatever key you use for Next
    page = min(page+1, pagecount)    # don't go beyond last page

elif inp == '-':              # switch statements use "if .. elif .. elif .. else"
    page = max(page-1, 1)

After you get that version working, you can generalize it to allow an arbitrary number of pages by constructing the file name from the page number instead of storing filenames in a list. And you only need one "read" for your input loop -- since every key reads a page you can factor that out of each individual key.

share|improve this answer
Thank you so much @Dave, worked well! Appreciate it!! –  Binita Maharjan Sep 18 '12 at 12:04
Dave, the contents in the page are returned as a list..How can I convert the generated list into a string? –  Binita Maharjan Sep 18 '12 at 12:15
If x is a list of strings, then ''.join(x) will return a single string concatenating the contents of the list. –  Dave Sep 18 '12 at 12:27
add comment

Your Answer


