第1章 什么是 Python?
# Python——编程新手最好的选择
第2章 为 Python 做好准备
# 单行注释 打印出单词 "Hello World"
print("Hello World")
''' 多行注释
这是一条注释
这也是一条注释
'''
print("Hello Python")
第3章 变量和操作符的世界
- 3.1 定义变量
userAge, userName = 16, 'saber' """ <==> userAge = 16, userName = 'saber' <==> userAge = 16 userName = 'saber' """
- 3.2 命名变量
与 C 一致: 1. 字母数字下划线; 2. 不能为关键字; 3. 区分大小写; 命名规则举例: 1. 驼峰式: ThisIsAVariableName 2. 下划线式: this_is_a_variable_name
- 3.3 赋值符号
x = 8 y = 2 x = y print("x =",x) # x = 2 print("y =",y) # y = 2
- 3.4 基本操作符
+ - * / // % ** 加法 减法 乘法 除法 整除 取余 指数 x = 5 y = 2 print("x+y =",x+y) # x+y = 7 print("x-y =",x-y) # x-y = 3 print("x*y =",x*y) # x*y = 10 print("x/y =",x/y) # x/y = 2.5 print("x//y =",x//y) # 向下取整 x//y = 2 print("x%y =",x%y) # x%y = 1 print("x**y =",x**y) # x**y = 25 print('100 + 200 =', 100 + 200, 1-2, 10/3, 10//3, 10%3, 2*3, 2**10)
- 3.5 更多的分配操作符
+= -= *=
第4章 Pyhon 中的数据类型
-
4.1 整数类型
int
print(123_456_578, 0x1011_0010, 0xFFBC_9890, -9, 0)
-
4.2 浮点类型
float
print(-18.579, 1.974e6, 1.4e-8, 124.089_743_572_903_8)
-
4.3 字符串
str
userName = 'peter', userSpouseName = "Janet", usrAge = '30' # 字符串中使用 "" 或 '' 都可以,但必须配对使用,不能 ' " 单独使用 # 可以使用 + 连接多个字符串 print("I love"+" Saber"+" forever!") # "I love Saber forever!" print('alice', "I'm Bob.", '\t hello, Eve', 'How are you? I\'m fine, thanks!', '\\\n\\\\%', r'\\\n\\\\t\\\b\\', ''' line1, line2, line3''', "'Hello, world'", "'hello,\\\'Adam\\\''", "r\'hello,\"Bart\"\'")
- 4.3.1 内建的字符串函数
'excalibur'.upper() # 将字符串中每一个字符都转化为大写
- 4.3.2 使用
%
操作符格式化字符串# 格式化输出 age = 12 location = 'Xi\'an, Shaanxi' price = 9.962 rate = 0.23528 print('I\'m %d years old, and I come from %s. The price of the book is $%.2f, its increase rate is %.1f %%' % (age, location, price, rate*100) ) # I'm 12 years old, and I come from Xi'an, Shaanxi. The price of the book is $9.96, its increase rate is 23.5 % # 引号内编写要格式化的字符串,写出% 使用一对小括号,括号内写上要插入字符串的值或变量 # 这对包含值的小括号事实上叫做——元组 %d %f %s 宽度,保留小数位数等与 C 一致 brand = 'Apple' exchangeRate = 1.235235344 message = 'The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR' %(brand, 1299, exchangeRate) print(message) # The price of this Apple laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR
- 4.3.3 使用
format()
方法格式化字符串message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1 EUR'.format("Apple", 1299, 1.4354351) print(message) # The price of this Apple laptop is 1299 USD and the exchange rate is 1.44 USD to 1 EUR message = 'The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR'.format("Apple", 1299, 1.4354351) print(message) # The price of this Apple laptop is 1299 USD and the exchange rate is 1.4354351 USD to 1 EUR message1 = '{0} is easier than {1}'.format("Python",'Java') message2 = '{1} is easier than {0}'.format("Python","Java") message3 = '{:10.2f} and {:d}'.format(1.23454545,12) message4 = '{}'.format(1.233455644) print(message1) # Python is easier than Java print(message2) # Java is easier than Python print(message3) # 1.23 and 12 print(message4) # 1.233455644
- 4.3.1 内建的字符串函数
-
4.4 Python 中的类型转换
# Python中的三个内建函数 int() float() str() print(int(2.34)) # 2 print(int("4654")) # 4654 print(int(8)+6) # 14 print(float(6+7)) # 13.0 print(float("85438.443")) # 85438.443 print(float("5")) # 5.0 print(str(6)) # 6 print(str(9.56)+"dfjgh") # 9.56dfjgh print(str("534fdf")) # 534fdf
-
4.5 列表
list
# list # a. 使用中括号[] # b. 索引从0开始,最后一个元素为-1,倒数第二为-2 依此类推 # c. 1:5叫做切片,它总是包括开始索引的元素,而不包括结尾索引的元素 1:5表示从索引1到索引4 = 5-1 # d. 切片第三个数字叫做步长 [1:5:2]从索引位置1~4=5-1 中每隔一个数字的子列表,故步长为2 # e. 若不指定则默认:第一个数字为0,第二个数字为列表长度 [:4]表示0~3 [2:]表示2~4 总长为5,共有5个元素 linlee = ['Michael', 123, 'Bob', [99.98, '$'], 'Tracy', True] print(linlee, len(linlee), type(linlee) ) print(linlee[-1], linlee[0], linlee[1], linlee[3], len(linlee[3]), linlee[3][1]) linlee.append('Adam') # 追加元素到列表末尾 print(linlee) linlee.insert(1,'Jack') # 插入元素到列表指定位置 print(linlee) linlee.pop() # 删除列表末尾元素 print(linlee) linlee.pop(1) # 删除列表第二个元素 print(linlee) linlee[1] = 'Sarah' # 修改列表中指定元素 print(linlee)
-
4.6 元组
tuple
# tuple 不可变更的 list month = ("Jan","Feb","Mar") classmates = ('Alice', 99.9, 'Bob', False, 'Eve', 0) print(classmates, len(classmates), type(classmates)) t1 = () # 空 tuple t2 = (1,) # 仅有一个元素 1 的 tuple t3 = (1) # <==> t3 = 1 不是 tuple print(t1, t2, t3, type(t1), type(t2), type(t3), len(t1), len(t2)) # "可变的" tuple t4 = ('a', 'b', ['A', 'B']) print(t4) t4[2][0] = 'X' print(t4) # 检索 name = ( ('Apple', 'Google', 'Microsoft'), ('Java', 'Python', 'Ruby', 'PHP'), ('Adam', 'Bart', 'Lisa') ) print(name[0][0]) print(name[1][1]) print(name[2][2])
-
4.7 字典
dict
list dict 查找插入时间随元素增加而增加 查找插入快,与元素多少无关 内存占用小 内存占用多 元素可以重复 key 不允许重复 userNameAndAge = {"peter":34,"John":42,"Saber":16,"Archer":"Not Available"} userNameAndAge = dict(peter=34,John=42,Saber=16,Archer="Not Available") # dict name_to_score = {'Alice':95, 'Bob':99, 'Eve':92} print(name_to_score['Bob']) print('Thomas' in name_to_score) # 检查 'Thomas' 是否存在 print(name_to_score.get('Thomas')) # 检查 'Thomas' 是否存在, 不存在时返回 None name_to_score.pop('Bob') # 删除 key
-
4.8 集合
set
# set s1 = set([1, 2, 3, 3, 2, 1]) s2 = set([3, 4, 5, 1, 1]) s1.add(4) s2.remove(4) print(s1) print(s2) print (s1 & s2) print (s1 | s2) s3 = set((1, 2, 3)) s3.add(4) s3.remove(3) print(s3) s4 =set(1, [2, 3]) # TypeError: set expected at most 1 argument, got 2 print(s4) s4 =set(1, 2, 3) # TypeError: set expected at most 1 argument, got 3 print(s4) s4 = set((1, [2, 3])) # TypeError: unhashable type: 'list' print(s4) s4 = set((1, (2, 3))) print(s4)
第5章 程序可交互
- 5.1&5.2
input() print()
myName = input("Please enter your name: ") myAge = input("What about your age: ") print("Hello World,my name is ",myName,"and I am",myAge,"years old.")
- 5.3 三引号
print('''Hello World. My name is John and I am 20 years old.''')
- 5.4 转义字符
print("a\tb\nc\\d\"e\'f")
第6章 选择和判断
- 6.1 条件语句
== | != | < | > | <= | >= | and | or | not |
---|---|---|---|---|---|---|---|---|
等于 | 不等于 | 小于 | 大于 | 小于等于 | 大于等于 | 与 | 或 | 非 |
-
6.2
if
user = input("Enter 1 or 2:") if user == "1": print("Hello World") print("How are you") elif user == "2": print("Python Rocks") print("Ilove Python") else: print("You didn't enter a valid number!") # if elif else height = float(input('Please input your height(m): ')) weight = float(input('Please input your weight(kg): ')) bmi = weight / (height * height) print('Your bmi is %.2f.' % bmi) if bmi < 18.5 : print('too light.') elif bmi < 25 : print('normal.') elif bmi < 28 : print('overweight.') elif bmi < 32 : print('obese.') else : print('too obese.') # inline if user = input("Enter 1 or 2:") num=1 if user=="1" else 5 print(num) print("This is task A " if user=="2" else "This is task B")
-
6.3
match case
# match # basic match score = 'B' match score: case 'A': print('score is A.') case 'B': print('score is B.') case 'C': print('score is C.') case _: # _表示匹配到其他任何情况 print('score is ?.') # sequence match point = (2, 7) match point: case (0, 0): print('Origin') case (0, y): print(f'Point is on the Y axis at {y}') case (x, 0): print(f'Point is on the Y axis at {x}') case (x, y): print(f'Point is at ({x}, {y})') case _: print('Not a point') # object match class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(0, 3) match p: case Point(x=0, y=0): print(f'Point is on origin') case Point(x=0, y=y): print(f'Point is on the Y axis at {y}') case Point(x=x, y=0): print(f'Point is on the X axis at {x}') case Point(x=x, y=y): print(f'Point is at ({x}, {y})') case _: print('Not a point') # band match x = 2 match x: case x if x > 3: print(f'{x} > 3') case 1 | 2 | 3: print("x is 1, 2, or 3") case _: print("x is something else") # list match args = ['gcc', 'hello.c', 'world.c'] # args = ['clean'] # args = ['gcc'] match args: case ['gcc']: # 列表仅有'gcc'一个字符串,没有指定文件名,报错 print('gcc: missing source code file(s).') case ['gcc', file1, *files]: # 列表第一个字符串是'gcc',第二个字符串绑定到变量file1,后面的任意个字符串绑定到*files print('gcc compile: ' + file1 + ',' + ','.join(files)) case ['clean']: # 列表仅有'clean'一个字符串 print('clean') case _: # 其他所有情况 print('invalid command.')
-
6.4
for
循环- 6.4.1 迭代
pets = ["cats","dogs","rabbits","hamsters"] for mypets in pets: print(mypets) for index, mypets in enumerate(pets): print(index, mypets) message = "Hello" for i in message: print(i)
- 6.4.2 在一段数字上循环
range(start, end, step)
, 默认start == 0, step == 1
生成连续列表 end 必须显式给出range(5) # 生成[0,1,2,3,4] range(3,10) # 生成[3,4,5,6,7,8,9] range(4,10,2) # 生成[4,6,8] for i in range(5): print(i)
- 6.4.2 在一段数字上循环
- 6.4.1 迭代
-
6.5
while
循环counter = 5 while counter>0: print("counter = ",counter) counter = counter - 1
-
6.6
break
j = 0 for i in range(5): j=j+2 print("i=",i,"j=",j) if(j==6): break
-
6.7
continue
j = 0 for i in range(5): j=j+2 print("i=",i,"j=",j) if(j==6): continue print("if counter!=6,print counter=",i)
-
6.8
Try, Except
[格式] try子句(可能出错的语句) except子句(错误发生,执行的语句)
def spam(divideBy): try: return 42/divideBy except ZeroDivisionError: print('Error:Invalid argument') print(spam(2)) print(spam(12)) print(spam(0)) print(spam(3)) None 的输出是因为 print()函数的返回值为 none