• if,for,异常,random模块,计算圆周率


    一、分支结构

    单分支结构

    if 一般用于判断选择

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

    双分支结构

    • if...else
    age = 20
    if age >= 18:
        print('成年')
    else:
        print('未成年')
    
    • 三目运算
    age = 19
    print('成年') if age >=18 else print('未成年') # 只有双分支有这种写法
    
    • if...elif...elif...else 与 if...if...if...else
    # 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('不及格')
    

    if...elif...elif...else 执行完if才到elif 执行if就已经筛选了

    if...if...if...if 同时判断 (效率低)

    二、异常处理

    • 捕获异常
    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)
    

    不需要记住具体异常,只要捕捉Exception

    • finally (无论是否报错,都会执行finally下的代码)
    try:
        1 / 0
        y = input('请输入数字:')
        y += 10
    except Exception as e:   # 只要捕捉Exception
        print('error:', e)
    finally:    # 无论是否报错,都会执行finally下的代码
        print(1)
    
    • raise (可以自定义异常)
    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: 报错了, 请输入数字
    
    

    三、循环结构

    • while循环
    count = 0
    while count < 10:
        if count %2 == 0:
            print(count, end=',')
        count += 1
        
    # 打印结果:
    0,2,4,6,8,
    
    • for循环
    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, 
    
    • 循环 + continue
    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,
    
    • 循环 + break
    for  i  in  range(21):
        if i == 10:
            break
        print(i, end=', ')
        
    # 打印结果:
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
    

    四、random模块

    • 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)
    

    五、计算圆周率

    • 公式法计算

    圆周率计算公式:

    [pi = sum_{k=0}^infty [frac{1}{16^k} (frac{4}{8k+1}-frac{2}{8k+4}-frac{1}{8k+5}-frac{1}{8k+6})] ]

    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)
    
  • 相关阅读:
    阿里云安骑士和云盾不能检测连接服务器问题
    UDP反射DDoS攻击原理和防范
    linux查看端口是否开放
    记一次阿里云服务器被用作DDOS攻击肉鸡
    记一次阿里云负载测试
    mysql定时任务event——清理过期数据
    ansible(一)
    基于python实现的三方组件----Celery
    MongoDB
    flask相关使用
  • 原文地址:https://www.cnblogs.com/setcreed/p/11408371.html
Copyright © 2020-2023  润新知