Python_0基础:2.变量以及数据类型

作者: liang_820 | 来源:发表于2022-05-17 15:44 被阅读0次

    2.1 变量的定义

    在不使用变量的情况下:

    print('今天的天气很好,晴天了')  
    print('今天的天气很好,晴天了')  
    print('今天的天气很好,晴天了')  
    print('今天的天气很好,晴天了')
    

    重复的值 书写/修改起来都很麻烦

    在使用变量的情况下:

    # 变量的格式 : 变量的名字 = 变量的值
    weather = '今天的天气很好,晴天了!!!!'    
    print(weather)  
    print(weather)  # 注意:变量名不需要使用引号包裹
    print(weather)  
    print(weather)
    

    定义变量后可以使用变量名来访问变量值

    应用场景

    img='https://img13.360buyimg.com/babel/s580x740_jfs/t1/92557/10/15252/173783/60a60c58Eaec1cb70/466903cb1e5a5d82.jpg!cc_290x370.webp'  
    print(img)
    

    可直接访问图片

    说明:

    • 变量即是可以变化的值,可以随时进行修改。
    • 程序就是用来处理数据的,而变量就是用来存储数据的。

    2.2 数据类型

    在python中,为了应对不同的业务需求,也把数据分为不同的类型

    如下表所示:

    • Numbers(数字)
      • int(有符号整型)
      • long(长整型【也可代表8/16进制】最新python3已取消
      • float(浮点型)
      • complex(复数)
    • 布尔类型
      • True
      • False
    • String(字符串)
    • List(列表)
    • Tuple(元组)
    • Dictionary(字典)

    变量类型

    Number 数值

    money1 = 5000 # int
    
    money2 = 1.2 # float
    

    Boolean 布尔

    • 流程控制语句
    • 性别的变量
    • 性别在实际的企业级开发中 使用的单词是sex gender
    sex = True      # 男 True  
    gender = False  # 女 False
    

    String 字符串

    • 字符串使用的是 单引号/双引号 不允许一单一双
    s1 = '苍茫的大海上有一只海燕 你可长点心吧'  
    s2 = "嘀嗒嘀嗒嘀"
    
    • 单引号和双引号的嵌套
    s3 = '"嘿嘿嘿"'  # 单引号嵌套双引号
    print(s3)  
    s4 = "'哈哈哈'"  # 双引号嵌套单引号
    print(s4)
    
    • 单引号套单引号 双引号套双引号 这是不可以的
    s5 = ''不可以''  # 错误
    s6 = ""不可以""    # 错误
    

    List 列表

    应用场景: 当获取到了很多个数据的时候 那么我们可以将他们存储到列表中 然后直接使用列表访问

    name_list = ['周杰伦', '科比']  
    print(name_list)
    

    Tuple 元组

    age_tuple = (18, 19, 20, 21)  
    print(age_tuple)
    

    Dictionary 字典

    应用场景: scrapy框架使用

    # 格式: 变量名 = {key1:value1,key2:value2}
    
    person = {'name': '红浪漫', 'age': 18}  
    print(person)
    

    要求 : 必须掌握 列表 元组 字典 的格式


    2.3 查看数据类型

    • 在python中,只要定义了一个变量,而且它有数据,那么它的类型就已经确定了,不需要开发者主动的去说明它的类型,系统会自动辨别。
    • 也就是说在使用的时候变量没有类型,数据才有类型

    1. 比如下面的示例里,a的类型可以根据数据来确认,但是我们没法预测变量b的类型。

    2.如果临时想要查看一个变量存储的数据类型,可以使用type(变量名),来查看变量存储的数据类型。

    int

    a = 1  
    print(a)  
    print(type(a))  # <class 'int'>  
    

    float

    b = 1.2  
    print(b)  
    print(type(b))  # <class 'float'>  
    

    boolean

    c = True  
    print(c)  
    print(type(c))  # <class 'bool'>  
    

    string

    d = '中国'  
    print(d)  
    print(type(d))  # <class 'str'>
    

    list

    e = [1, 2, 3, 4]  
    print(e)  
    print(type(e))  # <class 'list'>  
    

    tuple

    f = (1, 2, 3, 4, 5)  
    print(f)  
    print(type(f))  # <class 'tuple'> 
    

    dictionary

    g = {'name': 'zs'}  
    print(g)  
    print(type(g))  # <class 'dict'>
    

    相关文章

      网友评论

        本文标题:Python_0基础:2.变量以及数据类型

        本文链接:https://www.haomeiwen.com/subject/codnurtx.html