table of Contents
A. Review Review (basic data types)
1. Digital Type
(1) integer
x = int(10) pow(x, 10)
(2) Float
y = float(10) # 10.0 print(round(0.1 + 0.2, 1) == 0.3)
2. Operator
+-*/ // % **
3. String
name = str(10) # '10' name = 'nick' name = "nick" name = "nick's"# 双引号可以包裹单引号 name = """ nick's name is "nick" """ # 三双引号里的字符串可以换行
4. The built-in method
name.split() # 指定字符串分割 name.startswith('n')#从头开始匹配 name.endswith('k')# 从尾开始匹配 print(name.center(50, '*')) # 从中间开始补充字符*,总长度50
The escape character
s = "nick's name is \"nick\"" s = '\t' # 缩进 print(s) s = '\n' # 换行 print(s) s = r'\t\n' # \r原位打印,和end=''成对使用 print(s) for i in range(5): print('1',end=',')
Two control structure of a program
1. The branched structure
Single branch
Usually for determining if the scene / selection
90 points or more outstanding
score=95 if score>90: print('优秀')
Dual Branch
if ....else
More than 90 points outstanding, 90 points or less good
score=95 if score>90: print('优秀') else: peint('良好')
A triplet of expressions
score=75 print('优秀')if score>90 else print('良好')# 单分支没有,多分支也没有 #结果一 条件 结果二
Multi-Branch
Elif Elif .... if .... else ......
90 more than excellent, 90-70 good, about 70 fail
score=95 if score>90: print('优秀') elif score>70: peint('良好') else: peint('及格')
if......if......if......if
score=95 if score>90: print('优秀') if score>70 and score<90: peint('良好') if score<60: peint('及格')
2. Logical Operators
> >= < <= == !=
and 两者都必须成立
or 其中一个成立即可
not 非
3. Exception Handling
try: y = int(input('数字:')) # 10 y += 10 # y = y + 10 except Exception as e: print(f'error: \033[1;35m {e} \033[0m!') finally: # 无论报不报错,都会执行finally下面的代码 print(1) Exception# 异常处理的时候,只要写这个就可以了 raise # 自定义报错 assert 断言() assert 1==2
III. Cyclic structure of the program
1.for circulation
for i in range(1,10,2): print(i)# [1,3,5,7,9],输出的就是1-10之间的奇数 for i in 'nick': print(i)# n,i,c,k每个字符换行输出
2.while cycle
continue和break的区别 # continue不执行下面代码,继续运行循环 count = 0 while count < 100: # 49 if count == 49: count += 1 continue # 不执行下面代码,继续运行循环 count += 1 # 50 跳过不打印 print(count) # 50 # break终止循环 结束本次的while循环 count = 0 while count < 100: # 49 if count == 49: count += 1 break # 终止循环 结束本次的while循环 count += 1 # 50 print(count) # 50
3.while.....else
count = 0 while count < 100: # 49 if count == 49: count += 1 break # 终止循环 count += 1 # 50n print(count) # 50 else: #正常跳出循环的时候会执行,异常中断不执行 print('打我')
Four .random module
1.random generate random numbers
import random random.seed(10) # 种子 # 如果不自定义种子,则种子按照当前的时间来 print(random.random())# 取0和1之间的小数 print(random.choice([1,1,2,3,4]))
2.time () custom function
# 自己造的一个随机数 import time time=time.time() print(str(time).split('.')[-1][-1])
Calculation V. pi
# Π pi = 0 k = 0 while True: pi += (1/(16**k))* \ (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))# 数学求Π的公式 print(pi) k += 1 # 蒙特卡洛方法求Π import random count = 0 for i in range(100000): x, y = random.random(), random.random() dist = pow(x ** 2 + y ** 2, 0.5) if dist < 1: count += 1 print(count / 100000 * 4)