【學(xué)習(xí)筆記,持續(xù)更新中】笨辦法學(xué)python3

作者 Zed A. Shaw

前言

要點

  • 重視讀寫,注重細(xì)節(jié),發(fā)現(xiàn)不同
  • 少瞅多問,親自動手,刻意練習(xí),耐心實踐
  • 學(xué)習(xí)多種編程語言
  • 會寫不重要,重要的是利用編程語言去解決的問題才重要
  • 建議:撰寫代碼,運行代碼竞阐,破壞代碼,修正代碼医瘫,反復(fù)實踐
  • 習(xí)慣:倒著讀代碼蓖救,為每一行代碼在其上方寫注釋洪规,打印代碼,朗讀代碼
  • 特別提醒,由于markdown顯示的原因,所有代碼沒有換行和縮進(jìn),和書上有區(qū)別,直接黏貼代碼會報錯

習(xí)題0 準(zhǔn)備工作

  • 下載安裝python3,記得關(guān)聯(lián)路徑(Add python3.6 to path),文本編輯器ATOM,或者使用VS CODE
  • 利用powershell(win10自帶)創(chuàng)建目錄,比較重要的命令行有: mkdir 創(chuàng)建目錄,ls查看文件內(nèi)容循捺, cd 更改目錄斩例,特別是退回到上一級采用cd .. , dir 查看, quit() 退出,clear清屏,echo 創(chuàng)建txt文件, cat查看文件从橘, rm 刪除文件
  • 學(xué)習(xí)python不要依賴自帶的IDLE,而要習(xí)慣利用文本編輯器,命令行終端,以及python軟件.
  • 習(xí)題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.')

習(xí)題1 打印

print 打印念赶,有兩種方式,一種是逐行打印恰力,一種是多行同時打印

  • print("內(nèi)容")叉谜,雙引號+print
  • print(''''''內(nèi)容'''''),'三引號+print
    我們需要再windows 下的powershell中運行,具體是 python ex1.py牺勾,當(dāng)遇到語法錯誤的時候正罢,即現(xiàn)時SyntaxError時,把錯誤復(fù)制到搜索引擎驻民,取尋找到答案.
  • 習(xí)題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.")

習(xí)題2 注釋

  • # 英文名是 octothorpe翻具,其作用是注釋或者臨時禁用一段代碼
  • 如果是字符串中,出現(xiàn)#回还,是不會被忽略的裆泳,比如:print("Hi # is here"),這時候只是一個普通字符.
  • EOF語法錯誤: End Of File
  • 習(xí)題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.")

習(xí)題3 數(shù)學(xué)符號和數(shù)字類型

  • 常見的數(shù)學(xué)運算符號
    +,-柠硕,*工禾,/,//蝗柔,%闻葵,<,>,<=,>=,==
  • 整數(shù) 3 ,而浮點數(shù) 3.0 癣丧,相應(yīng)函數(shù) int(), float()
  • print函數(shù)返回的數(shù)學(xué)計算式的布爾值
  • 習(xí)題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)

習(xí)題4 變量和命名

  • 變量:指代某個東西的名字槽畔,可以采取字母,數(shù)字胁编,下劃線去命名,通常采用 cars = 100 的方式
  • print 函數(shù)有常見的引用變量的方式厢钧,引用變量要用逗號隔開,操作符兩邊用逗號隔開更容易閱讀
  • ATOM中,ctrl+t可以調(diào)用文件列表
  • 習(xí)題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.")

習(xí)題5 更多的變量和打印

  • 可以利用ctrl + F 查找和替換
  • round() 函數(shù)可以將浮點數(shù)四舍五入
  • f"Let's talk about {my_name}." 格式化打印,稱之為f字符串
  • 習(xí)題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}.")

習(xí)題6 字符串和文本

  • w+e 是串聯(lián)字符串的一種方法
  • 利用print()函數(shù)調(diào)試代碼
  • 習(xí)題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)

習(xí)題7 連接字符串

  • 格式化字符 .format() ,需要預(yù)先在變量后加{}
  • 兩個字符用 + 號鏈接可以生成更長的字符
  • end=' ' 是告訴系統(tǒng)不要換行,注意習(xí)題7 end= ' ',單引號之間存在空格的
  • 習(xí)題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)

習(xí)題8 打印,打印

  • 利用.format()函數(shù)實現(xiàn),format()函數(shù)可以傳遞多個參數(shù),需要與formatter中的{}數(shù)量匹配,但是并非一定要完全相同嬉橙,參數(shù)數(shù)量不能少于{}數(shù)量
  • "one"是字符串需要加引號,而True和False是關(guān)鍵字不需要加
  • 習(xí)題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"
    ))

習(xí)題9 打印,打印,打印

  • \n 稱之為轉(zhuǎn)義字符早直,用于實現(xiàn)換行
  • 利用三引號可以直接輸入多行,無需額外換行符
  • 習(xí)題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.
    """)

習(xí)題10 那是什么

  • "\n"轉(zhuǎn)義字符,用于展示一些特別的符號,在字符串中市框,轉(zhuǎn)義字符也可以識別出
  • 習(xí)題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)
  • 字符串轉(zhuǎn)義序列
關(guān)鍵字 描述
\\ 反斜杠
\' 單引號
\" 雙引號
\a 響鈴
\b 退格符
\f 進(jìn)紙符
\N{name} Unicode數(shù)據(jù)庫中的字符名霞扬,其中name是它的名字,僅Unicode適用
\n 換行符
\r 回車符(CR)
\t 水平制表符(TAB)
\v 垂直制表符(VT)

習(xí)題11 提問

  • 軟件一般做的三件事:接受輸入的內(nèi)容枫振,改變輸入的內(nèi)容喻圃,打印出改變的內(nèi)容
  • print("How old are you?",end='')
  • age = input() ,input()是輸入函數(shù),input()函數(shù)輸入內(nèi)容必須從命令行得到,對于輸入內(nèi)容是整數(shù),可以利用int()函數(shù)轉(zhuǎn)換輸入內(nèi)容,比如age = int(input())
  • repr()呈現(xiàn)函數(shù),可以查看數(shù)據(jù)的類型,如果是字符串,打印時會有引號
  • 習(xí)題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.")

習(xí)題12 提示別人

  • 變量名 = input("可以添加提示內(nèi)容:")
  • 后面也可以采取提示符的方式提示
  • 習(xí)題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.")

習(xí)題13 參數(shù)蒋得、解包和變量

  • import 引入模塊 module
  • sys 就是一個模塊
  • argv 參數(shù)變量,保存著python運行時级及,傳遞給python腳本的參數(shù)
  • script 腳本名稱,系統(tǒng)自帶的變量
  • script,first,second,third = argv 解包额衙,將參數(shù)賦值給4個變量
  • argv是在執(zhí)行命令時就要輸入,input()是在腳本運行過程中用戶輸入
  • 習(xí)題13:ex13.py
  • 用戶執(zhí)行命令時饮焦,用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)

習(xí)題14 提示和傳遞

  • prompt = '>' 利用> 進(jìn)行提示,告知這個地方需要輸入,這個提示符可以修改成自己喜歡的字符
  • lives = input (prompt)
  • 習(xí)題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.
    """)

習(xí)題15 讀取文件

  • 通過argv獲取文件名并賦值給filename
  • 通過txt= open(filename) 獲取"file object"(文件對象)县踢,而非內(nèi)容
  • 因此txt.read()讀取文件對象中的內(nèi)容

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.

  • 習(xí)題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())

習(xí)題16 讀寫文件

  • read: 讀取文件的內(nèi)容, r+表示讀寫
  • readline:讀取文件中的一行內(nèi)容
  • close:關(guān)閉文件
  • truncate: 清空文件,小心使用該命令
  • seek(0): 將讀寫位置移動到文件開頭
  • write('stuff'): 將'stuff'寫入文件
  • append(' stuff'): 追加'stuff' , a+ 用于讀寫
  • 本例子中 target = open(filename,'w') 中伟件,w打開一個文件只用于寫入硼啤。如果該文件已存在則將其覆蓋。如果該文件不存在斧账,創(chuàng)建新文件谴返。此外:w+則表示讀寫
  • 基本使用方法,沿著如下路線:open---read---close
  • 習(xí)題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()

習(xí)題17 更多文件操作

  • 模塊 os.path 參數(shù) exists
  • 題目中的格式是 print(f"Does the output file exist?{exists(to_file)}") 返回的是布爾值煞肾,如果文件存在,則返回True嗓袱,否則False
  • len( ) 返回文本長度
  • 使用close()函數(shù)是為了避免資源浪費甚至耗盡
  • echo函數(shù)生產(chǎn)txt文件的方法,在中文環(huán)境下可能會產(chǎn)生問題,因此,用VS CODE生成txt文件更好
  • 習(xí)題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()

習(xí)題18 命名籍救、變量、代碼和函數(shù)

  • 函數(shù)用def開頭
    -函數(shù)名用字母數(shù)字和下劃線組成渠抹,數(shù)字不可以開頭
  • 函數(shù)名必須帶小括號
  • 小括號內(nèi)不一定要有參數(shù)蝙昙,參數(shù)與參數(shù)之間用逗號隔開,也可以用*args將參數(shù)放到名為args的列表中去
  • 括號后緊跟冒號:
  • 使用TAB或者四個空格縮進(jìn)
  • 運行函數(shù)梧却,調(diào)用函數(shù)奇颠,使用函數(shù)是一個意思
  • 習(xí)題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()

習(xí)題19 函數(shù)和變量

  • 函數(shù)里的變量和腳本里的變量之間是沒有聯(lián)系,一個是局部變量,另一個是全局變量,盡可能讓局部變量和全局變量名稱不一樣,盡管不會影響
  • 函數(shù)中的變量盡量不超過5個,函數(shù)中可以調(diào)用函數(shù)
  • 習(xí)題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)

習(xí)題20 函數(shù)和文件

  • 定義一個函數(shù)來讀取文件,理解函數(shù)和文件是如何一起協(xié)作的
  • readline()讀取一行
  • 習(xí)題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)

習(xí)題21 函數(shù)可以返回某些東西

  • 函數(shù)利用命令return 返回值,print函數(shù)的返回值為None
    -復(fù)合函數(shù)要有內(nèi)部到外部讀取
  • 習(xí)題21:ex21.py
    def add(a,b):
    print(f"ADDING {a} + 放航")
    return a + b
    def subtract(a, b):
    print(f"SUBTRACTING {a} - 烈拒")
    return a - b
    def multiply(a, b):
    print(f"MULTIPLING {a} * ")
    return a * b
    def divide(a, b):
    print(f"DIVIDING {a} / 三椿")
    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?")

習(xí)題22 到現(xiàn)在為止你學(xué)到什么

  • 復(fù)習(xí):記下每個詞和每一個符號缺菌,在每一個關(guān)鍵字后面寫出它的名字,并說明作用搜锰,遇到找不到答案的東西伴郁,先記下來,等下次遇到再找蛋叼,等列表做好后過幾天重再做列表
  • 學(xué)會了輸入input和輸出print, 學(xué)會注釋#, 學(xué)會了提問和提示別人
  • 學(xué)會了通過變量和命名,學(xué)會了利用變量存儲數(shù)據(jù)
  • 學(xué)會計算操作,學(xué)會了格式化字符串,f字符換,和format()函數(shù)
  • 學(xué)會如何使用轉(zhuǎn)義字符
  • 學(xué)到模塊sys, os.path, 明白了什么是參數(shù),解包和變量
  • 掌握了如何讀取文件的基本步驟:OPEN-READ-WRITE-CLOSE
  • 掌握了函數(shù)的命名,如何定義參數(shù),以及如何返回值return,知道了什么是全局變量,什么是局部變量
  • 習(xí)題22:ex22.py

習(xí)題23 字符串焊傅、字節(jié)串和字符編碼

  • 需要理解的四個方面:
    計算機(jī)是如何存儲人類語言的,計算機(jī)的字符串的編碼和字節(jié)串的解碼,如何處理字符串和字節(jié)處理中的出現(xiàn)的錯誤,如何閱讀代碼
  • 計算機(jī)根本上是一個巨大的開關(guān)列陣,通過電來觸發(fā)開關(guān),用數(shù)字1表示有電和開啟,用數(shù)字0表示沒電和關(guān)閉,而數(shù)字1和0被稱之為位; 8位序列被稱之為字節(jié)
  • ASCII:American Standard Code For Imformation Interchange ;Unicode:萬國碼
  • 編碼字符串,解碼字節(jié)串
  • main()函數(shù)有三個參數(shù),第一個參數(shù)是文件狈涮,第二個參數(shù)是編碼方式:utf-8狐胎,第三個編碼要求是:strict,利用open函數(shù)讀取文件內(nèi)容歌馍,并復(fù)制給languages獲得第一個參數(shù)握巢, 第二個參數(shù)和第三個參數(shù)利用argv解包得到
  • if line:是用來判斷語句是否存在,后面接著跟著兩個函數(shù)松却,一個是打印行的自定義函數(shù)暴浦,一個是調(diào)用main函數(shù)本身
  • print_line函數(shù)有三個參數(shù),一個參數(shù)是從主函數(shù)main得到的參數(shù)line晓锻,后面兩個仍然是之前通過argv得到的兩個參數(shù)歌焦,strip()函數(shù)用于刪除結(jié)尾的換行符\n,15和16分別用來編碼字符串和解碼字節(jié)串砚哆,其邏輯是通過編碼字符串得到字節(jié)串独撇,然后解碼字節(jié)串得到字符串。18行直接打印對比的字節(jié)串和字符串
  • 21行打開文件,編碼方式是utf-8,23行是調(diào)用主函數(shù).
  • 習(xí)題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)

習(xí)題24 更多的練習(xí)

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))

習(xí)題25 更多更多的練習(xí)

  • 定義函數(shù)纷铣,利用import調(diào)用函數(shù)文件学赛,在IDLE中實現(xiàn)交互式操作
  • 結(jié)束需要用quit()來實現(xiàn)
  • 習(xí)題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)

習(xí)題26 恭喜你浪蹂,現(xiàn)在可以考試了

  • 代碼下載地址
  • 習(xí)題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.")

習(xí)題27 記住邏輯關(guān)系

  • 布爾操作符: 與and,或or,非not
  • 比較操作符: 不等于!=,等于==,大于或等于>=,小于或等于<=
  • 布爾值:真True,假False
  • 習(xí)題27:ex27.py

習(xí)題28 布爾表達(dá)式練習(xí)

  • 順序:比較操作符---布爾二元操作符---NOT---找到剩下的and/or武花,解出它們的值
  • 習(xí)題28:ex28.py

習(xí)題29 if語句

  • if語句是控制流程語句型型,判斷真假班缰,if使用時匈睁,if + 條件 + :
  • 判斷語句的下一行要縮進(jìn)四個空格蹬碧,類似于目錄
  • x += 1 <===> x = x+1 皇筛,我們稱之為遞增運算符
  • 習(xí)題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.")

習(xí)題30 else和if

  • 習(xí)題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.")

習(xí)題31 作出決定

  • IF語句中可以嵌套IF語句
  • 改進(jìn)提示prompt = ">"
  • 比較操作符 == 是兩個等號
  • 習(xí)題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!")

習(xí)題32 循環(huán)和列表

  • 創(chuàng)建列表 hairs = {'brown', 'blond', 'red'}
  • 空列表 [], append()函數(shù)用于列表尾部追加元素
  • for循環(huán)開始的變量就直接被定義了色鸳,for i in range(1,3)支循環(huán)兩次的原因是這是一個半閉半開去間社痛,從第一個數(shù)開始,最后一個數(shù)不執(zhí)行
  • 二位列表 [[1, 2, 3], [4, 5, 6]]
  • 習(xí)題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}")

習(xí)題33 while循環(huán)

  • while 循環(huán)又稱為無限循環(huán)命雀,直到出現(xiàn)False才會結(jié)束
  • 三個原則:盡量少用while 循環(huán)蒜哀,大部分時候for更好; 重復(fù)檢查你的while語句吏砂,測試布爾表達(dá)式最后會變?yōu)镕alse撵儿; 如果不確定, 就在while 循環(huán)的開始和結(jié)尾打印出你要測試的值狐血,看看它的變化
  • 習(xí)題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)

習(xí)題34 訪問列表的元素

  • 序數(shù):有順序的數(shù)字,從1開始; 基數(shù):隨機(jī)選取的數(shù),用于找到位置,從0開始
  • 基礎(chǔ) = 序數(shù) - 1
  • 習(xí)題34:ex34.py

習(xí)題35 分支和函數(shù)

  • 用思維導(dǎo)圖制作一個流程圖淀歇,要點是明確是串聯(lián)還是并聯(lián)
  • 這個分支與函數(shù)是后面ex42的前身
  • 習(xí)題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()

習(xí)題36 設(shè)計和調(diào)試

  • if 語句的規(guī)則
  1. 每一條if語句必須包含一個else
  2. 如果這個else永遠(yuǎn)都不應(yīng)該被執(zhí)行到,因為它本身沒有任何意義匈织,那么必須再else語句后面使用一個叫做die的函數(shù)浪默,讓它打印出出錯消息,并且”死“給你看缀匕,這和上一個習(xí)題類似纳决,這樣你可以找到很多的錯誤,PS:老肖真會開玩笑
  3. if語句的嵌套不要超過兩層乡小,盡量保持只有一層
  4. 將if語句當(dāng)作段落來對待阔加,期中的每一個if-elif-else組合就跟一個段落的句子組合一樣,再這種組合的最前面和最后面留一個空行用以區(qū)分
  5. 你的不二測試應(yīng)該很簡單满钟,如果它們很復(fù)雜胜榔,你需要在函數(shù)里將它們的運算事先放到一個變量里,給變量取一個好名字
  • 循環(huán)的規(guī)則
  1. 只有在循環(huán)永不停止時使用”while“循環(huán)零远,這意味著你可能永遠(yuǎn)都用不到苗分。這一條只有在python中成立,其他語言另當(dāng)別論
  2. 其他類型的循環(huán)都使用for循環(huán)牵辣,尤其是在循環(huán)的對象數(shù)量固定或者有限的情況下.
  • 調(diào)試的小技巧
  1. 不要使用”調(diào)試器“(debugger)摔癣。調(diào)試器所作的相當(dāng)于對病人進(jìn)行全身掃描。你并不會得到某方面的有用信息,而且你會發(fā)現(xiàn)他輸出的信息太多择浊,而且大部分沒有用戴卜,或者只會讓你更困惑。
  2. 調(diào)試程序的最好的方法是使用print在各個想要檢查的關(guān)鍵點將變量打印出來琢岩,從而檢查那里是否有錯
  3. 讓程序一部一部分地運行起來投剥。不要等寫了一大堆代碼文件后采取運行它們,寫一點兒担孔,運行一點江锨,再修改一點兒。
  • 寫軟件最好的方法
  1. 再紙上或者索引卡上列出你要完成的任務(wù)糕篇,這就是你的待辦任務(wù)
  2. 從中挑出最簡單的任務(wù)
  3. 在源代碼文件中寫下注釋啄育,作為你完成任務(wù)代碼的指南
  4. 在注釋下面寫一些代碼
  5. 快速運行你的代碼,看它是否工作
  6. 循環(huán)”寫代碼拌消,運行代碼進(jìn)行測試挑豌,修正代碼”的過程
  7. 從任務(wù)列表中劃掉這條任務(wù),跳出下一個最簡單的任務(wù)墩崩,重復(fù)上述步驟氓英。

習(xí)題37 復(fù)習(xí)各種符號

關(guān)鍵字

關(guān)鍵字 描述 示例
and True and False == False
as with-as 語句的一部分 with X as Y:pass
assert 斷言某東西為真 assert False, 'Error!'
break 立即停止循環(huán) while True: break
class 定義類 class Person(object)
continue 停止當(dāng)前循環(huán)的后續(xù)步驟,再做一次循環(huán) While True:continue
def 定義函數(shù) 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 如果發(fā)生異常,運行此處代碼 except ValueError,e:print(e)
exec 將字符串作為python腳本運行 exec'print('Hello')'
finally 不管是否發(fā)生異常盛龄,都運行此處代碼 finally:pass
for 針對物件集合執(zhí)行循環(huán) for X in Y:pass
from 從模塊中導(dǎo)入特定部分 from X import Y
global 聲明全局變量 global X
if if條件 if:X; elif: Y;else:J
import 將模塊導(dǎo)入當(dāng)前文件以供使用 import os
in for循環(huán)一部分饰迹,也可以判斷x是否在y中 fro X in Y:pass 以及1 in [1] == True
is 類似于==,判斷是否一樣 1 is 1 == True
lambda 創(chuàng)建短匿名函數(shù) 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 出錯后引發(fā)異常 raise ValueError("No")
return 返回值并且退出函數(shù) def X(): return Y
try 嘗試執(zhí)行代碼余舶,出錯后轉(zhuǎn)到except try: pass
while while循環(huán) while X: pass
with 將表達(dá)式作為一個變量啊鸭,然后執(zhí)行代碼塊 with X as Y : pass
yield 暫停函數(shù),返回到調(diào)用函數(shù)的代碼中 def X(): yield Y; X().next()

數(shù)據(jù)類型

關(guān)鍵字 描述 示例
True True of Flase ==True
False False and True == False
None 不存在匿值,沒有值 x == None
bytes 字節(jié)存儲值 x = b'hello'
strings 存儲文本信息 x ='hello'
numbers 存儲整數(shù) i = 100
Floats 存儲十進(jìn)制數(shù) i= 10.389
lists 存儲列表 j = [1,2,3,4]
dicts 存儲鍵-值映射 e = {'x': 1, 'y':2 }
  • 閱讀代碼的一些要求
  1. 打印代碼赠制,大腦更偏愛紙質(zhì)內(nèi)容
  2. 筆記涵蓋內(nèi)容方面要求
  • 函數(shù)以及函數(shù)的功能
  • 每個變量初始賦值的位置
  • 每個在程序的各個部分中多次出現(xiàn)的同名變量。它們以后可能會給你帶來麻煩
  • 任何不包含else子句的if語句挟憔。它們是正確的嘛钟些?
  • 任何可能沒有結(jié)束點的while循環(huán)
  • 代碼中任何你看不懂的部分
  1. 自己寫注釋節(jié)是代碼,節(jié)是各個函數(shù)的使用方法绊谭,各個變量的用途政恍,以及任何其他方面的內(nèi)容
  2. 代碼中比較難的各個部分,逐行或者逐個函數(shù)跟蹤變量值达传,再打印一份出來篙耗,在代碼空白處寫出> 要“追蹤”的每個變量的值
  3. 一旦理解了代碼的功能迫筑,回到計算機(jī)前,在屏幕上重讀一次宗弯,看看能不能找到新的問題點脯燃,然后繼續(xù)新的代碼,用上述方法閱讀理解蒙保,直到你不再需要紙質(zhì)打印為止

習(xí)題38 列表的操作

  • 有序的列表
  • 要存儲的東西
  • 隨機(jī)訪問
  • 線性
  • 通過索引
  • spilt()函數(shù)是將字符串按照指定的格式分開成列表辕棚,join()函數(shù)是將列表按照指定的格式變成字符串
  • pop()函數(shù)將列表最后一個元素刪除,并且返回最后一個元素
  • 習(xí)題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!

習(xí)題39 字典邓厕,可愛的字典

  • Python 字典 items() 方法以列表返回可遍歷的(鍵, 值) 元組數(shù)組逝嚎。
  • Python 列表 list() 創(chuàng)建列表
  • Python 字典 get() 函數(shù)返回指定鍵的值,如果值不在字典中返回默認(rèn)值懈糯。
  • 習(xí)題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}")

習(xí)題40 模塊、類和對象

  • 模塊類似于字典的映射概念她紫,是一種將一種東西對應(yīng)到另外一種的方式
  • 模塊包含函數(shù)和變量的python文件,可以導(dǎo)入這個文件渐逃,然后可以使用操作符訪問模塊中的函數(shù)和變量
  • python一個非常常用的模式,即拿一個類似“鍵=值”風(fēng)格的容器民褂,通過”鍵“的名稱獲取期中的”值"
  • 類就像一種藍(lán)圖或者一種預(yù)定義的東西面殖,通過它可以創(chuàng)建新的迷你模塊
  • 實例化的過程相當(dāng)于你創(chuàng)建了這么一個迷你模塊脊僚,而且同時導(dǎo)入了它辽幌。”實例化“的意思就是從類創(chuàng)建一個對象
  • 結(jié)果創(chuàng)建的迷你模塊就像是一個對象加酵,你可以將它賦給一個變量后供后續(xù)操作
  • 類的工作原理
  1. python 查找MyStuff()并且知道它是一個定義過的類
  2. python創(chuàng)建了一個空對象虽画,里面包含了你在該類中用def指定的所有函數(shù)
  3. python回去檢查你是不是創(chuàng)建了一個init函數(shù)渗柿,如果有創(chuàng)建朵栖,它就會調(diào)用這個函數(shù),從而對你新創(chuàng)建的空對象實現(xiàn)了初始化
  4. 在MyStuff的init函數(shù)里门扇,有一個多余的函數(shù)教self,這就是python為你創(chuàng)建的空對象吉拳,而你可以對它進(jìn)行類似模塊,字典等的操作炼邀,為它設(shè)置一些變量
  • 習(xí)題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()

習(xí)題41 學(xué)習(xí)面向?qū)ο笮g(shù)語

專有詞匯練習(xí)

  • 類(class):告訴python創(chuàng)建新類型的東西
  • 對象(object):兩個意思,即最基本的東西红淡,或者某樣?xùn)|西的實例
  • 實例(instance):這是讓python創(chuàng)建一個類時得到的東西
  • def:則會使類里定義函數(shù)的方法
  • self:在類的函數(shù)中,self指代被訪問的對象或者實例的一個變量
  • 繼承(inheritance): 指一個類可以繼承另一個類的特性桶蝎,和父子關(guān)系類似
  • 組合(composition):指一個類可以將別的類作為它的部件構(gòu)建起來噪服,有點像車子和車輪的關(guān)系
  • 屬性(attribute):類的一個屬性粘优,它來自于組合,而且通常是一個變量
  • 是什么(is-a): 用來描述繼承關(guān)系嬉愧,如Salmon is-a Fish
  • 有什么(has-a):某個東西有某特征,如Salmon has-a mouth四康,或用來描述某個東西是由另外一些東西組成
  • 措辭練習(xí)
  • class X(Y): 創(chuàng)建一個叫X的類疯溺,它是Y的一種
  • class X(object): def__init__(self,J): 類X有一個_init_, 它接收self和J作為參數(shù)
  • class X(object): def M(self,J): 類X有一個名為M的函數(shù)囱嫩,它接收self和J作為參數(shù)
  • foo = X(): 將foo設(shè)為類X的一個實例
  • foo.K = Q: 從foo中獲取K屬性今妄,并將其設(shè)為Q
  • foo.M(J): 從foo中找到M的函數(shù),并使用self和J參數(shù)調(diào)用它
  • 習(xí)題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")

習(xí)題42 對象套利、類及從屬關(guān)系

  • 類(class):用來描述具有同類蘇還行的實例的概括性的詞匯
  • 對象(object):具有類屬性的具體、真實的東西
  1. 類比: 魚---泥鰍---小麗 <===> 類---(子)類---實例
  2. 區(qū)分方法:is-a (是什么) 用在談?wù)?兩者以類的關(guān)系互相關(guān)聯(lián)"的時候 , has-a (有什么) 用在兩者無共同點,僅相互參照的時候. 比如: 是什么討論魚和泥鰍的關(guān)系, 有什么 討論的是泥鰍和鰓的關(guān)系.
  • 習(xí)題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()

習(xí)題43 基本的面向?qū)ο蠓治龊驮O(shè)計

  • 自頂向下流程:從抽象的概念入手,逐漸細(xì)化,知道概念變成具體的可用代碼實現(xiàn)的東西
  1. 把要解決的問題寫下來,或者畫出來
  2. 將第一條中的關(guān)鍵概念提取出來并加以研究
  3. 創(chuàng)建一個類層次結(jié)構(gòu)和對象圖
  4. 用代碼實現(xiàn)各個類,并寫一個測試來運行它們
  5. 重復(fù)上述步驟并細(xì)化代碼
  • 克蘇魯?shù)姆块g


    分支與選擇--python函數(shù)流程圖.png
  • 老肖整理的類層次結(jié)構(gòu)圖
  • MAP
    ** NEXT_SCENE
    ** OPENING_SCENE
  • ENGINE
    ** PLAY
  • SCENE
    ** ENTER
    ** DEATH
    ** CENTRAL OF CORRIDOR
    ** THE BRIDGE
    ** LASER WEAPON ARMORY
    ** ESCAPE POD
  • 克蘇魯?shù)姆块g中文版
    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("""
    熊離開了門虱颗,
    你可以進(jìn)入門了.
    你有三個選擇:"再次嘲笑熊"或者"打開門"或者你自己做選擇
    """)
    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("兄弟鸣驱,記得輸入一個數(shù)字.")
    if how_much <50:
    print("小伙不錯,不貪心,干的漂亮!")
    else:
    explain("你真是個貪婪的混蛋!")
    start()

習(xí)題44 繼承與組合

習(xí)題45 你來制作一款游戲

習(xí)題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!")

習(xí)題47 自動化測試

習(xí)題48 用戶輸入進(jìn)階

習(xí)題49 創(chuàng)建句子

習(xí)題50 你的第一個網(wǎng)站

習(xí)題51 從瀏覽器中獲取輸入

習(xí)題52 創(chuàng)建web游戲

接下來的路

  • 學(xué)習(xí)多種語言联喘,比如ruby
  • 學(xué)習(xí)Django web叭喜, Scipy, Pygame, Pandas, Natural Language Tool Kit, TensorFlow, Requests, ScraPy,Kivy

命令行快速入門

關(guān)鍵字 描述
pwd 打印計算機(jī)工作目錄
hostname 計算機(jī)在網(wǎng)絡(luò)中的名稱
mkdir 創(chuàng)建目錄
ls 列出目錄中的內(nèi)容
rmdir 刪除目錄
pushed 推送目錄
popd 彈出目錄
cp 復(fù)制文件或目錄
robocopy 更可靠的復(fù)制名利
mv 移動文件或目錄
more 逐頁查看文件
type 打印整個文件
forfiles 在一大堆文件上面運行一條命令
dir -r 尋找文件
select -string 在文件中查找內(nèi)容
help 閱讀手冊
helpctr 尋找恰當(dāng)?shù)氖謨皂撁?/td>
echo 打印一些參數(shù)
set 導(dǎo)出/設(shè)定一個新的環(huán)境變量
exit 退出shell
runas 成為超級用戶root,危險命令!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市陨瘩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌甚淡,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異睁枕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)跳仿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人佩憾,你說我怎么就攤上這事楞黄。” “怎么了桑阶?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我虐杯,道長,這世上最難降的妖魔是什么达舒? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上丈甸,老公的妹妹穿的比我還像新娘得湘。我一直安慰自己摆马,他們只是感情好囤采,可當(dāng)我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著进肯,像睡著了一般。 火紅的嫁衣襯著肌膚如雪环形。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼刃鳄。 笑死,一個胖子當(dāng)著我的面吹牛愉烙,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播遂鹊,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了吨娜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后身辨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绎晃。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡擎勘,死狀恐怖煤裙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情菠秒,我是刑警寧澤豹障,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站焦匈,受9級特大地震影響血公,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缓熟,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望够滑。 院中可真熱鬧垦写,春花似錦、人聲如沸版述。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽渴析。三九已至晚伙,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間俭茧,已是汗流浹背咆疗。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留母债,地道東北人午磁。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓尝抖,卻偏偏與公主長得像,于是被迫代替她去往敵國和親迅皇。 傳聞我的和親對象是個殘疾皇子昧辽,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,611評論 2 353