• python基础入门归纳


    python入门学习 版本3.8.8

    https://www.liaoxuefeng.com/wiki/1016959663602400

    运行

    win中cmd直接跑
    输入
    python 
    print('hello')
    
    或新建 xx.py 中写print('hello')
    cmd中输入python xx.py

    linux mac可以直接跑py 像shell脚本一样 第一行需加上注释

    #!/usr/bin/env python3
    
    print('hello, world')

    还得赋予执行权限

    $ chmod a+x hello.py

    输入input()

    name=input('请输入:')//用户输入信息 赋予变量name

    换行

    print('xx
    xx') 
    //打印
    xx
    xx
    
    也可以使用'''...''' 换行
    print('''line1 
    ...line2
    line3''')
    //打印
    line1
    line2
    line3

    计算符号

    >>> 10 / 3
    3.3333333333333335 // 符号/除法 计算结果浮点类型
    
    >>> 10 // 3    // 符号//取整 与java/一致
    3
    
    >>> 10 % 3    //符号%取余 与java一致
    1

    编码(***重点)

    Unicode编码整合了各国的编码
    utf-8编码将Unicode编码按字母编成1个字节 汉字3个字节 传输文本大量英文字母时 utf-8更节省空间
    
    编写py代码建议使用utf-8编码
    //bytes字节码 <--> str 互转
    >>> '中文'.encode('utf-8')
    b'xe4xb8xadxe6x96x87' //str转utf-8字节码
    
    >>> b'xe4xb8xadxe6x96x87'.decode('utf-8') //字节码转str
    '中文'

    另外为了让python读取源码时按utf-8读取 最好在py文件开头加上

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-

    list、tuple集合

    list
    //定义例子如下
    >>> classmates = ['Michael', 'Bob', 'Tracy']
    >>> classmates
    ['Michael', 'Bob', 'Tracy']
    
    //常用api
    classmates[0] //获取第一个索引
    classmates[-1] //获取最后一个索引
    classmates.append('Adam') //末尾插入
    classmates.insert(1, 'Jack') //索引1位置插入 其它索引往后推
    classmates.pop() //删除末尾索引
    classmates[1] = 'Sarah' //修改值
    
    --------------------------------------------------------------------
    tuple
    //tuple小括号定义
    //tuple与list相似但定义后不能修改
    //定义例子如下
    >>> classmates = ('Michael', 'Bob', 'Tracy')
    
    注意
    定义空tuple classmates=()
    定义1个值要多个逗号 classmates=(8,)

    条件判断

    //例子:
    age = 3
    if age >= 18:
        print('adult')
    elif age >= 6:
        print('teenager')
    else:
        print('kid')

    循环

    //for循环 类似java for(:)
    //例子如下
    names = ['Michael', 'Bob', 'Tracy']
    for name in names:
        print(name)
    
    
    //while循环
    //例子如下
    sum = 0
    n = 99
    while n > 0:
        sum = sum + n
        n = n - 2
    print(sum)
    
    
    //break continue在python中也能使用

    dict、set

    //dict就是map
    //定义例子如下
    >>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
    >>> d['Michael']
    95
    
    d['Adam'] = 67//存参
    d['Adam']     //取参 注意 若参数不存在会报错
    d.pop('Adam') //删除
    
    避免key不存在报错方式
    1.
    >>> 'Thomas' in d
    False
    
    2.
    >>> d.get('Thomas')       //不存在返回None
    >>> d.get('Thomas', -1)  //不存在返回-1
    -1
    //set
    //定义例子如下
    >>> s = set([1, 2, 3]) //即list放在set()中
    >>> s
    {1, 2, 3}
    
     s.add(4) //添加
    s.remove(4) //删除
    
    //交 并集
    >>> s1 = set([1, 2, 3])
    >>> s2 = set([2, 3, 4])
    >>> s1 & s2
    {2, 3}
    >>> s1 | s2
    {1, 2, 3, 4}

    函数

    //常用api
    abs(-2) //返回绝对值
    max(2, 3, 1, -5) //返回最大值
    int('123') //类型转换
    float('12.34')
    str(1.23)
    bool(1)
    hex(255) //十进制转十六进制
    
    
    //定义函数
    //如下是定义函数例子 def定义 retuen返回
    def my_abs(x):
        if not isinstance(x, (int, float))://这段是校验参数类型
            raise TypeError('bad operand type')
        if x >= 0:
            return x
        else:
            return -x
    
    
    //python上例返回1个值 也可以返回多个值
    def move(x, y, step, angle=0):
        nx = x + step * math.cos(angle)
        ny = y - step * math.sin(angle)
        return nx, ny
    
     x, y = move(100, 100, 60, math.pi / 6)//获取
    >>> print(x, y)
    151.96152422706632 70.0
    //实际上返回的值是tuple 仍是单一值 
    >>> r = move(100, 100, 60, math.pi / 6)
    >>> print(r)
    (151.96152422706632, 70.0)
    //可变参数*
    //多个参数传入时函数将多个参数变为tuple来解析
    def calc(numbers):
        sum = 0
        for n in numbers:
            sum = sum + n * n
        return sum
    //但是调用的时候,需要先组装出一个list或tuple:
    >>> calc([1, 2, 3])
    14
    >>> calc((1, 3, 5, 7))
    84
    
    
    //用可变参数解决 参数加上*
    def calc(*numbers):
        sum = 0
        for n in numbers:
            sum = sum + n * n
        return sum
    //不需要组装list 直接多参数调用
    >>> calc(1, 2, 3)
    14
    >>> calc(1, 3, 5, 7)
    84
    //如果已经有组装好的list 调用可变参数的函数 list加上*号变成可变参数
    >>> nums = [1, 2, 3]
    >>> calc(*nums)
    14
    //关键字**
    //同上可变参数相似 *是将多个传入参数转tuple **将多参数转dict
    例子如下
    def person(name, age, **kw):
        print('name:', name, 'age:', age, 'other:', kw)
    
    >>> person('Adam', 45, gender='M', job='Engineer')
    name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
    //如果已经有组装好的dict
    >>> extra = {'city': 'Beijing', 'job': 'Engineer'}
    >>> person('Jack', 24, **extra)
    name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
    //命名关键字* 函数中*后面的参数必须传入参数名
    def person(name, age, *, city, job):
        print(name, age, city, job)
    
    >>> person('Jack', 24, 'Beijing', 'Engineer') //报错
    >>> person('Jack', 24, city='Beijing', job='Engineer') //正确
    Jack 24 Beijing Engineer
  • 相关阅读:
    PAT 1012 数字分类
    PAT 1046 划拳
    PAT 1021 个位数统计
    PAT 1003 我要通过!
    PAT 1031 查验身份证
    安装swoole
    PHP yield 分析,以及协程的实现,超详细版(上)
    PHP性能优化利器:生成器 yield理解
    swoole深入学习 8. 协程 转
    swoole| swoole 协程初体验 转
  • 原文地址:https://www.cnblogs.com/hbhb/p/14688873.html
Copyright © 2020-2023  润新知