zoukankan      html  css  js  c++  java
  • python基础代码2

    变量:

    1. 使用前不需要声明,但是必须赋值
    2. 没有固定的类型
    3. 等号“=”来给变量赋值
    4. 变量可以重复赋值,后面的会覆盖前面的
    counter = 100
    pi = 3.14
    name = "Python" 
    print(counter)
    print(pi)
    print(name)
    100
    3.14
    Python
    a = 123
    print(a)
    a = "ABC"
    print(a)
    123
    ABC

    变量的赋值过程

    a = 'ABC'
    b = a
    print(a)
    print(b)
    ABC
    ABC
    a = "XYZ"
    print(a)
    print(b)
    XYZ
    ABC

    标准数据类型(常用的)

    • 数字:整数、小数、其他
    • 布尔值:True或False
    • 字符串
    • 列表:有序的值的序列
    • 元组:有序的值的不可变序列
    • 集合:无序的值的集合
    • 字典:无序的键值对的集合
    100
    100
    type(100)
    int

    可以通过函数isinstance()来检验某个对象是不是指定的类型

    isinstance(100,int)
    True

    浮点数(小数):有精度上的限制,超过16位就不再精确了

    1.23
    1.23
    type(1.23)
    float
    1.23e9
    1230000000.0
    num = 1.12345678901234567890
    num
    1.1234567890123457

    用字符串格式化方法取小数位数

    print("{:.25f}.format(num))#保留25位
    1.1234567890123456912476740
    print("{:.20f}".format(1.5))
    print("{:.20f}".format(1.25))
    print('{:.20f}'.format(1.245))
    print('{:.20f}'.format(1.45))

    数字间的转换

    • int()函数可以把一个数值转换成整数类型,但是会截断(只保留整数)
    print(int(1.23))
    print(int(1.89))
    • 可以采用round()函数来进行四舍五入
    print(round(1.23))
    print(round(1.89))
    print(round(1.89,1))#可以指定位数
    • round由于是二进制,日常用的是十进制,所以会有误差
    print(round(0.5))
    print(round(1.5))
    print(round(2.5))
    print(round(2.45,1))
    print(round(2.125,2))
    • 这个时候可以使用十进制的内置函数库decimal来解决
    • float()
    float(10)

    常用数值运算

    • 浮点除/、整除//、求余数%、求幂**
    print(12/5)
    print(12/3)
    print(12.34/2)
    print(12.0/2)
    print(9//2)
    print(9.0//2)
    print(8.3 % 2)
    print(9 % 2)
    print(9.0 % 2)
    print(2 ** 3)
    print(2.0 ** 3)

    Python的数学运算符的优先级与数学上的相同,建议用括号表达运算先后逻辑(与SQL类似)

    print(50 - 5*6)
    print(5 + 6**2)
    print(5 * (6**2))#推荐的写法,为了有更好的可读性

    Python还内建支持复数,后缀用j或J表示虚数部分

    print(3 + 5J)
    type(3 + 5j)

    分数需要Fraction库(Python内置)

    import fractions
    fractions.Fraction(4,6)
    fractions.Fraction(4,-6)

     Decimal库来计算十进制数处理二进制在小数运算时不精确的问题

    import decimal
    d = decimal.Decimal('1.45')
    print(d)
    d = decimal.Decimal(1.45)

     

     

  • 相关阅读:
    Python中所有的关键字
    关于selenium的8种元素定位
    对提示框的操作
    selenium+webservice进行百度登录
    MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled...报错解决
    Vue中使用echarts
    npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142解决方法
    插入排序
    冒泡排序优化
    roject 'org.springframework.boot:spring-boot-starter-parent:XXX' not found 解决
  • 原文地址:https://www.cnblogs.com/ao-yu-a/p/11076584.html
Copyright © 2011-2022 走看看