day-04 作业

day-04 作业

1.简述Python的五大数据类型的作用、定义方式、使用方法:

  1. 数字类型

    • 作用:定义数字
    • 定义方式
      • 整型:a = 1 / a = int(1)
      • 浮点型:b = 1.1 / b = float(1.1)
    • 使用方法
      • 加、减、乘、除、取余、取整、幂
      • 调用cmath扩展
  2. 字符串类型

    • 作用:具有描述意义的一段字符

    • 定义方式

      • 单引号、双引号:' str '"str "

      • 三单引号、三双引号(可换行)

        '''
        str
        '''
        或
        """
        str
        """
    • 使用方法:

      • 加法:拼接字符串
      • 乘法:复制字符串
  3. 列表

    • 作用:存储多个任意数据类型的元素
    • 定义方式:[]内用逗号隔开的多个元素
    • 使用方法:索引取值
  4. 字典

    • 作用:存储多个具有描述信息的任意数据类型的元素
    • 定义方式:{}内用逗号隔开多个键(描述,用字符串):值(具体的值,可以为任意数据类型)对
    • 使用方法:按key取值
  5. 布尔型

    • 作用:用于判断条件结果,为真则值为 True,为假则值为 False

    • 定义方式:True、False通常情况不会直接引用,需要使用逻辑运算得到结果

    • 使用方法:所有数据类型都自带布尔值,除了 0/None/空(空字符/空列表/空字典)/False 之外所有数据类型自带布尔值为 True

      print(bool(0))
      print(bool('nick'))
      print(bool(1 > 2))
      print(bool(1 == 1))

      结果:

      True
      False
      False
      False
      False
      False
      
      Process finished with exit code 0

2.一行代码实现下述代码实现的功能:

x = 10
y = 10
z = 10

实现代码,使用print()检查:

x = y = z = 10
print(x, y, z)

结果如下:

10 10 10

Process finished with exit code 0

3.写出两种交换x、y值的方式:

x = 10
y = 20

方法一代码:

x = 10
y = 20

z = x
x = y
y = z
print('x=',x,';','y=', y)

方法二代码:

x = 10
y = 20

x, y = y, x
print('x=',x,';','y=', y)

两种方法的结果相同,如下所示:

x= 20 ; y= 10

Process finished with exit code 0

4.一行代码取出nick的第2、3个爱好:

nick_info_dict = {
'name':'nick',
'age':'18',
'height':180,
'weight':140,
'hobby_list':['read','run','music','code'],
}

实现代码:

nick_info_dict = {
    'name': 'nick',
    'age': '18',
    'height': 180,
    'weight': 140,
    'hobby_list': ['read', 'run', 'music', 'code'],
}
print(nick_info_dict['hobby_list'][1:3])

结果如下:

['run', 'music']

Process finished with exit code 0

5.使用格式化输出的三种方式实现以下输出

name = '你的名字'
height = 你的身高
weight = 你的体重

# "My name is 'Nick', my height is 180, my weight is 140"

实现代码:

name = 'Alex'
height = 185
weight = 130

# "My name is 'Nick', my height is 180, my weight is 140"

print(f'"My name is {name}, my height is {height}, my weight is {weight}"')
print('"My name is %s, my height is %s, my weight is %s"' % (name, height, weight))
print('"My name is {}, my height is {}, my weight is {}"'.format(name, height, weight))

结果如下:

"My name is Alex, my height is 185, my weight is 130"
"My name is Alex, my height is 185, my weight is 130"
"My name is Alex, my height is 185, my weight is 130"

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/liveact/p/11498014.html