当前位置:首页 » 《随便一记》 » 正文

Python基础之输入、输出与高阶赋值_盼小辉丶的博客

18 人参与  2022年05月16日 08:19  分类 : 《随便一记》  评论

点击全文阅读


Python基础之输入、输出与高阶赋值

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

0. 学习目标

Python 是简洁、易学、面向对象的编程语言。它不仅拥有强大的原生数据类型,也提供了简单易用的控制语句。在《Python基础之变量与内置数据类型》中,我们介绍了 Python 中的内置原生数据类型。本节的主要目标是介绍 Python 程序如何利用输入、输出语句与用户进行交互,以及高阶赋值语句,为接下来的学习奠定基础,本文会完整的介绍学习数据结构和算法所需的 Python 基础知识及基本思想,并给出相应的实战示例及解释。

  • 掌握 Python 利用输入输出和用户进行交互
  • 理解并掌握 Python 高阶赋值语句

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'

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

点击全文阅读


本文链接:http://zhangshiyu.com/post/40211.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1