지인 파이썬 (b)

분기 구조

단일 지점 구조

일반적으로 선택한 경우 결정

score = 95
if score > 90:
    print('优秀')

두 가지 구조

  • 다른 경우라면
age = 20
if age >= 18:
    print('成年')
else:
    print('未成年')
  • 세 개의 머리 작업
age = 19
print('成年') if age >=18 else print('未成年') # 只有双分支有这种写法
  • 만약 ... ELIF ... ELIF ... 다른 与 만약 ... 만약 ... 만약 ... 다른
# 90以上优秀,70-90良好,70以下不及格

# 法1:
score = 79
if score > 90:
    print('优秀')
elif score > 70:
    print('良好')
else:
    print('不及格')
    
# 法2:
score = 79
if score > 90:
    print('优秀')
if score > 70 and score < 90:
    print('良好')
else:
    print('不及格')

만약 ... ELIF ... ELIF ... 다른에만 실행을 실행 ELIF에 상영 한 경우 경우

만약 있다면 ... ... ... 경우 동시 결정 (비효율적 있으면)

둘째, 예외 처리

  • 예외를 잡아라
try:
    
    print('----1----')
    f = oen('a.txt', 'r')  # 路径不对, 是错误的代码
    print('----2----')
    
except:   # 捕获异常
    pass
    
# 输出结果:
----1----
  • 특정 이상을 캡처


try:
    1 / 0
    y = input('请输入数字:')
    y += 10
except TypeError as e:
    print('error:', e)
except ZeroDivisionError as a:
    print('error:', a)

print(x + 10)

# 打印结果:
error: division by zero
11
try:
    1 / 0
    y = input('请输入数字:')
    y += 10
except Exception as e:   # 只要捕捉Exception
    print('error:', e)

캐치 예외만큼, 특정 예외를 기억 할 필요가 없습니다

  • 마지막 (오류 여부, 이는 마지막 코드에서 실행한다)
try:
    1 / 0
    y = input('请输入数字:')
    y += 10
except Exception as e:   # 只要捕捉Exception
    print('error:', e)
finally:    # 无论是否报错,都会执行finally下的代码
    print(1)
  • 인상 (지정 예외 일 수있다)
s = input('请输入数字:')
# print(s.isalpha())       # isalpha() 如果全是字母,则输出True
if s.isalpha():
    raise TypeError('报错了, 请输入数字')
    
# 打印结果:
Traceback (most recent call last):
  File "D:/test2.py", line 82, in <module>
    raise TypeError('报错了, 请输入数字')
TypeError: 报错了, 请输入数字

셋째, 루프 구조

  • 루프 동안
count = 0
while count < 10:
    if count %2 == 0:
        print(count, end=',')
    count += 1
    
# 打印结果:
0,2,4,6,8,
  • 루프
for  i  in  range(21):
    print(i, end=', ')
    
# 打印结果:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
  • 순환은 계속 +
for  i  in  range(21):
    if i == 10: 
        continue     #  continue终止本次循环,跳到下次循环
    print(i, end=', ')
    
# 打印结果:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  • + 브레이크주기
for  i  in  range(21):
    if i == 10:
        break
    print(i, end=', ')
    
# 打印结果:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 

네, 임의 모듈

  • random.randint ()
import random

print(random.randint(1,10))  # 随机生成1-10中某个数

print(random.random())  # 在0-1之间默认生成数
  • random.random ()
import random

random.seed(4)   # 给一个随机数种子
print(random.random())   # 只第一次随机生成,之后生成的数字就一样了
print(random.random())

# 如果不自定义种子,则种子按照当前的时间来
  • random.choice ()
import random
print(random.choice([1,2,3,4,5]))
  • random.shuffle
import random
lt = [1,2,3,4,5,6]
random.shuffle(lt)    # 打乱列表顺序
print(lt)

V.은 PI를 계산

  • 배합 계산

파이 화학식 :
\ [\ PI = \ sum_ {K = 0} ^ \ infty [\ FRAC {. 1} {16 ^ K} (\ FRAC {. 4} {. 8K + 1} - \ FRAC {2} {8K를 + 4} - \의 FRAC {1} {5} + 8K - \의 FRAC {1} {6} 8K +)] \]

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(1000000):
    x, y = random.random(), random.random()
    distance = pow(x**2 + y**2, 0.5)
    if distance < 1:
        count += 1
print(count/1000000*4)

추천

출처www.cnblogs.com/setcreed/p/11408371.html