• 技术文章 >后端开发 >Python教程

    洞悉 Python基础概况

    coldplay.xixicoldplay.xixi2020-12-24 17:14:45转载1046
    Python视频教程栏目介绍掌握Python基础概况

    推荐(免费):Python视频教程

    Python基础

    theme: juejin

    highlight: Python基础
    Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。
    Python 由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。像 Perl 语言一样, Python 源代码同样遵循 GPL(GNU General Public License) 协议。官方宣布,2020 年 1 月 1 日, 停止 Python 2 的更新。Python 2.7 被确定为最后一个 Python 2.x 版本。
    出自 www.runoob.com/python/pyth…

    一. 变量类型

    在Python中没有和C , Java一样要求对于基本变量的定义所以只要定义其变量名称直接赋值就行,类似于默认javascript中的var只是作为一个声明,这是一个变量。
    # 字节 字符串 整型 浮点型 bool类型
    # pass 换行
    # true false 代表布尔做if判断使用
    var0 = 'a'print(var0)pass
    var1 = "hr"print(var1)pass
    var2 = 10print(var2)pass
    var3 = 100000.00print(var3)pass
    # 注意:True 与 False 在python中首字母需要大写的
    varTrue = True
    varFalse = Falseif varTrue:
        print("bool值True is True")else:
        print("bool值false is True")passif not varFalse:
        print("bool值True is False")else:
        print("bool值false is False")pass
    # 字符串的用法
    str = "你是谁老豆?"# 只需要前两位print(str[:2])# 需要第2位到最后一位print(str[2:len(str) - 1])pass
    # 列表(List)用法
    list1 = ['python', 'java', 1996, 2020]list2 = [1, 2, 3, 4, 5]list3 = ["a", "b", "c", "d"]# 列表的数据项不需要具有相同的类型,类型为 Objectprint(list1)# 可以自由拼接print(list1 + list2)# 可以自由使用任意类型拼接该数组中 使用方法 append
    # 方式1:
    list3.append(1)list3.append(2)list3.append(3)print(list3)# 方式2:(注意添加的如果是个数组 格式为:[ ... , [], ... ])list3.insert(2, 3)list3.insert(2, list1)print(list3)# 删除指定下标的数据
    # 方式1:
    del list3[1]print(list3)# 方式2:
    list3.remove("c")print(list3)pass
    # 元组件 (类似于数组列表 元组使用的是() 而 列表(list)使用的是[])a = (1, 2, 3, 4, 5, "1", "2")print(a)pass
    # 字典 (是一个key value 的 hash值)a = {"key1": "value1", "key2": "value2"}print(a)# 访问字典里的值
    # 方法 1:print(a["key1"])# 方法 2:print(a.get("key1"))# 修改字典中数据
    a["key2"] = "my love"print(a["key2"])# 删除字典中数据
    del a['key2']  # 删除键是'Name'的条目
    # a.clear()      # 清空字典所有条目
    # del a          # 删除字典print(a)pass
    复制代码

    二. 算术运算符

    运算符描述
    +a值 + b值
    -a值 - b值
    *a值 * b值
    /a值 / b值
    %a值 % b值
    **a值 ** b值
    //a值 // b值
    # Python -- 运算符
    int1 = 2int2 = 6int3 = 8int4 = 10int5 = 3# 加法print("int加法: ", int1 + int2)# 减法print("int减法: ", int4 - int2)# 乘法print("int乘法: ", int3 * int2)# 除法print("int除法: ", int4 / int1)# 取模print("int取模: ", int4 % int5)# 幂等print("int幂等: ", int1 ** int2)# 取整除print("int整除: ", int4 // int5)pass
    double1 = 10.00double2 = 20.10double3 = 30.20double4 = 40.30# 加法print("double加法:", double1 + double2)# 减法print("double减法:", double4 - double3)# 乘法print("double乘法:", double4 * int2)# 除法print("double除法:", double4 / int1)# 取模print("double取模:", double4 / double1)# 幂等print("double幂等: ", double4 ** int2)# 取整除print("double整除: ", double4 // int5)复制代码

    三. 条件语句与循环语句

    常用语句:
    1. if…else…
    2. while
    3. for
    4. break,continue
    # if...else 条件语句
    a = 0if a == 0:
        print("我等于0哦!")else:
        print("我不等于0哦!")pass
    # while 循环语句
    # 1. while 无限循环 (注意:使用 Stop 或者 Ctrl+C 结束)a = 0b = 0while a == 0:
        print("我来了第", b, "次!")
        b = b + 1# 2. while 条件循环
    a = 0while a < 5:
        print("我是", a, "号!")
        a = a + 1# 3. while 循环语句 + 条件语句
    a = 0exact = []not_exact = []while a < 10:
        # 0 - 10 是否存在被整除的数    if a % 2 == 0:
            exact.append(a)
        # 不能被整除的数    else:
            not_exact.append(a)
        a = a + 1else:
        print("这个循环我结束了!")print("能被被整除的数:", exact)print("不能被被整除的数:", not_exact)pass
    # 4. while 循环语句 + 条件语句 + 跳出循环
    a = 0exact = []while a < 10:
        # 0 - 10 是否存在被整除的数    if a % 2 == 0:
            exact.append(a)
        # 不能被整除的数    else:
            a = a + 1
            continue
        a = a + 1print("能被被整除的数 continue :", exact)pass
    # 5. while 循环语句 + 条件语句 + 跳出循环
    a = 0exact = []while a < 10:
        # 0 - 10 是否存在被整除的数    if a % 2 == 0:
            exact.append(a)
        # 不能被整除的数    else:
            a = a + 1
            break
        a = a + 1print("能被被整除的数 break :", exact)pass
    # for 循环语句
    # 1. for 循环
    a = [1, 2, 3, "4", 5, True]for b in a:
        print(b)pass
    # 2. for 循环 + 条件语句
    a = [1, 2, 3, "4", 5, True, 9, '10']b = False
    d = []for c in a:
        if c == True:
            b = True        continue
        d.append(c)print("含有bool值吗? ", b)print("不含bool值的数组:", d)pass
    复制代码

    四. 日期与时间

    # 日期与时间
    # 引入time模块import time
    pass
    # 获取毫秒值
    ticks = time.time()print("当前时间戳为:", ticks)pass
    # 获取本地时间
    localtime = time.localtime(time.time())print("本地时间为 :", localtime)pass
    # 获取有时间结构的数据
    localtime = time.asctime(time.localtime(time.time()))print("本地时间为 :", localtime)pass
    # 1. 格式化时间:
    # 格式化成2020-12-04 15:44:05形式print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))# 格式化成Fri Dec 04 15:44:05 2020形式print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))# 将格式字符串转换为时间戳
    a = "Sat Mar 28 22:24:24 2016"print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))pass
    # 2. 获取某月日历
    # 引入Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历import calendar
    cal = calendar.month(2020, 1)print("输出2020年1月份的日历:")print(cal)pass
    复制代码

    五. 函数与模块(Module)

    1. 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
    2. 函数能提高应用的模块性,和代码的重复利用率。
    3. 模块 能定义函数,类和变量,模块里也能包含可执行的代码。
    # 自定义一个函数
    def test_function(str):
        if str % 2 == 0:
            return str    else:
            return False
    
    str = 3print(test_function(str))复制代码
    # 导入模块import dbtest
    # 使用模块中的函数print(dbtest.test_function(2))pass
    复制代码

    六. File文件使用方法

    # input([prompt]) 函数可以接收一个Python表达式作为输入,并将运算结果返回
    str = input("请输入:")print("最终值为:", str)pass
    # open函数
    # file object = open(file_name [, access_mode][, buffering])# 1.file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
    # 2.access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
    # 3.buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
    # 4.encoding: 一般使用utf8
    # 5.errors: 报错级别
    # 6.newline: 区分换行符
    # 7.closefd: 传入的file参数类型
    # 8.opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符
    fo = open("D:\\桌面\\test.txt", "w+", -1)print("文件名: ", fo.name)print("是否已关闭 : ", fo.closed)print("访问模式 : ", fo.mode)# print("末尾是否强制加空格 : ", fo.softspace)pass
    # 写入文件内容 write([string])fo.write("当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。")print("写入成功!")pass
    # 读取文件内容 read([number])var = fo.read(10)print("文件内容:", var)pass
    # 文件定位 tell()print("文件位置:", fo.tell())pass
    # close 关闭
    # 当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。
    fo.close()print("已关闭")pass
    # 文件重新命名 os.rename([string -- old],[string -- new])import os
    var1 = "D:\\桌面\\test.txt"var2 = "D:\\桌面\\test2.txt"os.rename(var1, var2)print(var1, "已重新命名", var2)pass
    # 文件移除(文件删除)os.remove([string -- filename])os.remove(var2)print(var2, ",该文件已被删除!")pass
    # 改变当前目录 chdir([string]) 方法
    var3 = "D:\\桌面\\"os.chdir(var3)print("已跳转目录至:", var3)pass
    # 创建文件夹方式 os.mkdir([string])var4 = "123456789"# os.mkdir(var4)print("创建成功!")pass
    # os.rmdir([string]) rmdir()方法删除目录,目录名称以参数传递。 删除文件夹
    var5 = var3+var4
    # os.rmdir(var5)print(var3, var4, ",该文件已被删除!")pass
    # File 写入多行文件 writelines([string])var6 = "D:\\桌面\\test123.txt"# 创建文件 os.mknod([string -- file_path])# os.mknod(var6)fo2 = open(var6, "w+")# readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符
    line_read = fo2.readline(10)print("读取的字符串为: %s" % line_read)# writelines() 方法用于向文件中写入一序列的字符串
    a = 0while 10 > a:
        fo2.writelines("我开始喽!")
        a += 1print("录入成功!")pass
    
    # isatty() 方法检测文件是否连接到一个终端设备,如果是返回 True,否则返回 False
    ret = fo2.isatty()print(ret)# 刷新缓冲区
    fo2.flush()# 关闭文件
    fo2.close()pass

    以上就是洞悉 Python基础概况的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:learnku,如有侵犯,请联系admin@php.cn删除
    专题推荐:python
    上一篇:Python基础 装饰器及练习 下一篇:python socket 完成简单的通信
    大前端线上培训班

    相关文章推荐

    • 会python再学php难吗• python如何读取txt文件• 用Python Tkinter实现剪刀石头布小游戏• 实现python批量下载网易云音乐的免费音乐• Python爬取Json数据的示例

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网