美文网首页工作生活
【学习笔记,持续更新中】笨办法学python3

【学习笔记,持续更新中】笨办法学python3

作者: Alex_0822 | 来源:发表于2019-07-04 12:10 被阅读0次

    作者 Zed A. Shaw

    前言

    要点

    • 重视读写,注重细节,发现不同
    • 少瞅多问,亲自动手,刻意练习,耐心实践
    • 学习多种编程语言
    • 会写不重要,重要的是利用编程语言去解决的问题才重要
    • 建议:撰写代码,运行代码,破坏代码,修正代码,反复实践
    • 习惯:倒着读代码,为每一行代码在其上方写注释,打印代码,朗读代码
    • 特别提醒,由于markdown显示的原因,所有代码没有换行和缩进,和书上有区别,直接黏贴代码会报错

    习题0 准备工作

    • 下载安装python3,记得关联路径(Add python3.6 to path),文本编辑器ATOM,或者使用VS CODE
    • 利用powershell(win10自带)创建目录,比较重要的命令行有: mkdir 创建目录,ls查看文件内容, cd 更改目录,特别是退回到上一级采用cd .. , dir 查看, quit() 退出,clear清屏,echo 创建txt文件, cat查看文件, rm 删除文件
    • 学习python不要依赖自带的IDLE,而要习惯利用文本编辑器,命令行终端,以及python软件.
    • 习题0:ex0.py
      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.')

    习题1 打印

    print 打印,有两种方式,一种是逐行打印,一种是多行同时打印

    • print("内容"),双引号+print
    • print(''''''内容'''''),'三引号+print
      我们需要再windows 下的powershell中运行,具体是 python ex1.py,当遇到语法错误的时候,即现时SyntaxError时,把错误复制到搜索引擎,取寻找到答案.
    • 习题1:ex1.py
      # 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 is will run.")

    习题2 注释

    • # 英文名是 octothorpe,其作用是注释或者临时禁用一段代码
    • 如果是字符串中,出现#,是不会被忽略的,比如:print("Hi # is here"),这时候只是一个普通字符.
    • EOF语法错误: End Of File
    • 习题2:ex2.py
      # 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 is will run.")

    习题3 数学符号和数字类型

    • 常见的数学运算符号
      +,-,*,/,//,%,<,>,<=,>=,==
    • 整数 3 ,而浮点数 3.0 ,相应函数 int(), float()
    • print函数返回的数学计算式的布尔值
    • 习题3:ex3.py
      print("I will now count my chickends:")
      print("Hens", 25+30/6)
      print("Roosters", 100-25*3%4)
      print("Now I wil count the eggs:")
      print(3+2+1-5+4%2-1/4+6)
      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)

    习题4 变量和命名

    • 变量:指代某个东西的名字,可以采取字母,数字,下划线去命名,通常采用 cars = 100 的方式
    • print 函数有常见的引用变量的方式,引用变量要用逗号隔开,操作符两边用逗号隔开更容易阅读
    • ATOM中,ctrl+t可以调用文件列表
    • 习题4:ex4.py
      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 available.")
      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 need to about", average_passengers_per_car, "in each car.")

    习题5 更多的变量和打印

    • 可以利用ctrl + F 查找和替换
    • round() 函数可以将浮点数四舍五入
    • f"Let's talk about {my_name}." 格式化打印,称之为f字符串
    • 习题5:ex5.py
      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(f"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 get {total}.")

    习题6 字符串和文本

    • w+e 是串联字符串的一种方法
    • 利用print()函数调试代码
    • 习题6:ex6.py
      types_of_people = 10
      x = f"There are {types_of_people} types of people"
      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)

    习题7 连接字符串

    • 格式化字符 .format() ,需要预先在变量后加{}
    • 两个字符用 + 号链接可以生成更长的字符
    • end=' ' 是告诉系统不要换行,注意习题7 end= ' ',单引号之间存在空格的
    • 习题7:ex7.py
      print("Mary had a little lamb.")
      print("Its fleece was white as {}.".format('snow'))
      print("And everywhere what 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=' ')
      print(end7 + end8 + end9 +end10 +end11 +end12)

    习题8 打印,打印

    • 利用.format()函数实现,format()函数可以传递多个参数,需要与formatter中的{}数量匹配,但是并非一定要完全相同,参数数量不能少于{}数量
    • "one"是字符串需要加引号,而True和False是关键字不需要加
    • 习题8:ex8.py
      formatter = "{} {} {} {}"
      print(formatter.format(1, 2, 3, 4))
      print(formatter.format("one", "two", "three", "four"))
      print(formatter.format(True, False, False, True))
      print(formatter.format(formatter, formatter, formatter, formatter))
      print(formatter.format(
      "Try your",
      "Own text here",
      "Maybe a poem",
      "Or a song about fear"
      ))

    习题9 打印,打印,打印

    • \n 称之为转义字符,用于实现换行
    • 利用三引号可以直接输入多行,无需额外换行符
    • 习题9:ex9.py
      # Here's some strange stuff, remember type it exatly.
      days = "Mon Tue Wed Thu Fri Sat Sun"
      months = "\nJar\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
      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.
      """)

    习题10 那是什么

    • "\n"转义字符,用于展示一些特别的符号,在字符串中,转义字符也可以识别出
    • 习题10:ex10.py
      tabby_cat = "\tI'm tabbed in."
      persian_cat = "I'm split\non a line."
      backslash_cat = "I'm \ a \ cat."
      fat_cat = """
      I'll do a list:
      \t* Cat food
      \t* Fishies
      \t* Catnip\n\t* Grass
      """
      print(tabby_cat)
      print(persian_cat)
      print(backslash_cat)
      print(fat_cat)
    • 字符串转义序列
    关键字 描述
    \\ 反斜杠
    \' 单引号
    \" 双引号
    \a 响铃
    \b 退格符
    \f 进纸符
    \N{name} Unicode数据库中的字符名,其中name是它的名字,仅Unicode适用
    \n 换行符
    \r 回车符(CR)
    \t 水平制表符(TAB)
    \v 垂直制表符(VT)

    习题11 提问

    • 软件一般做的三件事:接受输入的内容,改变输入的内容,打印出改变的内容
    • print("How old are you?",end='')
    • age = input() ,input()是输入函数,input()函数输入内容必须从命令行得到,对于输入内容是整数,可以利用int()函数转换输入内容,比如age = int(input())
    • repr()呈现函数,可以查看数据的类型,如果是字符串,打印时会有引号
    • 习题11:ex11.py
      print("How old are you?", end=' ')
      age = input()
      print("How tall are you?", end='' )
      height = input()
      print("How much your weight?", end=' ')
      weight = input()
      print(f"So, you're {age} old, {height} tall and {weight} heavy.")

    习题12 提示别人

    • 变量名 = input("可以添加提示内容:")
    • 后面也可以采取提示符的方式提示
    • 习题12:ex12.py
      age = input("How old are you?")
      height = input("How tall are you?")
      weight = input("How much your weight?")
      print(f"So, you're {age} old, {height} tall and {weight} heavy.")

    习题13 参数、解包和变量

    • import 引入模块 module
    • sys 就是一个模块
    • argv 参数变量,保存着python运行时,传递给python脚本的参数
    • script 脚本名称,系统自带的变量
    • script,first,second,third = argv 解包,将参数赋值给4个变量
    • argv是在执行命令时就要输入,input()是在脚本运行过程中用户输入
    • 习题13:ex13.py
    • 用户执行命令时,用argv,运行程序时,用input
      from sys import argv
      # read the WYSS section for how to run this
      script, first, second, third = argv
      print("The script is called:", script)
      print("Your first variable is:", first)
      print("Your second variable is:", second)
      print("Your third variable is:", third)

    习题14 提示和传递

    • prompt = '>' 利用> 进行提示,告知这个地方需要输入,这个提示符可以修改成自己喜欢的字符
    • lives = input (prompt)
    • 习题14:ex14.py
      from sys import argv
      script, user_name =argv
      prompt = '>'
      print(f"Hi {user_name}, I'm the {script} script.")
      print("I'd like to ask you a few questions.")
      print(f"Do you like me {user_name}?")
      likes = input(prompt)
      print(f"Where do you live, {user_name}?")
      lives = input(prompt)
      print("What kind of computer do you have?")
      computer = input(prompt)
      print(f"""
      Alright, so you said {likes} about liking me.
      You lives in {lives}. Not sure where that is.
      And you have a {computer} computer. Nice.
      """)

    习题15 读取文件

    • 通过argv获取文件名并赋值给filename
    • 通过txt= open(filename) 获取"file object"(文件对象),而非内容
    • 因此txt.read()读取文件对象中的内容

    ex15_sample.txt
    This is stuff I typed into a file.
    It is readlly cool stuff.
    Lots and lots of fun to have in here.

    • 习题15:ex15.py
      from sys import argv
      script, filename = argv
      txt = open(filename)
      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())

    习题16 读写文件

    • read: 读取文件的内容, r+表示读写
    • readline:读取文件中的一行内容
    • close:关闭文件
    • truncate: 清空文件,小心使用该命令
    • seek(0): 将读写位置移动到文件开头
    • write('stuff'): 将'stuff'写入文件
    • append(' stuff'): 追加'stuff' , a+ 用于读写
    • 本例子中 target = open(filename,'w') 中,w打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。此外:w+则表示读写
    • 基本使用方法,沿着如下路线:open---read---close
    • 习题16:ex16.py
      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 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 lies.")
      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()

    习题17 更多文件操作

    • 模块 os.path 参数 exists
    • 题目中的格式是 print(f"Does the output file exist?{exists(to_file)}") 返回的是布尔值,如果文件存在,则返回True,否则False
    • len( ) 返回文本长度
    • 使用close()函数是为了避免资源浪费甚至耗尽
    • echo函数生产txt文件的方法,在中文环境下可能会产生问题,因此,用VS CODE生成txt文件更好
    • 习题17:ex17.py
      from sys import argv
      from os.path import exists
      script, from_file, to_file =argv
      print(f"Copying from {from_file} to {to_file}")
      # we could do these two on one line, how?
      in_file = open(from_file)
      indata = in_file.read()
      print(f"The input file is {len(indata)} 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(indata)
      print("Alright, all done.")
      out_file.close()
      in_file.close()

    习题18 命名、变量、代码和函数

    • 函数用def开头
      -函数名用字母数字和下划线组成,数字不可以开头
    • 函数名必须带小括号
    • 小括号内不一定要有参数,参数与参数之间用逗号隔开,也可以用*args将参数放到名为args的列表中去
    • 括号后紧跟冒号:
    • 使用TAB或者四个空格缩进
    • 运行函数,调用函数,使用函数是一个意思
    • 习题18:ex18.py
      # this one is like your scripts with argv
      def print_two(*args):
      arg1, arg2 =args
      print(f"arg1: {arg1}, arg2: {arg2}")
      # ok, that *args is actually pointless, we can just do this
      def print_two_again(arg1,arg2):
      print(f"arg1: {arg2}, arg2: {arg2}")
      # this just takes one argument
      def press_one(arg1):
      print(f"arg1: {arg1}")
      # this one takes no arguments
      def print_none():
      print("I got nothing.")
      print_two("Zed","Shaw")
      print_two_again("Zed","Shaw")
      press_one("First!")
      print_none()

    习题19 函数和变量

    • 函数里的变量和脚本里的变量之间是没有联系,一个是局部变量,另一个是全局变量,尽可能让局部变量和全局变量名称不一样,尽管不会影响
    • 函数中的变量尽量不超过5个,函数中可以调用函数
    • 习题19:ex19.py
      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.\n")
      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 函数和文件

    • 定义一个函数来读取文件,理解函数和文件是如何一起协作的
    • readline()读取一行
    • 习题20:ex20.py
      from sys import 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:\n")
      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)

    习题21 函数可以返回某些东西

    • 函数利用命令return 返回值,print函数的返回值为None
      -复合函数要有内部到外部读取
    • 习题21:ex21.py
      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"MULTIPLING {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?")

    习题22 到现在为止你学到什么

    • 复习:记下每个词和每一个符号,在每一个关键字后面写出它的名字,并说明作用,遇到找不到答案的东西,先记下来,等下次遇到再找,等列表做好后过几天重再做列表
    • 学会了输入input和输出print, 学会注释#, 学会了提问和提示别人
    • 学会了通过变量和命名,学会了利用变量存储数据
    • 学会计算操作,学会了格式化字符串,f字符换,和format()函数
    • 学会如何使用转义字符
    • 学到模块sys, os.path, 明白了什么是参数,解包和变量
    • 掌握了如何读取文件的基本步骤:OPEN-READ-WRITE-CLOSE
    • 掌握了函数的命名,如何定义参数,以及如何返回值return,知道了什么是全局变量,什么是局部变量
    • 习题22:ex22.py

    习题23 字符串、字节串和字符编码

    • 需要理解的四个方面:
      计算机是如何存储人类语言的,计算机的字符串的编码和字节串的解码,如何处理字符串和字节处理中的出现的错误,如何阅读代码
    • 计算机根本上是一个巨大的开关列阵,通过电来触发开关,用数字1表示有电和开启,用数字0表示没电和关闭,而数字1和0被称之为位; 8位序列被称之为字节
    • ASCII:American Standard Code For Imformation Interchange ;Unicode:万国码
    • 编码字符串,解码字节串
    • main()函数有三个参数,第一个参数是文件,第二个参数是编码方式:utf-8,第三个编码要求是:strict,利用open函数读取文件内容,并复制给languages获得第一个参数, 第二个参数和第三个参数利用argv解包得到
    • if line:是用来判断语句是否存在,后面接着跟着两个函数,一个是打印行的自定义函数,一个是调用main函数本身
    • print_line函数有三个参数,一个参数是从主函数main得到的参数line,后面两个仍然是之前通过argv得到的两个参数,strip()函数用于删除结尾的换行符\n,15和16分别用来编码字符串和解码字节串,其逻辑是通过编码字符串得到字节串,然后解码字节串得到字符串。18行直接打印对比的字节串和字符串
    • 21行打开文件,编码方式是utf-8,23行是调用主函数.
    • 习题23:ex23.py
      import sys
      script, encoding, error = sys.argv
      def main(language_file, encoding, errors):
      line = language_file.readline()
      if line:
      print_line(line, encoding, errors)
      return main(language_file, encoding, errors)
      def print_line(line, encoding, errors):
      next_lang = line.strip()
      raw_bytes = next_lang.encode(encoding, errors = errors)
      cooked_string = raw_bytes.decode(encoding, errors = errors)
      print(raw_bytes, "<===>", cooked_string)
      languages = open("languages.txt", encoding = "utf-8")
      main(languages, encoding, error)

    习题24 更多的练习

    print("Let's practice everything.")
    print('You'd need to know 'bout escapes with \ that do:' )
    print('\n newlines and \t tabs.')
    poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend pass from intuition
    and requires an explanation
    \n\t\twhere there is none.
    """
    print("--------------")
    print(poem)
    print("--------------")
    five = 10 -2 + 3 - 6
    print(f"This should be five:{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)
    # remeber that this is another way to format a string
    print("With a starting point of:{}".format(start_point))
    # it's just like with an f"" string
    print(f"We's have {beans} beans, {jars} jars, and {crates} crates.")
    start_point = start_point / 10
    print("We can also do that this way:")
    formula = secret_formula(start_point)
    # this is an easy way to apply a list to a format string
    print("We'd have {} beans, {} jars, and {} crates.".format(*formula))

    习题25 更多更多的练习

    • 定义函数,利用import调用函数文件,在IDLE中实现交互式操作
    • 结束需要用quit()来实现
    • 习题25:ex25.py
      def break_words(stuff):
      """This function will break 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 poping it off."""
      word = words.pop(0)
      print(word)
      def print_last_word(words):
      """Prints the last word agter poping 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)

    交互式代码
    python
    import ex25
    sentence = "All good things come to those who wait."
    words = ex25.break_words(sentence)
    words
    sorted_words = ex25.sort_words(words)
    sorted_words
    ex25.print_first_word(words)
    ex25.print_last_word(words)
    words
    ex25.print_first_word(sorted_words)
    ex25.print_last_word(sorted_words)
    sorted_words
    sorted_words = ex25.sort_sentence(sentence)
    sorted_words
    ex25.print_first_and_last(sentence)
    ex25.print_first_and_last_sorted(sentence)

    习题26 恭喜你,现在可以考试了

    • 代码下载地址
    • 习题26:ex26.py
    • 修改后代码如下
    • from sys import argv
      print("How old are you?", end=' ')
      age = input()
      print("How tall are you?", end=' ')
      height = input()
      print("How much do you weigh?", end=' ')
      weight = input()
      print(f"So, you're {age} old, {height} tall and {weight} heavy.")
      script, filename = argv
      txt = open(filename)
      print("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())
      print('Let's practice everything.')
      print("""You'd need to know 'bout escapes
      with \ that do \n newlines and \t 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(f"This should be five: {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)
      # remember that this is another way to format a string
      print("With a starting point of: {}".format(start_point))
      # it's just like with an f"" string
      print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
      start_point = start_point / 10
      print("We can also do that this way:")
      formula = secret_formula(start_point)
      # this is an easy way to apply a list to a format string
      print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
      people = 20
      cats = 30
      dogs = 15
      if people < cats:
      print ("Too many cats! The world is doomed!")
      if people < cats:
      print("Not many cats! The world is saved!")
      if people < dogs:
      print("The world is drooled on!")
      if people > dogs:
      print("The world is dry!")
      dogs += 5
      if people >= dogs:
      print("People are greater than or equal to dogs.")
      if people <= dogs:
      print("People are less than or equal to dogs.")
      if people == dogs:
      print("People are dogs.")

    习题27 记住逻辑关系

    • 布尔操作符: 与and,或or,非not
    • 比较操作符: 不等于!=,等于==,大于或等于>=,小于或等于<=
    • 布尔值:真True,假False
    • 习题27:ex27.py

    习题28 布尔表达式练习

    • 顺序:比较操作符---布尔二元操作符---NOT---找到剩下的and/or,解出它们的值
    • 习题28:ex28.py

    习题29 if语句

    • if语句是控制流程语句,判断真假,if使用时,if + 条件 + :
    • 判断语句的下一行要缩进四个空格,类似于目录
    • x += 1 <===> x = x+1 ,我们称之为递增运算符
    • 习题29:ex29.py
      people = 20
      cats = 30
      dogs = 15
      if people < cats:
      print("Too many cats! The world is doomed!")
      if people > cats:
      print("Not many cats! The world is saved!")
      if people < dogs:
      print("The world is drooled on!")
      if people > dogs:
      print("The world is dry!")
      dogs += 5
      if people >= dogs:
      print("People are greater than or equal to dogs.")
      if people <= dogs:
      print("People are less than or equal to dogs.")
      if people == dogs:
      print("People are dogs.")

    习题30 else和if

    • 习题30:ex30.py
      people = 30
      cars = 40
      trucks = 15
      if cars > people:
      print("We should take the cars.")
      elif cars < people:
      print("We should not take the cars.")
      else:
      print("We can't decide.")
      if trucks > cars:
      print("That's too many trucks.")
      elif trucks < cars:
      print("Maybe we could take the trucks.")
      else:
      print("We still can't decide.")
      if people > trucks:
      print("Alright, let's just take the trucks.")
      else:
      print("Fine, let's stay houme then.")

    习题31 作出决定

    • IF语句中可以嵌套IF语句
    • 改进提示prompt = ">"
    • 比较操作符 == 是两个等号
    • 习题31:ex31.py
      print("""You enter a dark room with two doors.
      Do you go through door #1 or door #2?""")
      prompt = ">"
      door = input(prompt)
      if door == "1":
      print("There's a giant bear here eating a cheese cake.")
      print("What do you do?")
      print("1. Take the cake.")
      print("2. Scream at the bear.")
      bear = input(prompt)
      if bear == "1":
      print("The bear eats your face off. Good job!")
      elif bear == "2":
      print("The bear eats your face legs off. Good job!")
      else:
      print(f"Well, doing {bear} is probably better.")
      print("Bear runs away.")
      elif door == "2":
      print("You stare into the endless abyss at Cthulhu's retina.")
      print("1. Blueberries.")
      print("2. Yellow jacket clothespins.")
      print("3. Understanding revolvers yeling melodies.")
      insanity = input(prompt)
      if insanity == "1" or insanity == "2":
      print("Your body survies powered by a mind of jello.")
      print("Good job!")
      else:
      print("The insanity rots your eyes into a pool of muck.")
      print("Good job!")
      else:
      print("You stumble around and fall on a knife and die. Good job!")

    习题32 循环和列表

    • 创建列表 hairs = {'brown', 'blond', 'red'}
    • 空列表 [], append()函数用于列表尾部追加元素
    • for循环开始的变量就直接被定义了,for i in range(1,3)支循环两次的原因是这是一个半闭半开去间,从第一个数开始,最后一个数不执行
    • 二位列表 [[1, 2, 3], [4, 5, 6]]
    • 习题32:ex32.py
      the_count = [1, 2, 3, 4, 5]
      fruits = ['apples', 'oranges', 'pears', 'apricots']
      change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
      # this first kind of for-loop goes through a list
      for number in the_count:
      print(f"This is count {number}")
      # same as above
      for fruit in fruits:
      print(f"A fruit of types: {fruit}")
      # also we can go through mixed lists too
      # notice we have to use {} since we don't know what's in it
      for i in change:
      print(f"I got {i}")
      # we can also build lists, first start with an empty one
      elements = []
      # then use the range function to do 0 to 5 counts
      for i in range(0,6):
      print(f"Adding {i} to the list.")
      # append is a function that lists understand
      elements.append(i)
      # now we can print them out too
      for i in elements:
      print(f"Element was : {i}")

    习题33 while循环

    • while 循环又称为无限循环,直到出现False才会结束
    • 三个原则:尽量少用while 循环,大部分时候for更好; 重复检查你的while语句,测试布尔表达式最后会变为False; 如果不确定, 就在while 循环的开始和结尾打印出你要测试的值,看看它的变化
    • 习题33:ex33.py
      i = 0
      numbers = []
      while i <6:
      print(f"At the top i is {i}")
      numbers.append(i)
      i = i + 1
      print("Numbers now: ", numbers)
      print(f"At the bottom i is {i}")
      print("The numbers: ")
      for num in numbers:
      print(num)

    习题34 访问列表的元素

    • 序数:有顺序的数字,从1开始; 基数:随机选取的数,用于找到位置,从0开始
    • 基础 = 序数 - 1
    • 习题34:ex34.py

    习题35 分支和函数

    • 用思维导图制作一个流程图,要点是明确是串联还是并联
    • 这个分支与函数是后面ex42的前身
    • 习题35:ex35.py
      from sys import exit
      def gold_room():
      print("This room is full of gold. How much do you take?")
      choice = input(">")
      if "0" in choice or "1" in choice:
      how_much = int(choice)
      else:
      dead("Man, learn to type a number.")
      if how_much < 50:
      print("Nice, you're not greedy, you win!")
      exit(0)
      else:
      dead("You greedy bastard!")
      def bear_room():
      print("There is a bear here.")
      print("The bear has bunch of honey.")
      print("The fat bear is in front of another door.")
      print("How are you going to move the bear?")
      bear_moved = False
      while True:
      choice = input(">")
      if choice == "Take honye":
      dead("The bear looks at you then slaps your face off.")
      elif choice == "taunt bear" and not bear_moved:
      print("The bear has moved from the door.")
      print("You can go through it now.")
      bear_moved = True
      elif choice == "taunt bear" and bear_moved:
      dead("The bear gets pissed off and chews your leg off.")
      elif choice == "open door" and bear_moved:
      gold_room()
      else:
      print("I got no idea what that means.")
      def cthulhu_room():
      print("Here you see the great evil Cthulhu.")
      print("He, it, whatever stares at you and you go insane.")
      print("Do you flee for your life or eat your head?")
      choice = input(">")
      if "flee" in choice:
      start()
      elif "head" in choice:
      dead("Well that was tasty!")
      else:
      cthulhu_room()
      def dead(why):
      print(why, "Good job!")
      exit(0)
      def start():
      print("You are in a dark room.")
      print("There is a door to your right and left.")
      print("Which one do you take?")
      choice = input(">")
      if choice == "left":
      bear_room()
      elif choice == "right":
      cthulhu_room()
      else:
      dead("You stumble around the room until you starve.")
      start()

    习题36 设计和调试

    • if 语句的规则
    1. 每一条if语句必须包含一个else
    2. 如果这个else永远都不应该被执行到,因为它本身没有任何意义,那么必须再else语句后面使用一个叫做die的函数,让它打印出出错消息,并且”死“给你看,这和上一个习题类似,这样你可以找到很多的错误,PS:老肖真会开玩笑
    3. if语句的嵌套不要超过两层,尽量保持只有一层
    4. 将if语句当作段落来对待,期中的每一个if-elif-else组合就跟一个段落的句子组合一样,再这种组合的最前面和最后面留一个空行用以区分
    5. 你的不二测试应该很简单,如果它们很复杂,你需要在函数里将它们的运算事先放到一个变量里,给变量取一个好名字
    • 循环的规则
    1. 只有在循环永不停止时使用”while“循环,这意味着你可能永远都用不到。这一条只有在python中成立,其他语言另当别论
    2. 其他类型的循环都使用for循环,尤其是在循环的对象数量固定或者有限的情况下.
    • 调试的小技巧
    1. 不要使用”调试器“(debugger)。调试器所作的相当于对病人进行全身扫描。你并不会得到某方面的有用信息,而且你会发现他输出的信息太多,而且大部分没有用,或者只会让你更困惑。
    2. 调试程序的最好的方法是使用print在各个想要检查的关键点将变量打印出来,从而检查那里是否有错
    3. 让程序一部一部分地运行起来。不要等写了一大堆代码文件后采取运行它们,写一点儿,运行一点,再修改一点儿。
    • 写软件最好的方法
    1. 再纸上或者索引卡上列出你要完成的任务,这就是你的待办任务
    2. 从中挑出最简单的任务
    3. 在源代码文件中写下注释,作为你完成任务代码的指南
    4. 在注释下面写一些代码
    5. 快速运行你的代码,看它是否工作
    6. 循环”写代码,运行代码进行测试,修正代码”的过程
    7. 从任务列表中划掉这条任务,跳出下一个最简单的任务,重复上述步骤。

    习题37 复习各种符号

    关键字

    关键字 描述 示例
    and True and False == False
    as with-as 语句的一部分 with X as Y:pass
    assert 断言某东西为真 assert False, 'Error!'
    break 立即停止循环 while True: break
    class 定义类 class Person(object)
    continue 停止当前循环的后续步骤,再做一次循环 While True:continue
    def 定义函数 def x():pass
    del 从字典中删除 del X[Y]
    elif else if 条件 if:X; elif:Y;else:J
    else else 条件 if:X; elif:Y;else:J
    except 如果发生异常,运行此处代码 except ValueError,e:print(e)
    exec 将字符串作为python脚本运行 exec'print('Hello')'
    finally 不管是否发生异常,都运行此处代码 finally:pass
    for 针对物件集合执行循环 for X in Y:pass
    from 从模块中导入特定部分 from X import Y
    global 声明全局变量 global X
    if if条件 if:X; elif: Y;else:J
    import 将模块导入当前文件以供使用 import os
    in for循环一部分,也可以判断x是否在y中 fro X in Y:pass 以及1 in [1] == True
    is 类似于==,判断是否一样 1 is 1 == True
    lambda 创建短匿名函数 s = lambda y: y**y; s(3)
    not 逻辑非 not True = Flase
    or 逻辑或 True or False == True
    pass 表示空代码块 def empty(): pass
    print 打印字符串 print("This sting")
    raise 出错后引发异常 raise ValueError("No")
    return 返回值并且退出函数 def X(): return Y
    try 尝试执行代码,出错后转到except try: pass
    while while循环 while X: pass
    with 将表达式作为一个变量,然后执行代码块 with X as Y : pass
    yield 暂停函数,返回到调用函数的代码中 def X(): yield Y; X().next()

    数据类型

    关键字 描述 示例
    True True of Flase ==True
    False False and True == False
    None 不存在,没有值 x == None
    bytes 字节存储值 x = b'hello'
    strings 存储文本信息 x ='hello'
    numbers 存储整数 i = 100
    Floats 存储十进制数 i= 10.389
    lists 存储列表 j = [1,2,3,4]
    dicts 存储键-值映射 e = {'x': 1, 'y':2 }
    • 阅读代码的一些要求
    1. 打印代码,大脑更偏爱纸质内容
    2. 笔记涵盖内容方面要求
    • 函数以及函数的功能
    • 每个变量初始赋值的位置
    • 每个在程序的各个部分中多次出现的同名变量。它们以后可能会给你带来麻烦
    • 任何不包含else子句的if语句。它们是正确的嘛?
    • 任何可能没有结束点的while循环
    • 代码中任何你看不懂的部分
    1. 自己写注释节是代码,节是各个函数的使用方法,各个变量的用途,以及任何其他方面的内容
    2. 代码中比较难的各个部分,逐行或者逐个函数跟踪变量值,再打印一份出来,在代码空白处写出> 要“追踪”的每个变量的值
    3. 一旦理解了代码的功能,回到计算机前,在屏幕上重读一次,看看能不能找到新的问题点,然后继续新的代码,用上述方法阅读理解,直到你不再需要纸质打印为止

    习题38 列表的操作

    • 有序的列表
    • 要存储的东西
    • 随机访问
    • 线性
    • 通过索引
    • spilt()函数是将字符串按照指定的格式分开成列表,join()函数是将列表按照指定的格式变成字符串
    • pop()函数将列表最后一个元素删除,并且返回最后一个元素
    • 习题38:ex38.py
      ten_things = "Apples Oranges Crows Telephone Light Sugar"
      print("Print there are not 10 things in that list. Let's fix that.")
      stuff = ten_things.split(' ')
      more_stuff = ["Day", "Night", "Song", "Frisbee",
      "Corn", "Banana", "Girl", "Boy"]
      while len(stuff) != 10:
      next_one = more_stuff.pop()
      print("Adding: ", next_one)
      stuff.append(next_one)
      print(f"There are {len(stuff)} items now.")
      print("There we go: ", stuff)
      print("Let's do some things with stuff.")
      print(stuff[1])
      print(stuff[-1]) # whoa!fancy
      print(stuff.pop())
      print(' '.join(stuff)) # what?cool
      print('#'.join(stuff[3:5])) # super stellar!

    习题39 字典,可爱的字典

    • Python 字典 items() 方法以列表返回可遍历的(键, 值) 元组数组。
    • Python 列表 list() 创建列表
    • Python 字典 get() 函数返回指定键的值,如果值不在字典中返回默认值。
    • 习题39:ex39.py
      # create a mapping of state to abbreviation
      states = {
      'Oregon': 'OR',
      'Florida': 'FL',
      'California': 'CA',
      'New York': 'NY',
      'Michigan': 'MI'
      }
      # create a basic set of states and some cities in them.
      cities = {
      'CA': 'San Francisco',
      'MI': 'Detroit',
      'FL': 'Jacksonville'
      }
      # add some more cities
      cities['NY'] = 'New York'
      cities['OR'] = 'Portland'
      # print out some cities
      print('-' * 10)
      print("NY State has:", cities['NY'])
      print("OR State has:", cities['OR'])
      # print some states
      print('-' * 10)
      print("Michigan's abbreviation is: ", states['Michigan'])
      print("Florida's abbreviation is: ", states['Florida'])
      # do it by using the state then cities dict
      print('-' * 10)
      print("Michigan has: ", cities[states['Michigan']])
      print("Florida has: ", cities[states['Florida']])
      # print every state abbreviation
      print('-' * 10)
      for state, abbrev in list(states.items()):
      print(f"{state} is abbreviated {abbrev}")
      # now every city in state
      print('-' * 10)
      for abbrev, city in list(cities.items()):
      print(f"{abbrev} has the city {city}")
      # now do both at the same time
      print('-' * 10)
      for state, abbrev in list(states.items()):
      print(f"{state} state is abbreviated {abbrev}")
      print(f"and has city {cities[abbrev]}")
      print('-' * 10)
      # safely get a abbreviation by state that might not be there
      state = states.get('Texas')
      if not state:
      print("Sorry, no Texas.")
      # get a city with a default value
      city = cities.get('TX', 'Does not Exist')
      print(f"The city for the state 'TX' is: {city}")

    习题40 模块、类和对象

    • 模块类似于字典的映射概念,是一种将一种东西对应到另外一种的方式
    • 模块包含函数和变量的python文件,可以导入这个文件,然后可以使用操作符访问模块中的函数和变量
    • python一个非常常用的模式,即拿一个类似“键=值”风格的容器,通过”键“的名称获取期中的”值"
    • 类就像一种蓝图或者一种预定义的东西,通过它可以创建新的迷你模块
    • 实例化的过程相当于你创建了这么一个迷你模块,而且同时导入了它。”实例化“的意思就是从类创建一个对象
    • 结果创建的迷你模块就像是一个对象,你可以将它赋给一个变量后供后续操作
    • 类的工作原理
    1. python 查找MyStuff()并且知道它是一个定义过的类
    2. python创建了一个空对象,里面包含了你在该类中用def指定的所有函数
    3. python回去检查你是不是创建了一个init函数,如果有创建,它就会调用这个函数,从而对你新创建的空对象实现了初始化
    4. 在MyStuff的init函数里,有一个多余的函数教self,这就是python为你创建的空对象,而你可以对它进行类似模块,字典等的操作,为它设置一些变量
    • 习题40:ex40.py
      class MyStuff(object):
      def init(self):
      self.tangerine = "And now a thousand years between"
      def apple(self):
      print("I AM CLASSY APPLES!")
      thing = MyStuff()
      thing.apple()
      print(thing.tangerine)

    class Song(object):
    def init(self,lyrics):
    self.lyrics = lyrics
    def sing_me_a_song(self):
    for line in self.lyrics:
    print(line)
    happy_bday= Song(["Happy birthday to you",
    "I don't want to get sued",
    "So I'll stop right there"])
    bulls_on_parade= Song(["They rally around the family",
    "with pockets full of shells"])
    happy_bday.sing_me_a_song()
    bulls_on_parade.sing_me_a_song()

    习题41 学习面向对象术语

    专有词汇练习

    • 类(class):告诉python创建新类型的东西
    • 对象(object):两个意思,即最基本的东西,或者某样东西的实例
    • 实例(instance):这是让python创建一个类时得到的东西
    • def:则会使类里定义函数的方法
    • self:在类的函数中,self指代被访问的对象或者实例的一个变量
    • 继承(inheritance): 指一个类可以继承另一个类的特性,和父子关系类似
    • 组合(composition):指一个类可以将别的类作为它的部件构建起来,有点像车子和车轮的关系
    • 属性(attribute):类的一个属性,它来自于组合,而且通常是一个变量
    • 是什么(is-a): 用来描述继承关系,如Salmon is-a Fish
    • 有什么(has-a):某个东西有某特征,如Salmon has-a mouth,或用来描述某个东西是由另外一些东西组成
    • 措辞练习
    • class X(Y): 创建一个叫X的类,它是Y的一种
    • class X(object): def__init__(self,J): 类X有一个_init_, 它接收self和J作为参数
    • class X(object): def M(self,J): 类X有一个名为M的函数,它接收self和J作为参数
    • foo = X(): 将foo设为类X的一个实例
    • foo.K = Q: 从foo中获取K属性,并将其设为Q
    • foo.M(J): 从foo中找到M的函数,并使用self和J参数调用它
    • 习题41:ex41.py
      import random
      from urllib.request import urlopen
      import sys
      WORD_URL = "http://learncodethehardway.org/words.txt"
      WORDS = []
      PHRASES = {
      "class %%%(%%%):":
      "Make a class named %%% that is-a %%%.",
      "class %%%(object):\n\tdef__init__(self, )":
      "class %%% has-a init that takes self and *** params.",
      "class %%%(object):\n\tdef (self, @@@":
      "class %%% has-a function *** that takes self and @@@ params.",
      "
      = %%%()":
      "set *** to an instance of class %%%.",
      "
      .(@@@)":
      "From *** get the *** function, call it with params self, @@@.",
      "
      .*** = ''":
      "From *** get the *** attribution and set it to '
      '."
      }
      # do they want to drill phrases first
      if len(sys.argv) == 2 and sys.argv[1] == "english":
      PHRASE_FIRST = True
      else:
      PHRASE_FIRST = False
      # load up the words from the website
      for word in urlopen(WORD_URL).readlines():
      WORDS.append(str(word.strip(), encoding = "utf-8"))
      def convert(snippet, phrase):
      clase_names = [w.capitalize() for w in
      random.sample(WORDS, snippet.count("%%%"))]
      other_names = random.sample(WORDS, snippet.count(""))
      results = []
      param_names = []
      for i in range(0, snippet.count("@@@")):
      param_count = random.randint(1,3)
      param_names.append(', '.join(
      random.sample(WORDS, param_count)))
      for sentence in snippet, phrase:
      result = sentence[:]
      \ # fake class names
      for word in clase_names:
      result = result.replace("%%%", word, 1)
      \ # fake other names
      for word in other_names:
      result = result.replace("
      ", word, 1)
      \ # fake parameter lists
      for word in param_names:
      result = result.replace("@@@", word, 1)
      results.append(result)
      return results
      # keep going until they hit CTRL-D
      try:
      while True:
      snippets = list(PHRASES.keys())
      random.shuffle(snippets)
      for snippet in snippets:
      phrase = PHRASES[snippet]
      question, answer = convert(snippet, phrase)
      if PHRASE_FIRST:
      question, answer = answer, question
      print(question)
      input("> ")
      print(f"ANSWER: {answer}\n\n")
      except EOFError:
      print("\nBye")

    习题42 对象、类及从属关系

    • 类(class):用来描述具有同类苏还行的实例的概括性的词汇
    • 对象(object):具有类属性的具体、真实的东西
    1. 类比: 鱼---泥鳅---小丽 <===> 类---(子)类---实例
    2. 区分方法:is-a (是什么) 用在谈论"两者以类的关系互相关联"的时候 , has-a (有什么) 用在两者无共同点,仅相互参照的时候. 比如: 是什么讨论鱼和泥鳅的关系, 有什么 讨论的是泥鳅和鳃的关系.
    • 习题42:ex42.py
      ## Animal is-a object (yes, sort of confuing) look at the extra credit
      class Animal(object):
      pass
      ## ??
      class Dog(Animal):
      def init(self, name):
      ## ??
      self.name = name
      ## ??
      class Cat(Animal):
      def init(self,name):
      ## ??
      self.name = name
      ## ??
      class Person(object):
      def init(self,name):
      ## ??
      self.name = name
      \ ## Person has-a pet of some kind
      self.pet =None
      ## ??
      class Employee(Person):
      def init(self, name, salary):
      ## ?? hmm what is this strange magic?
      super(Employee, self).init(name)
      ## ??
      self.salary = salary
      ## ??
      class Fish(object):
      pass
      ## ??
      class Salmon(Fish):
      pass
      ## ??
      class Halibut(Fish):
      pass
      ## rover is-a Dog
      rover = Dog("Rover")
      ## ??
      satan = Cat("Satan")
      ## ??
      mary = Person("Mary")
      ## ??
      mary.pet =satan
      ## ??
      frank = Employee("Frank", 120000)
      ## ??
      frank.pet =rover
      ## ??
      flipper =Fish()
      ## ??
      crouse = Salmon()
      ## ??
      harry = Halibut()

    习题43 基本的面向对象分析和设计

    • 自顶向下流程:从抽象的概念入手,逐渐细化,知道概念变成具体的可用代码实现的东西
    1. 把要解决的问题写下来,或者画出来
    2. 将第一条中的关键概念提取出来并加以研究
    3. 创建一个类层次结构和对象图
    4. 用代码实现各个类,并写一个测试来运行它们
    5. 重复上述步骤并细化代码
    • 克苏鲁的房间


      分支与选择--python函数流程图.png
    • 老肖整理的类层次结构图
    • MAP
      ** NEXT_SCENE
      ** OPENING_SCENE
    • ENGINE
      ** PLAY
    • SCENE
      ** ENTER
      ** DEATH
      ** CENTRAL OF CORRIDOR
      ** THE BRIDGE
      ** LASER WEAPON ARMORY
      ** ESCAPE POD
    • 克苏鲁的房间中文版
      from sys import exit
      def explain(why):
      print(why,"Good job!.")
      exit(0)
      def start():
      print("""
      你在一间黑暗的房间,
      在你的左右两边分别有一扇门,
      你会选择那一扇门呢?
      """)
      choice = input("你有三个选择,"左"或者"右"或者你自己做选择,\n>")
      if choice == "左":
      bear_room()
      elif choice == "右":
      cthulhu_room()
      else:
      explain("你被房间绊倒了直到被饿死")
      def cthulhu_room():
      print("""
      在这里你将看到伟大的恶魔克苏鲁.
      只要他看到你,你将被石化.
      你是逃跑还是让他吃掉你的头颅?
      """)
      choice = input("你是选择"逃跑"或者"让他吃掉头颅"或者自己做选择,\n>")
      if choice == "逃跑":
      start()
      elif choice == "让他吃掉头颅":
      explain("恶魔吃掉你的头颅,并宣称非常的美味!")
      else:
      cthulhu_room()
      def bear_room():
      print("""
      这里有一只熊.
      这只熊有一大串蜂蜜.
      这只肥胖的熊堵在另一扇门前面.
      你是打算去移动那只熊吗?
      你有三个选择:"嘲笑熊"或者"拿走蜂蜜"或者你自己做选择
      """)
      bear_moved = False
      while True:
      choice = input(">")
      if choice == "拿走蜂蜜":
      explain("熊盯着你,然后吃掉你的脸.")
      elif choice == "嘲笑熊" and not bear_moved:
      print("""
      熊离开了门,
      你可以进入门了.
      你有三个选择:"再次嘲笑熊"或者"打开门"或者你自己做选择
      """)
      bear_moved = True
      elif choice == "再次嘲笑熊" and bear_moved:
      explain("熊生气了,吃掉你的腿.")
      elif choice == "打开门" and bear_moved:
      gold_room()
      else:
      print("兄弟,我不懂你的意思!")
      def gold_room():
      print("这里充满了黄金的房间,你打算拿走多少?")
      choice = input(">")
      if "0" in choice or "1" in choice:
      how_much = int(choice)
      else:
      explain("兄弟,记得输入一个数字.")
      if how_much <50:
      print("小伙不错,不贪心,干的漂亮!")
      else:
      explain("你真是个贪婪的混蛋!")
      start()

    习题44 继承与组合

    习题45 你来制作一款游戏

    习题46 项目骨架

    • powershell中输入
    • cd ~
    • py
    • pip list
    • pip install virtualenv
    • mkdir .venvs
    • virtualenv --system-site-packages ..venvs\lpthw
    • ..venvs\lpthw\Scripts\activate (如果报错,打开一个新的POWERSHELL,然后以管理员身份运行,输入代码set-executionpolicy remotesigned,然后选Y即可)
    • pip install nose
    • nosetests
    • pip
    • mkdir projects
    • cd projects
    • mkdir skeleton
    • cd skeleton
    • ls
    • mkdir bin
    • mkdir NAME
    • mkdir tests
    • mkdir docs
    • ls
    • new-item -type file NAME/init.py
    • new-item -type file tests/init.py
    • py
    • import tests
    • import NAME
    • quit()
    • cp C:\Users\43503\lpthw\setup.py
    • ls
    • cat setup.py
    • cp C:\Users\43503\lpthw\NAME_tests.py
    • ls
    • mv NAME_tests.py tests
    • ls
    • setup.py
    • try:
      from setuptools import setup
      except ImportError:
      from distutils.core import setup
      config = {
      'description': 'My project',
      'author': 'My name',
      'url': 'URL to get it at.',
      'download_url': 'where to download it.',
      'author_email': 'My email.',
      'version': '0.1',
      'install_requires': ['nose'],
      'packages': ['NAME'],
      'scripts': [],
      'name': 'projectname'
      }
      setup(**config)
    • NAME_tests.py
    • from nose.tools import *
      import NAME
      def setup():
      print("SETUP!")
      def teardown():
      print("TEAR DOWN!")
      def test_basic():
      print("I RAN!")

    习题47 自动化测试

    习题48 用户输入进阶

    习题49 创建句子

    习题50 你的第一个网站

    习题51 从浏览器中获取输入

    习题52 创建web游戏

    接下来的路

    • 学习多种语言,比如ruby
    • 学习Django web, Scipy, Pygame, Pandas, Natural Language Tool Kit, TensorFlow, Requests, ScraPy,Kivy

    命令行快速入门

    关键字 描述
    pwd 打印计算机工作目录
    hostname 计算机在网络中的名称
    mkdir 创建目录
    ls 列出目录中的内容
    rmdir 删除目录
    pushed 推送目录
    popd 弹出目录
    cp 复制文件或目录
    robocopy 更可靠的复制名利
    mv 移动文件或目录
    more 逐页查看文件
    type 打印整个文件
    forfiles 在一大堆文件上面运行一条命令
    dir -r 寻找文件
    select -string 在文件中查找内容
    help 阅读手册
    helpctr 寻找恰当的手册页面
    echo 打印一些参数
    set 导出/设定一个新的环境变量
    exit 退出shell
    runas 成为超级用户root,危险命令!

    相关文章

      网友评论

        本文标题:【学习笔记,持续更新中】笨办法学python3

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