Very basic Python question (strings, formats and escapes)

后端 未结 10 2081
别那么骄傲
别那么骄傲 2021-02-06 10:59

I am starting to learn Python with an online guide, and I just did an exercise that required me to write this script:

from sys import argv

script, filename = ar         


        
10条回答
  •  独厮守ぢ
    2021-02-06 12:02

    bad

    Original code is repetitive, and copy-pasting code is dangerous ( Why is "copy and paste" of code dangerous? ):

    print "Now I'm going to ask you for three lines."
    
    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")
    
    print "I'm going to write these to the file."
    
    target.write(line1)
    target.write("\n")
    target.write(line2)
    target.write("\n")
    target.write(line3)
    target.write("\n")
    

    good

    Much shorter, can change it to 4+ lines just by changing one character:

    print "Now I'm going to ask you for three lines."
    
    lines = [raw_input("line {i}: ".format(i=i)) for i in range(1,4)]
    
    print "I'm going to write these to the file."
    
    for line in lines:
        target.write(line+'\n')
    

提交回复
热议问题