广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python基础之输入,输出与高阶赋值详解
  • 515
分享到

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

2024-04-02 19:04:59 515人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录1. 输入、输出与注释1.1 获取用户输入1.2 格式化输出1.2.1 基本方法1.2.2 fORMat 格式化函数1.3 注释2. 高阶赋值语句2.1 赋值运算符2.2 并行赋

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

总结

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

--结束END--

本文标题: Python基础之输入,输出与高阶赋值详解

本文链接: https://www.lsjlt.com/news/158102.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python基础之输入,输出与高阶赋值详解
    目录1. 输入、输出与注释1.1 获取用户输入1.2 格式化输出1.2.1 基本方法1.2.2 format 格式化函数1.3 注释2. 高阶赋值语句2.1 赋值运算符2.2 并行赋...
    99+
    2022-11-12
  • python基础之输入与输出
    目录Python的输入与输出输出输入总结Python的输入与输出 输出 通过字符串格式化优化不必要的重复输出 %占位符来优化 # 输出 % 占位符,实现字符串可视化输出 na...
    99+
    2022-11-12
  • Python输入输出与高阶赋值的方法是什么
    本篇内容主要讲解“Python输入输出与高阶赋值的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python输入输出与高阶赋值的方法是什么”吧!1. 输入、输出与注释1.1 获取用户输...
    99+
    2023-06-25
  • python的赋值语句和基本输入输出详解
    目录赋值语句直接赋值:增量赋值: 链式赋值: 多重赋值:语法糖:基本输入:input()函数:eval()函数: 基本输出:print()函数:print函数-格式化模板总结 顺序结...
    99+
    2022-11-12
  • Python编程基础之输入与输出
    目录一、IPO模型 二、基本输入 - input()函数1、函数格式2、参数说明3、实例演示(1)接收字符串数据(2)接收整型数据(3)接收浮点型数据(4)容易出现的错误三、基本输出...
    99+
    2022-11-12
  • C++基础学习之输入输出流详解
    目录1. 输入输出流2. 文件输入输出3. 格式化输入输出4. 字符串输入输出5. 空格处理C++是一种广泛应用的编程语言,其输入和输出是程序所必须的基本操作之一。输入是指从外部获取...
    99+
    2023-05-17
    C++输入输出流 C++输入流 C++输出流
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作