美文网首页
笨办法学python16-26

笨办法学python16-26

作者: 靜美花開 | 来源:发表于2020-03-14 21:41 被阅读0次

    exercise 16 读写文件

    看起来代码就很长的样子
    作业代码:

    from sys import argv
    
    script, filename = argv
    
    print ("We're going to erase %r." %filename)   
    print ("If you don't want that, hit CTRL-C(^C).")  #CTRL-C直接中断进程
    print ("If you do want that, hit RETURN.")
    
    input("?")
    
    print ("Opening the file...")
    target = open(filename, 'w')
    
    print ("Truncating the file. Goodbye!")
    target.truncate()
    
    print ("Now I'm going to ask you for three lines.")
    
    line1 = input ("line 1: ")
    line2 = input ("line 2: ")
    line3 = 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")
    
    print ("And finally, we close it.")
    target.close()
    

    运行结果:

    PS C:\Users\Brenda\Desktop\Python学习路径资料\exercise>  python 1.py ex15_sample.txt
    We're going to erase 'ex15_sample.txt'.
    If you don't want that, hit CTRL-C(^C).
    If you do want that, hit RETURN.
    ?RETURN
    Opening the file...
    Truncating the file. Goodbye!
    Now I'm going to ask you for three lines.
    line 1: I love winner.
    line 2: They have different type.
    line 3: Forever.
    I'm going to write these to the file.
    And finally, we close it.
    

    同时,打开文件,确实实现了txt文件内容的更新
    疑问:1.print ("If you don't want that, hit CTRL-C(^C)."):无论在input行输入什么,都是往下执行的。(CTRL-C应该是能够直接中断进程的)

    加分练习:
    2.写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。

    加入这两行代码即可。

    txt = open (filename,'r')
    print (txt.read())
    

    加分练习:3.文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。

    from sys import argv
    
    script, filename = argv
    
    print ("We're going to erase %r." %filename)   
    print ("If you don't want that, hit CTRL-C(^C).")  
    print ("If you do want that, hit RE.")
    
    input("?")
    
    print ("Opening the file...")
    target = open(filename, 'w')   #w是特殊字符串,表示文件的访问模式,
    #w,写入write模式;r读取read模式,a追加append(只有特别指定才会进入写入模式,否则位阅读模式
    
    print ("Truncating the file. Goodbye!")
    target.truncate()
    
    print ("Now I'm going to ask you for three lines.")
    
    line1 = input ("line 1: ")
    line2 = input ("line 2: ")
    line3 = input ("line 3: ")
    
    print ("I'm going to write these to the file.")
    
    target.write ("%s\n%s\n%s"  %( line1 , line2 , line3))   #这一行进行了更改,加入了格式化字符串和转义字符。
    
    print ("And finally, we close it.")
    target.close()
    
    txt = open (filename,'r')
    print (txt.read())    #在关闭了文档之后,再次打开读取出文档内容,检验实验效果
    

    exercise 17 更多文件操作

    作业代码:

    from sys import argv
    from os.path import exists
    #exists 将文件名字符串作为参数,如果存在返回TRUE,否则返回FALSE
    
    script, from_file, to_file = argv
    
    print ("Copying from %s to %s" % (from_file, to_file))
    
    #we could do these two on one line too, how?
    in_file = open (from_file)
    indata = in_file.read()
    
    print ("The input file is %d bytes long" % len (indata))   #len 以数字的形式返回传递字符串的长度
    
    print ("Does the output file exist? %r"  % exists (to_file))    
    print ("Ready, hit RETURN to continue, CTRL-C to abort.")
    input()
    
    out_file = open (to_file, 'w')
    out_file.write (indata)
    
    print ("Alright, all done.")
    
    out_file.close ()
    in_file.close()
    

    运行结果

    Copying from ex15_sample.txt to 1.txt
    The input file is 8 bytes long
    Does the output file exist? True
    Ready, hit RETURN to continue, CTRL-C to abort.
    
    Alright, all done.
    

    we could do these two on one line too, how?
    indata = open(from_file).read()

    exercise 18 命名、变量、代码、函数

    函数 function!

    1. 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
    2. 它们可以接受参数,就跟你的脚本接受 argv 一样。
    3. 通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。

    自定义函数通过def进行定义。python中还含有内置函数。
    代码:

    #用def新建函数 define
    #like argv
    def print_two (*args):    #def + 定义的函数名称(参数):
        arg1, arg2 = args    #4个空格缩进,将参数解包
        print ("arg1: %r, arg2: %r" % (arg1, arg2))  #解包后每个参数打印出来
        
    #OK, that *args is actually pointless, we can just do this 
    def print_two_again (arg1, arg2):    #跳过整个参数解包的过程,直接使用变量名
        print ("arg1: %r, arg2: %r" % (arg1, arg2))
        
    # this just takes one argument 接受单个参数
    def print_one (arg1):    
        print ("arg1: %r" %arg1)
        
    # this one takes no arguments  函数可以不接受任何参数
    def print_none ():
        print ("I got nothin'.")
        
    print_two ("Zed", "Shaw")
    print_two_again ("Zed", "Shaw")
    print_one ("First!")
    print_none ()
    

    运行结果:

    arg1: 'Zed', arg2: 'Shaw'
    arg1: 'Zed', arg2: 'Shaw'
    arg1: 'First!'
    I got nothin'.
    

    print_two ("Zed", "Shaw");print_two_again ("Zed", "Shaw");print_one ("First!");print_none ()
    函数变量的定义必须放在最后,而不能放在最前方。

    exercise 19 函数和变量

    #函数里边的变量和脚本里边的变量之间是没有连接的
    def cheese_and_crackers (cheese_count, boxes_of_crackers):
        print ("You have %d cheese!" % cheese_count)
        print ("You have %d boxes of crackers!" % boxes_of_crackers)
        print ("Man that's enough for a party!")
        print ("Get a blanket.\n")
    
    #以上设定函数,以下开始运行
    print ("We can just give the function numbers directly:")
    cheese_and_crackers (20,30)    #cheese_and_crackers为定义的函数 
    
    print ("OR, we can use variables from our script:")
    amount_of_cheese = 10
    amount_of_crackers = 50
    cheese_and_crackers (amount_of_cheese, amount_of_crackers)
    
    print ("We can even do math inside too:")
    cheese_and_crackers (10+20, 5+6)
    
    print ("And we can combine the two, variables and math:")
    cheese_and_crackers (amount_of_cheese +100, amount_of_crackers +1000)
    

    运行结果

    We can just give the function numbers directly:
    You have 20 cheese!
    You have 30 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    OR, we can use variables from our script:
    You have 10 cheese!
    You have 50 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    We can even do math inside too:
    You have 30 cheese!
    You have 11 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    And we can combine the two, variables and math:
    You have 110 cheese!
    You have 1050 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    

    exercise 20 函数和文件

    代码:

    from sys import argv
    script, input_file = argv  #argv解包,将所有参数以此赋予左边变量名
    
    def print_all(f) :   #def定义函数,参数为f?
        print (f.read ())  #在f上调用read函数,并打印
        
    def rewind(f):   #定义函数rewind,参数为f
        f.seek(0)   #f上调用seek函数,移动文件读取指针到指定位置,转到文件的0byte。
        
    def print_a_line (line_count,f):   #定义print_a_line,参数为line_count和f
        print (line_count, f.readline())  #在f上调用readline,读取文本文件中的某一行
        
    current_file = open(input_file)   #open()打开文件
    print ("First let's print the whole file:\n")
    
    print_all (current_file)   #调用函数print_all
    
    print ("Now let's rewind, kind of like a tape.")
    
    rewind(current_file)
    
    print ("Let's print three lines:")
    
    current_line = 1
    print_a_line (current_line , current_file)
    
    current_line = current_line +1
    print_a_line(current_line , current_file)
    
    current_line = current_line +1
    print_a_line(current_line , current_file)
    

    运行结果:

    First let's print the whole file:
    
    fe
    we
    dd
    Now let's rewind, kind of like a tape.
    Let's print three lines:
    1 fe
    
    2 we
    
    3 dd
    

    exercise 21 函数可以返回东西

    代码:

    def add (a,b):
        print ("ADDING %d +%d" % (a,b))
        return a+b
    #调用了参数a,b,打印函数功能,做回传动作,将a,b的值返回return
    def subtract (a,b):
        print ("SUBTRACTING %d -%d" % (a,b))
        return a-b 
        
    def multiply (a,b):
        print ("MULTIPLYING %d *%d" % (a,b))
        return a*b 
    
    def divide (a,b):
        print ("DIVIDING %d /%d" % (a,b))
        return a/b 
        
    print ("Let's do some math with just functions!")
    
    age = add(30,5)
    height = subtract (78,4)
    weight = multiply (90,2)
    iq = divide (100,2)
    
    print ("Age:%d, Height:%d, Weight:%d, IQ:%d" % (age, height, weight, iq))
    
    print ("Here is a puzzle.")
    what = add(age, subtract (height, multiply(weight,divide (iq,2))))
    
    print ("That becomes : %d Can you do it by hand?" % what)  #加分习题2修改代码
    

    运行结果:

    Let's do some math with just functions!
    ADDING 30 +5
    SUBTRACTING 78 -4
    MULTIPLYING 90 *2
    DIVIDING 100 /2
    Age:35, Height:74, Weight:180, IQ:50
    Here is a puzzle.
    DIVIDING 50 /2
    MULTIPLYING 180 *25
    SUBTRACTING 74 -4500
    ADDING 35 +-4426
    That becomes : -4391Can you do it by hand?
    

    exercise 24 练习

    代码:

    print ("Let's practice everything.")
    print (' You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
    #You'd need to know 'bout escapes with \ that do
    #newlines and   tabs.  
    #转义符\
    poem = """
    \tThe lovely world
    with logic so firmly planted 
    cannot discern \n the needs of love 
    nor comprehend passion from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """
    
    print ("--------------")
    print (poem)
    print ("--------------")
    
    five = 10-2+3-6
    print ("This should be five: %s" % five)
    
    def secret_formula (started):
        jelly_beans = started *500
        jars = jelly_beans /1000
        crates =jars /100
        return jelly_beans, jars, crates
        
    start_point = 10000
    beans, jars, crates = secret_formula(start_point)   #创建了一个新变量,用来存放函数的返回值
    
    print ("With a starting point of : %d" %start_point)
    print ("we'd have %d beans, %d jars, and %d crates." %(beans, jars, crates))
    
    start_point = start_point /10
    print ("We can also do that this way:")
    print ("With a starting point of : %d" %start_point)
    print ("we'd have %d beans, %d jars, and %d crates." %secret_formula(start_point))
    

    结果:

    Let's practice everything.
     You'd need to know 'bout escapes with \ that do
     newlines and    tabs.
    --------------
    
            The lovely world
    with logic so firmly planted
    cannot discern
     the needs of love
    nor comprehend passion from intuition
    and requires an explanation
    
                    where there is none.
    
    --------------
    This should be five: 5
    With a starting point of : 10000
    we'd have 5000000 beans, 5000 jars, and 50 crates.
    We can also do that this way:
    With a starting point of : 1000
    we'd have 500000 beans, 500 jars, and 5 crates.
    

    exercise 25 练习

    def break_words (stuff):
        """This function will break up words for us."""
        words = stuff.split (' ')  #拆分 split '有空格'
        return words 
        
    def sort_words (words):
        """sorts the words."""
        return sorted (words)    #按照首字母顺序进行排序
        
    def print_first_word (words):
        """Prints the first word after popping it off."""
        word = words.pop(0)     #words.pop定位顺序,第0个
        print  (word)
       
    def print_last_word (words):
        """Prints the last word after popping it off."""
        word = words.pop(-1)    #words.pop定位顺序,最后一个
        print (word)
        
    def sort_sentence(sentence):
        """Takes in a full sentence and returns the sorted words."""
        words = break_words(sentence)
        return sort_words
        
    def print_first_and_last(sentence):
        """Prints the first and last words of the sentence."""
        words = break_words (sentence)
        print_first_word(words)
        print_last_word(words)
    
    

    exercise 26 改错

    import  ex2   #去掉#
    def break_words(stuff):
        """This function will break up words for us."""
        words = stuff.split(' ')
        return words
    
    def sort_words(words):
        """Sorts the words."""
        return sorted(words)
    
    def print_first_word(words):   # 加上":"
        """Prints the first word after popping it off."""
        word = words.pop(0)  #pop(0)
        print (word)
    
    def print_last_word(words):
        """Prints the last word after popping it off."""
        word = words.pop(-1)   #加上“)”
        print (word)
    
    def sort_sentence(sentence):
        """Takes in a full sentence and returns the sorted words."""
        words = break_words(sentence)
        return sort_words(words)
    
    def print_first_and_last(sentence):
        """Prints the first and last words of the sentence."""
        words = break_words(sentence)
        print_first_word(words)
        print_last_word(words)
    
    def print_first_and_last_sorted(sentence):
        """Sorts the words then prints the first and last one."""
        words = sort_sentence(sentence)
        print_first_word(words)
        print_last_word(words)
    
    print ("Let's practice everything.")
    print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
    #在python3中,print("")
    poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explantion
    \n\t\twhere there is none.
    """
    
    print ("--------------")
    print (poem)
    print ("--------------")
    
    five = 10 - 2 + 3 - 5
    print ("This should be five: %s" % five)
    
    def secret_formula(started):
        jelly_beans = started * 500
        jars = jelly_beans / 1000  #除法是“/”
        crates = jars / 100
        return jelly_beans, jars, crates
    
    start_point = 10000
    beans, jars, crates = secret_formula(start_point)  # jelly_beans =  start_point 
    
    print ("With a starting point of: %d" % start_point)
    print ("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))
    
    start_point = start_point / 10
    
    print ("We can also do that this way:")
    print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))   #  start_point拼写 括号
    
    sentence = "All god\tthings come to those who weight."  #good things
    
    words = ex2.break_words(sentence)
    sorted_words = ex2.sort_words(words)
    
    print_first_word(words)
    print_last_word(words)
    print_first_word(sorted_words)   # 去掉print前面的 .
    print_last_word(sorted_words)
    sorted_words = ex2.sort_sentence(sentence)
    print (sorted_words)   # print
    
    print_first_and_last(sentence)  # print print_first_and_last 拼写
    print_first_and_last_sorted(sentence)   #indent print first_a_last_sorted(sentence) 空格
    
    Let's practice everything.
    You'd need to know 'bout escapes with \ that do
     newlines and    tabs.
    --------------
    
            The lovely world
    with logic so firmly planted
    cannot discern
     the needs of love
    nor comprehend passion from intuition
    and requires an explantion
    
                    where there is none.
    
    --------------
    This should be five: 6
    With a starting point of: 10000
    We'd have 5000000 jeans, 5000 jars, and 50 crates.
    We can also do that this way:
    We'd have 500000 beans, 500 jars, and 5 crabapples.
    All
    weight.
    All
    who
    ['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']
    All
    weight.
    All
    who
    

    移除对ex2的引用也可以,把全篇的ex2相关都删去。

    相关文章

      网友评论

          本文标题:笨办法学python16-26

          本文链接:https://www.haomeiwen.com/subject/rfkmfhtx.html