Python基础学习笔记


注释

  • 单行注释#
  • 多行注释''' '''或者""" """

获取变量类型
使用type函数来获取变量的类型:

1
2
3
4
5
number = 9
print(type(number)) # print <class 'int'>

float_number = 9.0
print(type(float_number)) # print <class 'float'>

**强转
python强转通过函数来强转,如:

1
2
3
4
5
float_number = 9.0
print(float_number)
print(int(float_number)) # 强转为int
print(str(float_number)) # 强转为字符串
print(float(float_number)) # 强转为float

次方
Python提供次方操作符**

1
2
number = 9.0
print(number ** 3) # print 81.0

链式比较
Python链式比较同时进行,如下面的:

1
2
3
4
5
6
one = 1
two = 2
three = 3

# 等同于 one < two 和 two < three 同时进行比较
print(one < two < three) # print True

索引下标负值
Python的索引下标可以是负值,从最后一个开始计数,从-1开始:

1
2
3
long_string = "This is a very long string!"
exclamation = long_string[-1]
print(exclamation) # print !

slicing

slicing

通过[start:end]来切割字符串:

1
2
3
4
5
monty_python = "Monty Python"
monty = monty_python[:5] # monty_python[:5] is equal to monty_python[0:5]
print(monty) # print Monty
python = monty_python[6:] #
print(python) # print Python

同时也能切割数组

1
2
3
4
squares = [1, 4, 9, 16, 25]   # create new list
print(squares) # print [1, 4, 9, 16, 25]

print(squares[1:-1]) # print [4, 9, 16]

字符串格式化
在Python中,采用的格式化方式和C语言是一致的,用%实现:

1
2
3
4
name = "Jowan"
print("Hello, PyCharm! My name is %s!" % name) # print Hello, PyCharm! My name is Jowan!
years = 25
print("I'm %d years old" % years) # print I'm 25 years old

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

格式化整数和浮点数还可以指定是否补0和整数与小数的位数:

1
2
print('%2d-%02d' % (3, 1)) # print 3-01
print('%.2f' % 3.1415926) # print 3.14

另一种格式化的方法:

1
2
3
4
5
6
7
# format
print("{0} can be {1}".format("strings", "formatted"))
# print strings can be formatted

# 或者自定义
print("{name} can be {food}".format(food="lasagna", name="Bob"))
# print Bob can be lasagna

数组增删改
通过append函数添加一个item,通过+=添加多个:

1
2
3
4
5
6
7
animals = ['elephant', 'lion', 'tiger', "giraffe"]  # create new list

animals += ["monkey", 'dog'] # add two items
print(animals) # print ['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog']

animals.append("dino") # add
print(animals) # print ['elephant', 'lion', 'tiger', 'giraffe', 'monkey', 'dog', 'dino']

数组的item替换:

1
2
3
4
5
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog']
animals[1:3] = ['cat'] # replace 2 items
print(animals) # print ['elephant', 'cat', 'giraffe', 'monkey', 'dog']
animals[0] = 'lion'
print(animals) # print ['lion', 'monkey', 'dog']

通过remove函数删除item,或者直接替换删除:

1
2
3
4
5
6
7
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog']   # create new list

animals[1:3] = ['cat'] # replace 2 items
print(animals) # print ['elephant', 'cat', 'giraffe', 'monkey', 'dog']

animals[1:3] = [] # remove 2 items
print(animals) # print ['elephant', 'monkey', 'dog']

通过clear函数清空数组内容:

1
animals.clear()

tuple元祖
元组与列表几乎相同,元组和列表之间唯一的重要区别是元组不能被改变:你不能从元组中添加,改变或者删除元素。
元组由括号内的逗号运算符构成:

1
2
alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')

单个项目元组必须有一个尾随逗号:

1
2
alphabet = ('b', )
beta = ('d', )

dict
Python的dict(dictionary)类似与Map,使用key-value存储。

1
2
3
4
5
6
7
8
9
10
11
# create new dictionary.
phone_book = {"John": 123, "Jane": 234, "Jerard": 345}
print(phone_book) # print {'John': 123, 'Jane': 234, 'Jerard': 345}

# 添加
phone_book["Jill"] = 345
print(phone_book) # print {'John': 123, 'Jane': 234, 'Jerard': 345, 'Jill': 345}

# 删除
del phone_book['John']
print(phone_book) # print {'John': 123, 'Jane': 234, 'Jerard': 345, 'Jill': 345}

或者键值对对应值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
phone_book = {"John": 123, "Jane": 234, "Jerard": 345}
print(phone_book.keys()) # print dict_keys(['John', 'Jane', 'Jerard', 'Jill'])

print(phone_book.values()) # print

keys = phone_book.keys() # print dict_values([123, 234, 345, 456])
for key in keys:
print(phone_book[key])

"""
print
123
234
345
456
"""

布尔操作
Python的或||or表示,和&&and表示:

1
2
3
4
5
6
name = "John"
age = 17

print(name == "John" or age == 17) # print True

print(name == "John" and age == 23) # print False

Python的布尔操作不是按顺序的,而是isnot先执行,or再执行,and是最后执行的:

1
2
3
4
5
6
7
8
name = "John"
age = 17

print(name == "John" or not age > 17) # print True

print(name == "Ellis" or not age > 17) # print True

print(name is "Ellis" or not (name == "John" and age == 17)) # print False

条件判断
Python的条件判断是没有括号的,通过冒号:开始,代码块缩进:

1
2
3
4
5
6
7
8
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
# 打印teenager

if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elifelse

if语句的完整形式就是:

1
2
3
4
5
6
7
8
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>

for循环

1
2
3
# for each number i in range 0-4. 
for i in range(5): # range(5) function returns list [0, 1, 2, 3, 4]
print(i)

用于字符串:

1
2
3
4
hello_world = "Hello, World!"

for ch in hello_world: # print each character from hello_world
print(ch)

while循环

1
2
3
4
5
6
7
8
square = 1

# 当square小于或等于10的时候循环
while square <= 10:
print(square)
square += 1

print("Finished") # This code is executed once

break和continue
break

1
2
3
4
5
6
7
8
count = 0

while True:
print(count)
count += 1
if count >= 5:
break
# print 0, 1, 2, 3, 4

continue

1
2
3
4
for i in range(5):
if i == 3:
continue
print(i) # print 0, 1, 2, 4

try/except
使用try/except代码块来处理异常:

1
2
3
4
5
try:
# 使用 raise 来抛出一个错误
raise IndexError("This is an index error")
except IndexError as e:
pass

感谢