python简介
x = (1+2+
3+4)
print(x) # 10
x = (1+2+
3+4)
print(x) # 10
if 1 < 2:print(1) # 1
'''
while True:
reply = input('enter text:')
if reply == 'break':break
try:
num = int(reply)
except:
print('bad'*8)
else:
print(int(reply)**2)
print('Bye')
'''
赋值,表达式,打印
赋值语句建立对象引用值
变量名在首次赋值时会被创建
变量名在引用前必须先赋值
执行隐式赋值的一些操作
name, age = 1, 2
print(name, age) # 1 2
l = 'spam'
a, b, c = list(l[:2]) + [l[2:]]
print(a, b, c) # s p am
(a, b),c = l[:2],l[2:]
print(a, b, c) # s p am
((a, b),c) = ('sp','am')
print(a, b, c) # s p am
r, g, b = range(3)
print(r, g, b) # 0 1 2
l = [1,2,3,4]
while l:
front,l = l[0],l[1:]
print(front,l)
1 [2, 3, 4]
2 [3, 4]
3 [4]
4
l = [1,2,3,4]
front = l[0]
l = l[1:]
print(front, l) # 1 [2, 3, 4]
l = [1,2,3,4]
a, *b = l
print(a, b) # 1 [2, 3, 4]
a, *b = 'spam'
print(a, b) # s ['p', 'a', 'm']
l = [1,2,3,4]
while l:
front, *l = l
print(front, l)
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
l = [1,2,3,4]
*a, = l
print(a) # [1, 2, 3, 4]
for (a, *b, c) in [(1,2,3,4)]:
print(a, b, c) # 1 [2, 3] 4
s = 'spam'
s += 'sbam'
print(s) # spamsbam
l = [1, 2]
m = l
l = l+[3,4]
print(l, m) # [1, 2, 3, 4] [1, 2]
增强赋值在原处修改对象,可以改变共享的引用
l = [1, 2]
m = l
l += [3, 4]
print(l, m) # [1, 2, 3, 4] [1, 2, 3, 4]
命名规则
以单一下划线开头的变量名不会from module import * 语句导入 _x
前后双下划线的变量名__x__是系统定义的变量名。对解释器有特殊含义
以两下划线开头,结尾没双下划綫的变量名__x是类的本地变量
通过交互模式运行时,只有单个下划线的变量名会保存最后的表达式
x = print('spam')
print(x) # None
append, sort, reverse会在原处修改列表
流的重定向
print(1,1,1,sep = '') # 111
print(1,1,1,sep = ',') # 1,1,1
print(1,2,3,end='..\n') # 1 2 3..
print(1,2,3,sep='....',file = open('data.txt','w'))
print(1,2,3)
a = open('data.txt').read()
print(a) # 1....2....3
2.6 print
print x,y,
import sys
print(sys.stdout.write('hello world\n')) # hello world
print(x, y) == sys.stdout.write(str(x) +''+str(y)+'\n')
python3
log = open('datas.txt','w')
print(1,2,3,file=log)
print(4,5,6,file=log)
log.close()
print(7,8,9)
print(open('datas.txt').read())