In [10]:
# if else 的用法
x, y = 4, 5
smaller = x if x > y else y
print(smaller)
In [26]:
# 匿名函数 lambda 用法
a = lambda x, y=2 : x + y*3
print(a(3) + a(3, 5))
In [29]:
# list 的 count方法
l = ['tom', 'steven', 'jerry', 'steven']
print(l.count('tom') + l.count('steven'))
In [30]:
# os 用法
# 计算目录下有多少文件
import os
a = os.listdir()
print(len(a))
In [10]:
# 获得路径或者文件的大小
import os
os.path.getsize('/Users')
Out[10]:
In [9]:
# 列表生成式用法
# 在列表生成式后面加上判断,过滤出结果为偶数的结果
n = 0
for i in [x * x for x in range(8, 11) if x % 2 == 0]:
n = n + i
print(n)
In [14]:
# 简化调用方式
# 省却了 try...finally,会有 with 来自动控制
filename = 'test.txt'
with open(filename, 'r') as f:
print(f.read())
In [38]:
# python 有趣灵活的变量定义
first, second, *rest = (1,2,3,4,5,6,7,8)
print(first + second + rest[2])
In [42]:
# for continue 举例
# 以及 等于 不等于 或者 的逻辑判断
for l in 'computer':
if l != 't' or l == 'u':
continue
print('letter:', l)
In [12]:
# 找到符合 x*x + y*y == z*z + 3 的 x y z
# 多种循环
n = 0
for x in range(1,10):
for y in range(x,10):
for z in range(y,10):
if x*x + y*y == z*z:
print(x,y,z)
n= n + 1
print('count:',n)
In [7]:
# python 内置函数
print(max((1,2),(2,3),(2,4),(2,4,1)))
In [8]:
l = ['amy', 'tom', 'jerry ']
for i, item in enumerate(l):
print(i, item)
In [ ]: