zoukankan      html  css  js  c++  java
  • 笨方法学python练习与总结

      这是一篇根据书本《笨方法学python3》而来的博客,希望自己能在每天抽一点时间来学习python,使自己能够前后端都能得到进步。脚踏实地,一步一步!

      在开始之前,希望自己的英语能够在不断地积累与代码练习中的得到提高,以及告诫自己,无论什么事,取是能力,舍是境界。

    第一个程序

    练习代码:

    print("Hello World!")
    #print("Hello Again")
    #print("I like typing this.")
    #print("This is fun.")
    #print("Yay! Printing.")
    #print("i`d much rather you 'not' .")
    #print('I "said" do not touch this.')
    

      

    练习目的:使用python的打印方法,关于print这个方法其实有很深远的说法,待补充。

    问题:由于作者希望读者能够摆脱ide的依赖,使用最原始的文本编辑器去进行python练习,所以在一开始无法运行自己编写的python程序。

    解决:我们需要在我们自己写的python文件目录下执行 python3.x xxx.py才能将我们的程序运行起来。比如 lpthw/ex1.py 在编者的mac系统下就需要cd lpthw才可执行命令,运行python文件。

    注释与#号

    练习代码:

    # A comment ,this is so you can read your program later.
    # Anything after the # is ignored by python 
    
    print("I could have code like this.") # and the comment after is ignored
    
    # You can also use a comment to "disable" or comment out code:
    #print("This won't run")
    
    print("This will run.")
    

      

    练习目的:对于注释的使用,优秀的代码都是简洁明了的,通过合理的注释能够帮助使用者更好的理解项目。

    问题:无

    tip:一个小技巧,倒着阅读代码,这样可以避免你的大脑跟着每一段代码的意思走,这样可以让你精确处理每个片段,从而更容易发现代码中的错误。这是一个很好的差错技巧。

    数学与数字运算

    练习代码:

    print("I will now count my chickens:")
    
    print("Hens",25 + 30 / 6)
    print("Roosters",100 - 25 * 3 / 4)
    
    print("Now I will count the eggs:")
    
    print(3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0)
    
    print("Is it true that 3 + 2 < 5 — 7?")
    
    print(3 + 2 < 5 - 7)
    
    print("What is 3 + 2?",3 + 2)
    print("What is 5 - 7",5 - 7)
    
    print("Oh, that's why it's False." )
    
    print("How about some more.")
    
    print("Is it greater",5 > -2)
    print("Is it greater or equal",5 >= -2)
    print("Is it less or equal?", 5 <= -2)
    

      

    练习目的:对于python中的运算符的使用,以及对于相关运算的值的理解。

    问题:类似5 > 7 这类运算的结果是什么

    解决:是布尔值,正确则为true,错误为false

    tips:1.在运算中%是一个求余数的运算符

      2.运算的优先级,PE(M&D)(A&S),括号Parentheses,指数Exponents,除Division,加Addition,减Subtraction

    变量与命名

    练习代码:

    cars = 100
    space_in_a_car = 4.0
    drivers = 30
    passengers = 90
    cars_not_driven = cars - drivers
    cars_driven = drivers
    carpool_capacity = cars_driven * space_in_a_car
    average_passengers_per_car = passengers / cars_driven
    
    print("There are",cars,"cars available.")
    print("There are only",drivers,"drivers avaliable.")
    print("There will be",cars_not_driven,"empty cars today.")
    print("We can transport",carpool_capacity,"people today.")
    print("We have",passengers,"to carpool today.")
    print("We have to put about",average_passengers_per_car,"in each car.")
    

      执行结果:

    练习目的:巩固打印,了解对于变量的命名是对程序很重要的一部分。

    问题:无

    tips:

    1.在使用运算符号时,使符号左右空格,便于代码阅读。

    2.=是赋值,==是我们日常的等于

    3.学好英语对我们的编程有巨大的作用,目前来看,比如命名。

    更多的变量与打印

    练习代码:

    my_name = 'Zed A. Shaw'
    my_age = 35 # not a lie
    my_height = 74 # inches
    my_weight = 180 # lbs
    my_eyes = 'blue'
    my_teeth = 'White'
    my_hair = 'Brown'
    
    print(f"Let's talk about {my_name}.")
    print(f"He's {my_height} inches tall.")
    print(f"He's {my_weight} pounds heavy")
    print("Actually that's not too heavy.")
    print(f"He's got {my_eyes} eyes and {my_hair} hair.")
    print(f"His teeth are usually {my_teeth} depending on the coffee.")
    
    # this line is tricky, try to get it exactly right
    total = my_age + my_height + my_weight
    print(f"If I add {my_age},{my_height},and {my_weight} I got {total}.")
    

      练习目的:对打印的理解加深,以及合理的变量名对程序很重要。

      问题:无

      tips:这里的打印可以以f....{}的形式进行插值。

    习题6-字符传与文本

    练习代码:

    type_of_people = 10  # 定义人数
    x = f"There are {type_of_people} types of people."  #定义这里有10个人,并且是插值的方式
    
    binary = "binary"  # 定义binary变量
    do_not = "don't"
    y = f"Those who know {binary} and those who {do_not}."
    
    print(x)
    print(y)
    
    print(f"I said :{x}")
    print(f"I also said '{y}'")
    
    hilarious = False
    joke_evaluation = "Isn't that joke so funny ?! {}"
    
    print(joke_evaluation.format(hilarious))
    
    w = "This is the left side of ..."
    e = "a string with a right side."
    
    print(w + e)
    

      练习目的:继续使用打印,以及forma的插值使用。

    问题:无

    tips:对于代码的调试,重中之重就是不断的print  print  print

    习题7-更多打印

    练习代码:

    print("Mary had a little lamb.")
    print("Its fleece was white as {}.".format('snow'))
    print("And everywhere that Mary went.")
    print("." * 10)  # what'd that do ?
    
    end1 = "C"
    end2 = "h"
    end3 = "e"
    end4 = "e"
    end5 = "s"
    end6 = "e"
    end7 = "B"
    end8 = "u"
    end9 = "r"
    end10 = "g"
    end11 = "e"
    end12 = "r"
    
    # watch that comma at the end. try removing it to see what happens
    print(end1+end2+end3+end4+end5+end6,end=' ')  #打印cheese 并且加空格end=' ' 赋值并且打印
    print(end7+end8+end9+end10+end11+end12)
    

      练习目的:继续理解打印的规则

    问题:无

    tips:打印的时候可以赋值再打印,就像倒数第二行代码显示的一样。

    习题8-打印,打印

    练习代码:

    formatter = "{} {} {} {}"
    
    print(formatter.format(1,2,3,4))
    print(formatter.format("one","two","three","four"))
    print(formatter.format(True,False,True,False))
    print(formatter.format(formatter,formatter,formatter,formatter))
    print(formatter.format(
        "Try your",
        "Own text here",
        "Maybe a poem",
        "Or a song about fear"
    ))
    

      练习目的:学习format的使用

    问题:无

    tips:这里使用了函数,其实不只是我们自己定义的是函数,function()就是函数,带括号就是一种调用的方式。

    习题9-打印,打印,打印

    练习代码:

    # Here's some new strange stuff ,remember type it exactly.
    
    days = "Mon Tue Wed Thu Fri Sat Sun"
    months = "Jan
    Feb
    Mar
    Apr
    May
    Jun
    Jul
    Aug"
    
    print("Here are the days:",days)
    print("Here are the months:",months)
    
    print("""
    There's something going on here.
    With the three double-quotes.
    We'll be able to type as much as we like.
    Even 4 lines if we want, or 5, or 6.
    """)
    

      练习目的:继续体会打印的用处,初步了解转义符号以及多行打印的用处。

    问题:无

    tips:人世事艰难,你能熬过多少至暗时刻,就能走多远。

    习题10-那是什么

    练习代码:

    tabby_cat = "	I'm tabbed in."
    persian_cat = "I'm split
    on a line."
    backslash_cat = "I'm \ a \ cat"
    
    fat_cat = """
    I'll do a list:
    	* Cat food
    	* Fishies
    	* Catnip
    	* Grass
    """
    
    print(tabby_cat)
    print(persian_cat)
    print(backslash_cat)
    print(fat_cat)
    

      练习目的:对于转义字符的学习

    问题:无

    tips:这里分享部分转义序列(硬核分享),转义字符的斜杠是,不要记反了哦

    习题11-提问

    练习代码:

    print("How old are you?",end=' ')
    age = input()
    print("How tall are you?",end=' ')
    height = input()
    print("How much do you weight?",end='')
    weight = input()
    
    print(f"So, you're {age} old, {height} tall and {weight} heavy")
    

      练习目的:input的使用,用于用户输入,并赋值的过程

      问题:无

      tips:暂无。类似高级用法x = int(input())

    习题15-读取文件

    练习代码:注释如图

    from sys import argv  # 从sys的包中导入argv模块
    
    script, filename = argv  # 为运行命令行时需要输入文件名
    
    txt = open(filename)  # 相当于是文件句柄with open() as f的f
    
    print(f"Here's your file {filename}:")   # 打印文件名字
    
    print(txt.read())   # 打印文件内容
    
    print("Type the filename again:")   # 文件提示
    
    file_again = input("> ")    # 再次打开文件
    
    txt_again = open(file_again)    # 同第六行代码
    
    print(txt_again.read())     # 继续打印

    需要注意的点:

    问:为什么打开两次文件不会报错?

    答:因为在Python中不会限制让你打开一次文件,允许多次打印。但是关闭文件也是必须的。

    16-读写文件

    练习代码:

    from sys import argv
    
    script, filename = argv
    
    print(f"We're going to erase {filename}.")
    print("If you don't want that, hit CTRL-C (^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("
    ")
    target.write(line2)
    target.write("
    ")
    target.write(line3)
    target.write("
    ")
    
    print("And finally, we close it.")
    target.close()

    需要注意的知识点:

    1.close:关闭文件。与编辑器中的“文件” -> “保存” 是一个意思。

    2.read: 读取文件的内容。可以将结果赋给一个变量。

    3.readline: 只读取文本文件中的一行。

    4.truncate:清空文件,小心使用该命令。

    5.write('stuff'): 将"stuff"写入文件

    6.seek(0): 将读写位置移动到开头

    tips:

    open的默认打开模式为r,是只读模式

    习题17-更多文件操作

    from sys import argv
    from os.path import exists
    
    script, from_file, to_file = argv
    
    print(f"Copying from {from_file} to {to_file}")
    
    in_file = open(from_file).read()
    
    print(f"The input file is {len(in_file)} bytes long")
    
    print(f"Does the output file exist?{exists(to_file)}")
    
    print("Ready, hit RETURN to continue, CTRL-C to abort.")
    input()
    
    out_file = open(to_file, 'w')
    out_file.write(in_file)
    
    print("Alright, all done.")
    
    
    out_file.close()
    
    # in_file.close()

    知识点:

    1.exists  以文件名作为参数,文件存在返回true,不存在返回false

    2.书本上存在部分linux指令,后期需要学习

    3.read()一旦执行,会将文件关闭,所以不用自己去关闭文件。

    4.打开文件之后为什么要关闭?减少资源消耗、关闭才会同步到磁盘。

    19-命名、变量、代码和函数

    '''
    函数的功能
    1.他们给代码段命名,就像变量给字符串和数值命名一样
    2.它们可以接收参数,和脚本argv接收参数一样
    '''
    
    #   this one is like your scripts with argv
    def print_two(*args):
        agr1, agr2 = args
        print(f"arg1: {agr1}, arg2: {agr2}")
    
    #   ok, that *args is actually pointless, we can just do this
    def print_two_again(arg1,arg2):
        print(f"arg1: {arg1}, arg2: {arg2}")
    
    #   this just take one argument
    def print_one(arg1):
        print(f"arg1:{arg1}")
    
    #   this one take no argument
    def print_none():
        print("I got nothin'.")
    
    print_two("Zed","Shaw")
    print_two_again("Zed","Shaw")
    print_one("First!")
    print_none()

    知识点:

    1.函数命名的规则

      与变量名相同,只要以字母、下划线以及数字组成的,而不是以关键字开头的即可(也不能是常用的关键字)

    2.*args中的*是什么意思

      告诉python接收所有参数,放到args的列表当中去,在函数中取出来,解包,继续使用。

    19-函数与变量

    话不多说,代码先行:

    def cheese_and_crackers(cheese_count, boxes_of_crackers):
        print(f"You have {cheese_count} cheeses!")
        print(f"You have {boxes_of_crackers} boxes of crackers!")
        print("Man that's enough for a party!")
        print("Get a blanket. 
    ")
    
    print("We can just give the function numbers directly:")
    cheese_and_crackers(20, 30)
    
    
    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) # 调用该方法,通过变量加数字的形式

      本节主要是学习函数的不同的使用方式,分别为常量调用、变量调用、两者相加的调用、含有计算的调用。

      需要注意的是:函数的中的参数,当实际参数传入函数之后,函数会为这些变量创建一些临时的版本,等函数结束之后销毁。

     20-函数与文件

    from sys import argv #从sys库里面导入argv包
    
    script, input_file = argv
    
    def print_all(f):
        print(f.read())
    
    def rewind(f):
        f.seek(0)
    
    def print_a_line(line_count, f):
        print(line_count,f.readline())
    
    current_file = open(input_file)
    
    print("First let's print the whole file:
    ")
    
    print_all(current_file) # 调用函数,打印文件所有内容
    
    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) # 调用print_a_line函数

    知识点:

    1.文件句柄可以理解为针头,读取文件的使用类似固体磁盘去读取

    2.readline()是扫描文件里面的 来找到每一行的终止的。

    21-函数可以返回某些东西

    def add(a, b):
        print(f"ADDING {a} + {b}")
        return a + b
    
    def subtract(a, b):
        print(f"SUBTRACTING {a} - {b}")
        return a - b
    
    def multiply(a, b):
        print(f"MULTIPLYING {a} * {b}")
        return a * b
    
    def divide(a, b):
        print(f"DIVIDING {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(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")
    
    # A puzzle for the extra credit, type it in anyway.
    print("Here is a puzzle.")
    
    what = add(age,subtract(height,multiply(weight,divide(iq,2))))
    
    print("That becomes:",what,"Can you do it by hand?")

      函数中可以通过return,将我们在函数中处理的结果返回出来,比如一个加法的函数,我们的结果可以使用x = add()的方式获取,从而进行其他的操作。

    25-通过终端导入脚本进行测试

    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)
        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):
        """Take 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)

    终端操作如下:

    >>> import ex25
    >>> sentence = "All good things come to those who wait"
    >>> words = ex25.break_words(sentence)
    >>> words
    ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
    >>> sorted_words = ex25.sort_words(words)
    >>> sorted_words
    ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
    >>> ex25.print_first_word(words)
    All
    >>> ex25.print_last_word(words)
    wait
    >>> words
    ['good', 'things', 'come', 'to', 'those', 'who']
    >>> ex25.print_first_word(sorted_words)
    All
    >>> ex25.print_last_word(sorted_words)
    who
    >>> sorted_words
    ['come', 'good', 'things', 'those', 'to', 'wait']
    >>> ex25.print_first_and_last(sentence)
    All
    wait
    >>> ex25.print_first_and_last_sorted(sentence)
    All
    who
    >>> 

      要点:通过终端能够快速的测试我们的代码,而且不用创建新的文件,某种程度来说较为便利。

    30-if

    •  if为代码创建了分支,符合条件的执行,不符合条件的跳过
    • 多个elif为true时,只执行第一个为true的代码块

    if语句的规则

    1. 每一条if语句必须包含一个else.
    2. 如果这个else永远不应该被执行到,因为它本身没有任何意义,那你必须在else语句后面使用一个叫die函数,让它打印出出错消息并且"死"给你看。
    3. if 语句嵌套不要超过两层,最好尽量保持只有一层。
    4. 将if 语句当做段落来对待,其中的每一个if、else好和elif组合就和每一个段落的句子组合一样。这种组合最前面和最后面以一个空行区分。
    5. 布尔测试最好用计算好的运算结果进行判断。
  • 相关阅读:
    Activity的四种launchMode
    Activity及Intent
    关于android中PendingIntent.getBroadcase的注册广播
    C# Parallel用法
    用Parallel.For()和Parallel.For<TLocal>()方法实现并行运行迭代
    CursorAdapter中getView newView bindView异同
    Android四大组件之ContentProvider
    Android 自动换行流式布局的RadioGroup
    真机无法接收到android.provider.Telephony.SMS_RECEIVED的问题
    Wiz开发 定时器的使用与处理
  • 原文地址:https://www.cnblogs.com/swearBM/p/11135298.html
Copyright © 2011-2022 走看看