zoukankan      html  css  js  c++  java
  • 基础python学习笔记2——程序的控制

    程序的分支语句

    条件组合保留字

    • and(&&)
    • or(||)
    • not(!)

    异常处理的基本使用

    try :
        <语句块1>
    except :
        <语句块2>
    
    try :
        <语句块1>
    except<异常类型> :
        <语句块2>
    
    eg:
    try :
        num = eval(input("请输入一个整数:"))
        print(num**3) //三次方
    except :
        print("not!")
    
    

    一个小实例【BMI指数】

    height, weight = eval(input("请输入身高(米)和体重(公斤)【逗号隔开】"))
    bmi = weight / pow(height,2)
    print("BMI:{:.2f}".format(bmi))
    who,nat = "", ""
    if bmi < 18.5:
        who, nat = "偏瘦", "偏瘦"
    elif 18.5 <= bmi < 24:
        who, nat = "正常", "正常"
    elif 24 <= bmi < 25:
        who,nat = "正常", "偏胖"
    elif 25 <= bmi < 28:
        who, nat = "偏胖", "偏胖"
    elif 28 <=bmi < 30:
        who, nat = "偏胖", "肥胖"
    print("{}".format(nat))
    
    

    程序的循环结构

    for <循环变量> in <遍历结构>
        <语句块>
    
    for c in "python"
        print(c)
    
    for i in range(5)//从0打印到4
    for i in range(1,6)//从1打印到5
    for i in range(1,6,2)//打印1,3,5
    
    while<条件>
        <语句块>
    
    while a > 0 :
        a = a - 1
        print(a)
    

    如果程序一直运行,可以用ctr+c 退出运行

    其他的保留字:continue,break

    random库的运用

    random库用于生成伪随机数
    伪随机数用梅森旋转算法产生

    random.seed(a=None)
    random.random()//随记产生一个0-1的数
    

    如果需要再现随机过程,一定要使用种子

    randint(a,b)//生成一个[a,b]之间的整数
    randrange(m,n[,k])//生成一个[m,n)之间以k为步长的随机整数
    getrandbits(k)//生成一个k比特长的随机整数
    choice(seq) //从序列seq中随机选择一个元素
    >>>random.choice([1,2,3,4,5])
    shuffle(seq)//将序列seq中元素随机排列,返回打乱后的序列
    

    补充:

    如果代码很长,需要换行,可以在行末使用 单斜杠
    如果有必要多行代码写到一行,语句间要是用 ; 分隔开

    一个小实例:【圆周率的计算】

    # from random import random
    # from time import perf_counter
    import time
    import random
    start = time.perf_counter()
    cnt = 0
    times = 5000*5000
    for i in range(times):
         xx = random.random()
         yy = random.random()
         if (pow(xx**2 + yy**2, 0.5) <= 1.0):
             cnt = cnt+1
    print("{:.7f}".format(4 * cnt / times))
    print("run time = {:.2f}".format(time.perf_counter()-start))
    
    
  • 相关阅读:
    H264关于RTP协议的实现
    RTSP交互命令简介及过程参数描述
    RTSP协议详解
    TCP 协议中MSS的理解
    RTSP 协议分析
    Linux下/etc/resolv.conf 配置DNS客户
    371. Sum of Two Integers
    python StringIO
    高效的两段式循环缓冲区──BipBuffer
    JavaScript Lib Interface (JavaScript系统定义的接口一览表)
  • 原文地址:https://www.cnblogs.com/fengxunling/p/13581235.html
Copyright © 2011-2022 走看看