[Tutor] Python Variables Changing in Other Functions

Rachel-Mikel ArceJaeger arcejaeger at gmail.com
Wed May 25 23:04:20 CEST 2011


I'm not quite certain I understand. When you say sections, do you mean different worksheets? If so, you should finish writing on one worksheet first, and then move to another. If you're talking about writing to row 5, and then jumping to row 50, enumerate lets you do that by allowing you to determine where to start indexing.

btw, my improved code is below. Maybe it will offer some clarification?
Rachel

---------------

import xlwt as excel
import random
import copy

# Note: When python takes in arguments to a function, it passes in the entire 
# object, so any modifications made to that object will be retained after the 
# function terminates without you having to explicity return the object. You  
# only have to return an object if it wasn't passed in as an argument to the 
# function and you need to use in in another function.



def getTitleList():
    """ Makes a list of all the lines in a file """
    
    filename = raw_input("Name and Extension of File: ")
    
    myFile = open( filename )

    dictOfTitles = {}
    for title in myFile:    
        if title not in ["\n",""]:
            dictOfTitles[title] = []
    
    return dictOfTitles


def rank( randomizedTitles, dictOfTitles ):
    """ Gets a user-input ranking (0-10) for each line of text. 
        Returns those rankings 
    """
    
    for title in randomizedTitles:
        
        while True:
            
            rank = raw_input(title + " ")
            
            if not rank.isdigit():
                continue
            elif ( int(rank) > 10 ):
                continue
                
            dictOfTitles[title].append(rank)
            break


def rankRandom( dictOfTitles ):
    """ Takes a list of titles, puts them in random order, gets ranks, and then
        returns the ranks to their original order (so that the rankings always  
        match the correct titles).
    """
    
    randomizedTitles = dictOfTitles.keys()
    random.shuffle(randomizedTitles)    # Shuffle works in-place.
    rank(randomizedTitles, dictOfTitles)


def writeToExcel(dictOfTitles):
    """ Writes the titles and ranks to Excel """
    
    # Open new workbook
    mydoc = excel.Workbook()
    
    # Add a worksheet
    mysheet = mydoc.add_sheet("Ranks")
    
    # Make header style 
    header_font = excel.Font() # Make a font object
    header_font.bold = True
    header_font.underline = True
    header_style = excel.XFStyle(); header_style.font = header_font
    
    # Write headers and ranks to Excel. Indexing is 0-based
    # write( row, col, data, style )
    for col, title in enumerate(dictOfTitles):
        mysheet.write(0, col, title, header_style)
        for row, rank in enumerate( dictOfTitles[title], 1 ):
            mysheet.write(row, col, rank)
    
    # Save file. You don't have to close it like you do with a file object
    mydoc.save("r.xls")


def main():
    
    dictOfTitles = getTitleList()
    
    done = ""    
    while done.lower() != "y":
        rankRandom( dictOfTitles )
        done = raw_input("Done? (y/[n]): ")

    writeToExcel(dictOfTitles)
 

if __name__ == "__main__" : main()





On May 25, 2011, at 1:49 PM, Prasad, Ramit wrote:

> >> Having lots of += hanging around is a perfect example of a code smell (i.e. something in this code stinks, and we should change >>it). Part of being a good programmer is learning to recognize those bad smells and getting rid of them. Turns out, Python has a lot >>of nice built-in functions for the elimination of code smells.  In this case, it's the enumerate function:
>  
> What happens if you are trying to write to an excel document with several different sections and need to keep track of things like last written row / current row? I could keep track of enumerations and then save them to a local variable and then append it but that seems about as funky. Is there a better way?
>  
> # pseudocode-ish
> # Is this better?
> blah = enumerate(raw_data)
> For enumerate_value, data in blah:
>      sheet.write (base_row + enumerate_value , column, data)
> base_row = blah[-1][0]
>  
> Ramit
>  
>  
>  
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
> This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer tohttp://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities.
> 

R.M. ArceJaeger
Author/Publisher, Platypus Press

Contact: arcejaeger at gmail.com
Website: http://rmarcejaeger.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110525/f82f56f8/attachment-0001.html>


More information about the Tutor mailing list