Python基础之输入,输出与高阶赋值详解

 更新时间:2021年11月23日 11:25:44   作者:盼小辉丶  
这篇文章主要为大家介绍了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'

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

总结

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

相关文章

  • 实例讲解python读取各种文件的方法

    实例讲解python读取各种文件的方法

    这篇文章主要为大家详细介绍了python读取各种文件的方法,,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • OpenCV模板匹配matchTemplate的实现

    OpenCV模板匹配matchTemplate的实现

    这篇文章主要介绍了OpenCV模板匹配matchTemplate的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 图片去摩尔纹简述实现python代码示例

    图片去摩尔纹简述实现python代码示例

    这篇文章主要为大家介绍了图片去摩尔纹简述实现的python代码示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Python小波变换去噪的原理解析

    Python小波变换去噪的原理解析

    这篇文章主要介绍了Python小波变换去噪,对于去噪效果好坏的评价,常用信号的信噪比(SNR)与估计信号同原始信号的均方根误差(RMSE)来判断,需要的朋友可以参考下
    2021-12-12
  • Python中的TfidfVectorizer参数使用解析

    Python中的TfidfVectorizer参数使用解析

    这篇文章主要介绍了Python中的TfidfVectorizer参数使用解析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Python机器学习入门(四)之Python选择模型

    Python机器学习入门(四)之Python选择模型

    这篇文章主要介绍了Python机器学习入门知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-08-08
  • 浅析Python与Java和C之间有哪些细微区别

    浅析Python与Java和C之间有哪些细微区别

    这篇文章主要介绍了Python与Java和C之间有哪些细微区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Python OpenCV绘制各类几何图形详解

    Python OpenCV绘制各类几何图形详解

    这篇文章将详细讲解如何使用OpenCV绘制各类几何图形,包括cv2.line()、v2.circle()、cv2.rectangle()、cv2.ellipse()、cv2.polylines()、cv2.putText()函数。需要的可以参考一下
    2022-01-01
  • 基于scrapy实现的简单蜘蛛采集程序

    基于scrapy实现的简单蜘蛛采集程序

    这篇文章主要介绍了基于scrapy实现的简单蜘蛛采集程序,实例分析了scrapy实现采集程序的技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-04-04
  • 出现module 'queue' has no attribute 'Queue'问题的解决

    出现module 'queue' has no attrib

    这篇文章主要介绍了出现module 'queue' has no attribute 'Queue'问题的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04

最新评论