Python 中的类型和类型转换

类型和类型转换

  • 目前我们已经接触的数据类型

    1. 整型
    2. 浮点型
    3. 布尔型
    4. 字符串
  • 使用 type() 用来检查你所处理的任何变量的数据类型

    print(type(4)) # int
    print(type(3.7)) # float
    print(type('this')) # str
    print(type(True)) # bool

类型和类型转换[相关练习]

  • 你认为以下代码的结果是什么?

    "0" + 5

    将会报错:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: must be str, not int

    or

    0 + "5"

    将会报错:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • 以下对象是什么类型:"12"

    str
  • 以下对象是什么类型:12.3

    float
  • 以下对象是什么类型:len("my_string")

    int
  • 以下对象是什么类型:"hippo" *12

    str
  • 计算总销量

    mon_sales = "121"
    tues_sales = "105"
    wed_sales = "110"
    thurs_sales = "98"
    fri_sales = "95"
    
    #TODO: Print a string with this format: This week's total sales: xxx. You will probably need to write some lines of code before the print statement.
    
    total = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
    print("This week\'s total sales: " + str(total)) # This week's total sales: 529

猜你喜欢

转载自blog.csdn.net/tyro_java/article/details/80714115
今日推荐