Python 程序设计讲义(5):Python 的基本用法——数据的输入与输出
Python 程序设计讲义(5):Python 的基本用法——数据的输入与输出
目录
- Python 程序设计讲义(5):Python 的基本用法——数据的输入与输出
- 一、输入函数 input()
- 二、数据处理函数 eval()
- 三、输出函数 print()
- 1、输出单个信息
- 2、输出多个信息
一、输入函数 input()
input() 函数是 Python 的一个内置函数,用来接收用户的键盘输入。input() 函数可以包含提示信息。
注意:无论用户输入什么内容, input() 的返回值都是 str 类型。
该函数的语法如下:
input(提示性文字)
例如:
a=input("请输入:")
print(a)
print(type(a))运行结果为:
# 输入整数50,a的类型为str
请输入:50
50
<class 'str'># 输入浮点数58.7,a的类型为str
请输入:58.7
58.7
<class 'str'># 输入字符串 hello world,a的类型为str
请输入: hello worldhello world
<class 'str'># 输入逻辑值 True,a的类型为str
请输入: TrueTrue
<class 'str'>
二、数据处理函数 eval()
eval() 函数将参数根据数据的格式转化为相应的数据类型(相当于去掉字符串的引号)。当参数为表达式时,返回表达式的运算结果。
语法如下:
eval(x)
例如:
a=eval(input("请输入:"))
print(a)
print(type(a))运行结果为:
# 输入整数50,a的类型为int
请输入:50
50
<class 'int'># 输入浮点数58.7,a的类型为float
请输入:58.7
58.7
<class 'float'># 输入表达式50+25.7,a的值为表达式的值,类型为float
请输入:50+25.7
75.7
<class 'float'># 输入字符串 hello world,出现如下的错误。原因是eval()函数把字符串的引号去掉了。
请输入:hello world
Traceback (most recent call last):File "C:\Users\wgx58\PycharmProjects\PythonProject\hello.py", line 1, in <module>a=eval(input("请输入:"))~~~~^^^^^^^^^^^^^^^^^^File "<string>", line 1hello world^^^^^
SyntaxError: invalid syntax
# 输入字符串必须添加引号(单引号或双引号都可以)
请输入:'hello world'
hello world
<class 'str'># 输入逻辑值 True,a的类型为bool
请输入:True
True
<class 'bool'>
三、输出函数 print()
print() 函数用来在屏幕上输出信息。根据输出内容的不同,有两种格式。
1、输出单个信息
格式如下:
print(输出信息)
例如:
a,b,c,d=20,58.5,'hello python',True
print(a)
print(b)
print(c)
print(d)运行结果为:
20
58.5
hello python
True
2、输出多个信息
格式如下:
print(输出信息1, 输出信息2, ...)
例如:
a,b,c,d=20,58.5,'hello python',True
print(a,b,c,d)运行结果为:
20 58.5 hello python True