这篇博客不是完整的python教程,只是我在学习python3时记下的一些容易忘记的或比较重要的知识点,里面的代码大多是转自 廖雪峰的python3教程 和 菜鸟教程 。不管怎样,还是希望本篇博客对读者有用。
print ("hello world!")
total = item_one + \
item_two + \
item_three
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符,实例如下:
a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print (x)
for i in range(0, 10, 3) :
print(i)
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
d = {key1 : value1, key2 : value2 }
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in range(len(list)):
print(next(it), end=" ")
list=[1,2,3,4]
it = iter(list)
for x in it:
print (x, end=" ")
import sys # 引入 sys 模块
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
while True:
try:
print (next(it), end=" ")
except StopIteration:
sys.exit()
def fib(n):
a, b , counter = 0, 1, 0
while counter < n:
yield b
a, b = b, a+b
counter += 1
import sys
f = fib(20)
print(type(f))
while True:
try:
print(next(f), end=' ')
except StopIteration:
sys.exit()
for x in fib(20):
print(x, end=' ')
#必须参数
def printme( str ):
print (str)
return
printme()
#关键字参数
def printinfo( name, age ):
print ("名字: ", name)
print ("年龄: ", age)
return
printinfo( age = 22, name = "cyiano" )
#默认参数
def printinfo( name, age = 35 ):
print ("名字: ", name)
print ("年龄: ", age)
return;
printinfo(age=50, name="cyiano")
print ("------------------------")
printinfo(name="cyiano")
#不定长参数
def printinfo( arg1, *vartuple ):
print ("输出: ")
print (arg1)
for var in vartuple:
print (var)
return
printinfo( 10 )
printinfo( 70, 60, 50 )
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.popleft()
vec = [2, 4, 6, 8]
[[x*2, x**2] for x in vec if x>2]
v1 = [2, 4, 6]
v2 = [4, 3, -9]
[x*y for x in v1 for y in v2]
[x+y for x in v1 for y in v2]
matrix = [
[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]
]
transposed = [[row[i] for row in matrix] for i in range(4)]
matrix = [
[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]
]
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
matrix = [
[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]
]
transposed = []
for i in range(4):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
for k, v in knights.items():
for i, v in enumerate(['tic', 'tac', 'toe']):
for i in reversed(range(1, 10, 2)):
for f in sorted(set(basket)):
import support
support.name_access("cyiano")
import folder.support #文件夹最好不要有空格
folder.support.name_access("cyiano")
import folder.support
folder.support.name_access("cyiano")
access = folder.support.name_access
from folder.support import name_access #导入模块特定函数
from folder.support import * #导入模块所有函数
name_access("cyiano")
import math
print('常量 PI 的值近似为 {0:5.10f}。'.format(math.pi))
# :前面数字代表format中的编号,5.10代表总长5位右对齐,保留10位小数
print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com'))
import math
print('常量 PI 的值近似为:%5.10f。' % math.pi)
f = open("newtxt.txt", "r+") # "w"表示只写,"r"表示只读,"r+"表示可读又可写,还有其他模式
f.read(15) # 读取15个字节,没有参数则读取所有
f.readline() # 读取一行
f.readlines() # 读取所有行并返回列表,有参数则按固定长度进行分割
f.write("ahahahaaha.....") # 从指针的位置开始写(会覆盖),必须是字符串
f.seek(5) # 移动指针位置
f.close() # 最后记得关闭文件
with open('/path/to/file', 'r') as f:
print(f.read())
while True:
try:
x = int(input("Please enter a number: "))
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Not a valid number! Try again! ")
else:
print("You just have inputed: {}".format(x))
finally:
print("next round: ")
def division(x, y):
if y == 0 :
raise ZeroDivisionError('The zero is not allow')
return x / y
try:
division(2, 0)
except ZeroDivisionError as e:
print(e)
# 另一种方法
try:
division(2, 0)
except ZeroDivisionError:
raise