注: python的语法逻辑完全靠缩进,建议缩进4个空格。

1. 练习1:经典入门语句 输出 hello world

print('hello world!') #如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误

	#满足if条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别
	if 3 > 0:
	    print('OK')
	    print('yes')
	    
	# 不建议,应该写成两行
	# x = 3; y = 4
	# 建议。比较不容易混淆
	x = 3
	y = 4
	print(x + y)

2. 练习2:print 的基本用法

https://www.runoob.com/w3cnote/python3-print-func-b.html

	print('hello world!')
	print('hello', 'world!')  # 逗号自动添加默认的分隔符:空格
	print('hello' + 'world!')  # 加号表示字符拼接
	print('hello', 'world', sep='***')  # 单词间用***分隔
	print('#' * 50)  # *号表示重复50遍
	print('how are you?', end='') # 默认print会打印回车,end=''表示不要回车

3. 练习3:基本运算符

运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符

	print(5 / 2)  # 2.5
	print(5 // 2)  # 丢弃余数,只保留商
	print(5 % 2)  # 求余数
	print(5 ** 3)  # 5的3次方
	print(5 > 3)  # 返回True
	print(3 > 5)  # 返回False
	print(20 > 10 > 5)  # python支持连续比较
	print(20 > 10 and 10 > 5)  # 与上面相同含义
	print(not 20 > 10)  # False

4. 练习4:input的基本用法

注: input获得的数据是字符型

	number = input("请输入数字: ")  # input用于获取键盘输入
	print(number)
	print(type(number))  # input获得的数据是字符型
	print(number + 10)  # 报错,不能把字符和数字做运算
	print(int(number) + 10)  # int可将字符串10转换成数字10
	print(number + str(10))  # str将10转换为字符串后实现字符串拼接

5. 练习5:字符串

	str = 'tom\'s pet is a cat'  # 单引号中间还有单引号,可以转义
	str = "tom's pet is a cat"  # 也可以用双引号包含单引号
	str = "tom said:\"hello world!\""
	str = 'tom said:"hello world"'
	# 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串
	words = """
	hello
	world
	abcd"""
	print(words)
	
	py_str = 'python'
	len(py_str)  # 取长度
	py_str[0]  # 第一个字符
	'python'[0]
	py_str[-1]  # 最后一个字符
	# py_str[6]  # 错误,下标超出范围
	py_str[2:4]  # 切片,起始下标包含,结束下标不包含
	py_str[2:]  # 从下标为2的字符取到结尾
	py_str[:2]  # 从开头取到下标是2之前的字符
	py_str[:]  # 取全部
	py_str[::2]  # 步长值为2,默认是1
	py_str[1::2]  # 取出yhn
	py_str[::-1]  # 步长为负,表示自右向左取
	
	py_str + ' is good'  # 简单的拼接到一起
	py_str * 3  # 把字符串重复3遍
	
	't' in py_str  # True
	'th' in py_str  # True
	'to' in py_str  # False
	'to' not in py_str  # True

6. 练习6:列表

列表也是序列对象,但它是容器类型,列表中可以包含各种数据

	slist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
	len(slist)
	slist[-1]  # 取出最后一项
	slist[-1][-1]  # 因为最后一项是列表,列表还可以继续取下标
	[1,2,3][-1]  # [1,2,3]是列表,[-1]表示列表最后一项
	slist[-2][2]  # 列表倒数第2项是字符串,再取出字符下标为2的字符
	slist[3:5]   # ['bob', 'alice']
	10 in slist  # True
	'o' in slist  # False
	100 not in slist # True
	slist[-1] = 100  # 修改最后一项的值
	slist.append(200)  # 向**列表中追加一项

7. 练习7:元组

元组与列表基本上是一样的。注:列表可变,元组不可变

	atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
	len(atuple)
	10 in atuple
	atuple[2]
	atuple[3:5]
	# atuple[-1] = 100  # 错误,元组是不可变的

8. 练习8:字典

字典是另一种可变容器模型,且可存储任意类型对象。字典是key-value(键-值)对形式的,没有顺序,通过键取出值
https://www.runoob.com/python3/python3-dictionary.html

	adict = {'name': 'bob', 'age': 23}
	len(adict)
	'bob' in adict  # False
	'name' in adict  # True
	adict['email'] = 'bob@tedu.cn'  # 字典中没有key,则添加新项目
	adict['age'] = 25  # 字典中已有key,修改对应的value

9. 练习9:基本判断if

单个的数据也可作为判断条件。 任何值为0的数字、空对象都是False,任何非0数字、非空对象都是True。

	if 3 > 0:
	    print('yes')
	    print('ok')
	
	if 10 in [10, 20, 30]:
	    print('ok')
	
	if -0.0:
	    print('yes')  # 任何值为0的数字都是False
	
	if [1, 2]:
	    print('yes')  # 非空对象都是True
	
	if ' ':
	    print('yes')  # 空格字符也是字符,条件为True

10. 练习10:条件表达式、三元运算符

	a = 10
	b = 20
	if a < b:
	    smaller = a
	else:
	    smaller = b
	print(smaller)
	s = a if a < b else b  # 和上面的if-else语句等价
	print(s)

11. 练习11:判断练习:用户名和密码是否正确

	import getpass  # 导入模块
	
	username = input('username: ')
	# getpass模块中,有一个方法也叫getpass
	password = getpass.getpass('password: ')
	
	if username == '123' and password == '123456':
	    print('Login success')
	else:
	    print('Login fail')

12. 练习12:随机数 random + 条件判断

	import random # 导入模块
	num = random.randint(1, 10) # 随机生成1-10之间的数字
	answer = int(input('guess a number: '))  # 将用户输入的字符转成整数
	if answer > num:
	    print('猜大了')
	elif answer < num:
	    print('猜小了')
	else:
	    print('猜对了')
	print('the number is:', num)

random + if 实现的小游戏

	import random
	all_choices = ['石头', '剪刀', '布']
	win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
	prompt = """(0) 石头
	(1) 剪刀
	(2) 布
	请选择(0/1/2): """
	computer = random.choice(all_choices)
	ind = int(input(prompt))
	player = all_choices[ind]
	
	print("Your choice: %s, Computer's choice: %s" % (player, computer))
	if player == computer:
	    print('平局')
	elif [player, computer] in win_list:
	    print('赢')
	else:
	    print('输')

13. 练习13:随机数 random + 条件判断 + while循环

while循环 控制尝试最大次数

	import random

	num = random.randint(1, 10)
	counter = 0
	
	while counter < 5:
	    answer = int(input('guess the number: '))
	    if answer > num:
	        print('猜大了')
	    elif answer < num:
	        print('猜小了')
	    else:
	        print('猜对了')
	        break
	    counter += 1
	else:  # 循环被break就不执行了,没有被break才执行
	    print('the number is:', num)

14. 练习14:for循环遍历数据对象

	astr = 'hello'
	alist = [10, 20, 30]
	atuple = ('bob', 'tom', 'alice')
	adict = {'name': 'john', 'age': 23}
	
	for ch in astr:
	    print(ch)
	
	for i in alist:
	    print(i)
	
	for name in atuple:
	    print(name)
	
	for key in adict:
	    print('%s: %s' % (key, adict[key]))

15. 练习15:range用法及数字累加

	# range(10)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
	# >>> list(range(10))
	# range(6, 11)  # [6, 7, 8, 9, 10]
	# range(1, 10, 2)  # [1, 3, 5, 7, 9]
	# range(10, 0, -1)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
	sum100 = 0
	for i in range(1, 101):
	    sum100 += i
	
	print(sum100)

16. 练习16:列表实现斐波那契数列

斐波那契数列:列表从第3项开始,每一项都等于前两项之和

	fib = [0, 1]
	for i in range(8):
	    fib.append(fib[-1] + fib[-2])
	print(fib)

17. 练习17:九九乘法表

	for i in range(1, 10):
	    for j in range(1, i + 1):
	        print('%s*%s=%s' % (j, i, i * j), end=' ')
	    print()
	
	# i=1 ->j: [1]
	# i=2 ->j: [1,2]
	# i=3 ->j: [1,2,3]
	#由用户指定相乘到多少
	n = int(input('number: '))
	
	for i in range(1, n + 1):
	    for j in range(1, i + 1):
	        print('%s*%s=%s' % (j, i, i * j), end=' ')
	    print()

18. 练习18:文件对象基础操作

	# 文件操作的三个步骤:打开、读写、关闭
	##################################
	f = open('/tmp/txt')  # 默认以r的方式打开纯文本文件
	data = f.read()  # read()把所有内容读取出来
	print(data)
	data = f.read()  # 随着读写的进行,文件指针向后移动。
	# 因为第一个f.read()已经把文件指针移动到结尾了,所以再读就没有数据了
	# 所以data是空字符串
	f.close()
	##################################
	f = open('/tmp/txt')
	data = f.read(4)  # 读4字节
	f.readline()  # 读到换行符\n结束
	f.readlines()  # 把每一行数据读出来放到列表中
	f.close()
	
	##################################
	f = open('/tmp/txt')
	for line in f:
	    print(line, end='')
	f.close()
	
	##################################
	f = open('图片地址', 'rb')  # 打开非文本文件要加参数b
	f.read(4096)
	f.close()
	
	##################################
	f = open('/tmp/file', 'w')  # 'w'打开文件,如果文件不存在则创建
	f.write('hello world!\n')
	f.flush()  # 立即将缓存中的数据同步到磁盘
	f.writelines(['2nd line.\n', 'new line.\n'])
	f.close()  # 关闭文件的时候,数据保存到磁盘
	
	##################################
	with open('/tmp/txt') as f:
	    print(f.readline())
	
	##################################
	f = open('/tmp/txt')
	f.tell()  # 查看文件指针的位置
	f.readline()
	f.tell()
	f.seek(0, 0)  # 第一个数字是偏移量,第2位是数字是相对位置。
	              # 相对位置0表示开头,1表示当前,2表示结尾
	f.tell()
	f.close()

19. 练习19:复制文件

读取a文件,分段将a文件的内容写入b文件

	a_fname = '/bin/ls'
	b_fname = '/root/ls'
	
	a_fobj = open(a_fname, 'rb')
	b_fobj = open(b_fname , 'wb')
	
	while True:
	    data = a_fobj.read(4096)
	    if not data:
	        break
	    b_fobj.write(data)
	
	a_fobj.close()
	b_fobj.close()

20. 练习20:生成密码/验证码

设计思路:
1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字
2、循环n次,每次随机取出一个字符
3、将各个字符拼接起来,保存到变量result中

	from random import choice
	import string
	
	all_chs = string.ascii_letters + string.digits  # 大小写字母加数字

	def gen_pass(n=8):
	    result = ''
	
	    for i in range(n):
	        ch = choice(all_chs)
	        result += ch
	
	    return result
	
	if __name__ == '__main__':
	    print(gen_pass())
	    print(gen_pass(4))
	    print(gen_pass(10))
未完待续。。。