目录
  • 1. 输入、输出与注释
    • 1.1 获取用户输入
    • 1.2 格式化输出
      • 1.2.1 基本方法
      • 1.2.2 format 格式化函数
    • 1.3 注释
    • 2. 高阶赋值语句
      • 2.1 赋值运算符
        • 2.2 并行赋值
          • 2.3 序列解包
            • 2.4 链式赋值
            • 总结

              1. 输入、输出与注释

              1.1 获取用户输入

              程序常常需要与用户进行交互,以获得用户提交的数据。python 提供了input 函数,它接受用户输入数据并且返回一个字符串的引用。
              input 函数接受一个字符串作为参数,该字符串用于作为提示用户输入的文本,因此也被称为提示字符串:

              >>> number = input('enter the number of students: ')
              enter the number of students: 52
              >>> number
              '52'
              

              在交互式解释器中执行第一行 number = input(‘enter the number of students: ‘),它打印字符串 “enter the number of students: “,提示用户输入相应的信息。此处输入 52 并按回车,获取用户在提示字符串后的输入后,存储在 number变量中。需要注意的是 input 函数返回的值是字符串类型,如果需要将这个字符串转换成其他类型,必须提供相应的类型转换,以进行所需操作:

              >>> score = input('enter the total score: ')
              enter the total score: 4396
              >>> number = input('enter the number of students: ')
              enter the number of students: 52
              >>> average_score = int(score) / int(number)
              >>> average_score
              84.53846153846153
              

              1.2 格式化输出

              1.2.1 基本方法

              我们在以上示例中,已经不止一次看到了 print 函数,其提供了非常简便打印 python 输出的方法。它接受零个或者多个参数,默认使用单个空格作为分隔符来显示结果,可以通过可选参数 sep 修改分隔符。此外,默认情况下每一次打印都以换行符结尾,可以通过设置参数 end 来改变:

              >>> print('data', 'structure', 'and', 'algorithms')
              data structure and algorithms
              >>> print('data', 'structure', 'and', 'algorithms', sep='-')
              data-structure-and-algorithms
              >>> print('data', 'structure', 'and', 'algorithms', sep='-', end='!!!')
              data-structure-and-algorithms!!!>>>
              

              格式化字符串是一个模板,其中包含保持不变的单词或空格,以及用于之后插入的变量的占位符。 使用格式化字符串,可以根据运行时变量的值而发生改变:

              print("the price of %s is %d yuan." % (fruit, price)) 
              

              % 是字符串运算符,被称作格式化运算符。 表达式的左边部分是模板(也叫格式化字符串),右边部分则是一系列用于格式化字符串的值,右边的值的个数与格式化字符串中 % 的个数一致。这些值将依次从左到右地被换入格式化字符串。

              格式化字符串可以包含一个或者多个转换声明。转换字符告诉格式化运算符,什么类型的值会被插入到字符串中的相应位置。在上面的例子中,%s 声明了一个字符串,%d 声明了一个整数。

              可以在 % 和格式化字符之间加入一个格式化修改符,用于实现更加复杂的输出格式:

              >>> print("the price of %s is %d yuan." % ('apple', fruits['apple']))
              the price of apple is 5 yuan.
              >>> print("the price of %s is %10d yuan." % ('apple', fruits['apple']))
              the price of apple is          5 yuan.
              >>> print("the price of %s is %+10d yuan." % ('apple', fruits['apple']))
              the price of apple is         +5 yuan.
              >>> print("the price of %s is %-10d yuan." % ('apple', fruits['apple']))
              the price of apple is 5          yuan.
              >>> print("the price of %s is %10.3f yuan." % ('apple', fruits['apple']))
              the price of apple is      5.000 yuan.
              >>> print("the price of apple is %(apple)f yuan." % fruits)
              the price of apple is 5.000000 yuan.
              

              1.2.2 format 格式化函数

              上述方式虽然依旧可以使用,但是目前推荐到的另一种解决方案是模板字符串 format,其旨在简化基本的格式设置机制,它融合并强化了前一方法的优点。使用 format 格式化函数时,每个替换字段使用花括号括起,其中可以包含变量名,替换字段也可以没有名称或将索引用作名称::

              >>> "the price of {} is {} yuan.".format('apple', 5.0)
              'the price of apple is 5.0 yuan.'
              >>> "the price of {fruit} is {price} yuan.".format(fruit='apple', price=price)
              'the price of apple is 5.0 yuan.'
              >>> "the price of {1} is {0} yuan.".format(5.0, 'apple')
              'the price of apple is 5.0 yuan.'
              

              从上述示例可以看出,索引和变量名的排列顺序无关紧要。除此之外,还通过结合冒号 :,从而利用格式说明符(与 % 运算符类似):

              >>> value = 2.718281828459045
              >>> '{} is approximately {:.2f}'.format('e', value)
              'e is approximately 2.72'
              >>> '{} is approximately {:+.2f}'.format('e', value)
              'e is approximately +2.72'
              >>> '{} is approximately {:0>10.2f}'.format('e', value)
              'e is approximately 0000002.72'
              >>> '{} is approximately {:0<10.2f}'.format('e', value)
              'e is approximately 2.72000000'
              >>> '{} is approximately {:^10.2f}'.format('e', value)
              'e is approximately    2.72   '
              >>> '{:,}'.format(100000)
              '100,000'
              >>> '{} is approximately {:.2%}'.format('e', value)
              'e is approximately 271.83%'
              >>> '{} is approximately {:.4e}'.format('e', value)
              'e is approximately 2.7183e+00'
              >>> '{} is approximately {:0=+10.2f}'.format('e', value)
              'e is approximately +000002.72'
              

              从上述示例中,很容易总结出,使用 : 号可以指定宽度、精度以及千位分隔符等,^、<、> 分别用于居中、左对齐、右对齐,并且其后可以指定宽度, 并可以使用指定单个字符进行填充,默认情况下用空格填充,也可以使用说明符 =,指定将填充字符放在符号和数字之间。
              同样我们可以使用 b、d、o、x 进行数据类型转换,分别是二进制、十进制、八进制、十六进制,c 用于将数据转换为 unicode 码:

              >>> "the number is {num:b}".format(num=1024)
              'the number is 10000000000'
              >>> "the number is {num:d}".format(num=1024)
              'the number is 1024'
              >>> "the number is {num:o}".format(num=1024)
              'the number is 2000'
              >>> "the number is {num:x}".format(num=1024)
              'the number is 400'
              >>> "the number is {num:c}".format(num=1024)
              'the number is ѐ'
              

              1.3 注释

              是时候介绍下注释了,注释是提高程序可读性的一个绝佳方法,也是大家容易忽视的点。python 不解释紧跟在 # 符号后面的文本:

              radius = 5.0 # 圆的半径
              side = 2.0 # 正方形边长
              # 正方形面积与圆形面积的差
              area_c = 3.14 * radius ** 2
              area_s = side ** 2
              diff = area_s - area_c
              

              如果要使用多行注释,可以将注释语句放在一对三双引号 (“””) 或一对三单引号 (”’) 之间:

              radius = 5.0
              side = 2.0
              area_c = 3.14 * radius ** 2
              area_s = side ** 2
              diff = area_s - area_c
              

              2. 高阶赋值语句

              我们已经学习了如何给变量赋值,或者给数据结构的数据元素赋值,但还有其他类型的赋值语句,可以用于简化代码,增加代码的可读性。

              2.1 赋值运算符

              除了最基础的 = 赋值运算符外,也可以将右边表达式中的标准运算符移到赋值运算符 = 的前,构成新的运算符,如 +=、-=、*=、/=、%=等:

              >>> number = 1
              >>> number += 4
              >>> print(number)
              5
              >>> number //= 2
              >>> print(number)
              2
              >>> number **= 2
              >>> print(number)
              4
              >>> string_1 = 'hello!'
              >>> string_1 *= 2
              >>> print(string_1)
              'hello!hello!'
              

              可以这种赋值方式不仅可以用于数值数据,也可以用于其他数据类型(只要数据类型支持所使用的双目运算符)。

              2.2 并行赋值

              除了一个一个进行赋值外,可以同时(并行)为多个变量赋值:

              >>> a, b, c, d = 0, 1, 2, 3
              >>> print(a, b, c, d)
              0 1 2 3
              

              通过这种方式,可以简单的交换多个变量的值:

              >>> b, c = c, b
              >>> print(a, b, c, d)
              0 2 1 3
              

              2.3 序列解包

              序列解包是将一个可迭代对象解包,并将得到的值存储到一系列变量中,但要解包的序列包含的元素个数必须与等号左边列出的变量个数相同,否则将引发异常:

              >>> fruit, price = ['apple', 5.0]
              >>> print(fruit)
              apple
              >>> print(price)
              5.0
              >>> fruit, price, date = ('apple', 5.0)
              traceback (most recent call last):
                file "<stdin>", line 1, in <module>
              valueerror: not enough values to unpack (expected 3, got 2)
              >>> fruit, price = ('apple', 5.0, '2021-11-11')
              traceback (most recent call last):
                file "<stdin>", line 1, in <module>
              valueerror: too many values to unpack (expected 2)
              

              为了避免异常触发,可以使用星号运算符 * 来收集多余的值,这样便不需要确保值和变量的个数相同,赋值语句的右边可以是任何类型的序列,但带星号的变量最终得到的总是一个列表:

              >>> fruits = ['apple', 'orange', 'lemon']
              >>> fruit_a, *rest = fruits
              >>> print(rest)
              ['orange', 'lemon']
              >>> fruits_a, *rest, fruits_b = fruits
              >>> print(rest)
              ['orange']
              >>> fruits_a, fruits_b, fruits_c, *rest = fruits
              >>> print(rest)
              []
              

              2.4 链式赋值

              链式赋值可以将多个变量关联到同一个值:

              var_1 = var_2 = value
              

              等价于:

              var_1 = value
              var_2 = var_1
              

              总结

              本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注www.887551.com的更多内容!