learn python the hard way

1.first program

print()   #打印

2.comments

# 添加注释,每行一个#

3.number and math

print ("Hens",25+30/6)
print (3+2<5-7)

4.variables and name

cars = 100   #变量赋值
space_in_a_car = 4.0   #变量名可以带"_"

print ("There are",cars,"cars available.")   #打印变量

5.more variables and printing

my_name = 'Zed A.Shaw'

print (f"Let's talk about {my_name}.")   #打印变量的第2种方式

6.string and text

hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print (joke_evaluation.format(hilarious))   #打印变量的第3种方式

# 字符串连接
w = "this is the left side of ..."
e = "a string with a right side."
print (w+e)

7.more printing

print ("."*10)   #小技巧

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.printing,printing

formatter = "{} {} {} {}"

print (formatter.format(1,2,3,4))   #打印变量的第3种方式

9.printing,printing,printing

months = 'Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
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.
       """)   #打印变量的第4种方式

10.what was that?

# 打印单引号或双引号
print ("i am 6'2\" tall.")   
print ('i am 6\'2" tall.')
# 打印缩进
tabby_cat = "\tI'm tabbed in."
# 打印反斜杠
backslash_cat = "I'm \\ a \\ cat."

11.asking questions

print('how old are you?',end='')
age = input()   #从外部输入信息
print(f"so,you're {age} old.")

12.prompting people

# 上一个练习的缩写
age = input("how old are you:")
print(f"you're {age} old")

13.parameters,unpacking,variables

# 引入sys库
from sys import argv
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.prompting and passing

prompts = '>>>>>>>>>>>>>>>>'  #复习
likes = input(prompts)

15.reading files

txt = open(filename)   #打开文件

print(f"here's your file {filename}:")
print(txt.read())   输出文件内容

16.reading and writing files

print("opening the file...")
target = open(filename,'w')   #以写入方式打开文件

print("truncating the file.goodbye!")
target.truncate()   #清空文件内容

target.write(line1)   #写入内容
target.write("\n")

#写入完成,关闭文件
print("and finally,we close it.")
target.close()

扩展:

文件读写


17.more files

in_file = open(from_file)
indata = in_file.read()   #将文件内容读入内存

18.names,variables,code,functions

def print_two(*args):   #如果需要向函数传入多个变量,可以这样
    arg1,arg2,arg3,arg4 = args
    print(f"arg1: {arg1},arg2: {arg2},arg3: {arg3},arg4: {arg4}")

19.functions and variables

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")
    
# 可以向函数传入数值
cheese_and_crackers(20,30)

# 也可以这么传入数值
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)

# 也可以传入公式
cheese_and_crackers(10+20,5+6)

# 也可以传入公式+数值
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)

20.functions and files

def rewind(f):
    f.seek(0)   #指定文件指针位置
    
def print_a_line(line_count,f):     
    print(line_count,f.readline())    #read.line() :从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。

扩展

# 1.seek的用法
seek(offset [,from])方法改变当前文件的位置。
Offset:变量表示要移动的字节数。
From:变量指定开始移动字节的参考位置。
  如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。
  如果设为1,则使用当前的位置作为参考位置。
  如果它被设为2,那么该文件的末尾将作为参考位置

21.functions can return something

def add(a,b):
    print(f"ADDING {a} + {b}")
    return a+b   #退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None

22.what do you know so far

RETURN

23.Strings, Bytes, and Character Encodings

def main(language_file,encoding,errors):
    line = language_file.readline() 
    if line:
        print_line(line,encoding,errors)
        return main(language_file,encoding,errors)   #用RETURN作循环

def print_line(line,encoding,errors):
    next_lang = line.strip()   #移除字符串头尾指定的字符(默认为空格)

24.More Practice

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) # 赋值的数量和返回值的数量一定要一致

25.Even More Practice

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) 

32.Loops and Lists

for i in range(0,6):
    print(f"adding {i} to the list.")
#append is a function that lists understand
    elements.append(i)   # 在列表末尾添加新的对象

34.Accessing Elements of Lists

animals = ['bear','python3.6','peacock','kangaroo','whale','platypus']

print('1.',animals[1])   # 列表

35.Branches and Functions

from sys import exit    
def dead(why):
    print(why,"good job!")
    exit(0)   # sys.exit(0)---正常退出脚本,sys.exit(1)非正常退出脚本

38.Doing Things to Lists

print('  '.join(stuff))   # 将序列中的元素以指定的字符连接生成一个新的字符串
print('#'.join(stuff[3:5]))  #super stellar! 
***
result:
apples oranges crows telephone light sugar boy girl banana
telephone#light

39.Dictionaries, Oh Lovely Dictionaries

cities = {'ca':'san francisco',
          'mi':'detroit',
          'fl':'jacksonville',
        }

# add some more cities
cities['ny'] = 'new york'   # 向字典中增加数据

city = cities.get('mi','does not exist')   # 返回指定键的值,如果值不在字典中返回默认值
print(city)
--->detroit

40.Modules, Classes, and Objects

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)

#print (counter.__secretCount)  # 报错,实例不能访问私有变量
print (counter._JustCounter__secretCount)  # 正确
class A:
   def foo(self):
      print('called A.foo()')
class B(A):
   pass
class C(A):
   def foo(self):
      print('called C.foo()')
class D(B,C):
   pass

if __name__ == '__main__':
   d = D()
   d.foo()


--->called C.foo()

41.Learning to Speak Object-Oriented

for word in urlopen(word_url).readlines():
    words.append(str(word.strip(),encoding = "utf-8"))    # .strip()移除字符串头尾指定的字符(默认为空格)
snippets = list(phrases.keys())   # 以列表返回一个字典所有的键   
class_names = [w.capitalize() for w in random.sample(words,snippet.count("%%%"))]   # .capitalize()首字母大写
        for word in class_names:
            result = result.replace("%%%",word,1)    # 字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

44.Inheritance versus Composition

class Parent(object):
  def altered(self):
    print("PARENT altered()")

class Child(Parent):
  def altered(self):
    print("CHILD, BEFORE PARENT altered()")
    super(Child, self).altered()   # 调用父类的函数
    print("CHILD, AFTER PARENT altered()")

dad = Parent()
son = Child()

dad.altered()
son.altered()

--->
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()
调用父类的第二种方法
class Child(object):
  def __init__(self):
    self.other = Other()    # 调用父类
  def implicit(self):
    self.other.implicit()
  def override(self):
    print("CHILD override()")
  def altered(self):
    print("CHILD, BEFORE OTHER altered()")
    self.other.altered()
    print("CHILD, AFTER OTHER altered()")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容