简体   繁体   中英

Loop within a print statement

import sys
outfile = open( r'/Users/x/Desktop/myDoc.txt', 'w' )
    i = 0
    lis = []
    n = int(raw_input("How many interviews are there? "))
    while n:
       i += 1
       istart = raw_input("Interview Start Time: ")
       iend= raw_input("Interview End Time: ")
       ipeople= raw_input("What are the interviewer names: ")
       itype= raw_input("What is the interview type: ")
       lis.append((istart, iend, ipeople, itype))
       n-=1
    a = "<html><head></head><body><TABLE border=1><TR> </TR> <TR>\
        <TH>Start</TH>\
        <th>End</th>\
        <th>People</th>\
        <TH>Interview Type</TH></TR><TR ALIGN=CENTER></TR> \
        <td>fff</td>dd<td>dddd</td><td>ddd</td><td>ddddd</td></TABLE></body></html>"

    outfile.write(a)
outfile.close()

So basically this print statement is writing to a file on my computer but I am running into a problem of including another loop within this print statement since if the user says there are 5 interviews I need 5 rows where each row is one tuple within the list and each column is each item within that tuple (and if the user says 6 interviews I need 6 rows and so on). Is there a way to do this?

Does this solve your problem? The loop only has to create the rows, you should not put start and end of the document inside the loop.

import sys
outfile = open( r'/Users/x/Desktop/myDoc.txt', 'w' )
i = 0
lis = []
n = int(raw_input("How many interviews are there? "))
table = "<html><head></head><body><TABLE border=1><TR>\
    <TH>Start</TH>\
    <th>End</th>\
    <th>People</th>\
    <TH>Interview Type</TH></TR><TR ALIGN=CENTER></TR> \
    %s</TABLE></body></html>"

while n:
   i += 1
   istart = raw_input("Interview Start Time: ")
   iend= raw_input("Interview End Time: ")
   ipeople= raw_input("What are the interviewer names: ")
   itype= raw_input("What is the interview type: ")
   lis.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (istart, iend, ipeople, itype))
   n-=1



outfile.write(table % ''.join(lis))
outfile.close()

Instead of "while n" you could use range(n), then you don't need any counter variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM