1、input()函数
Python提供了内置函数input(),用于接收用户的键盘输入,该函数的一般用法为:
x = input(“提示文字”)
例如:
>>>name = input("请输入名字:")
请输入名字:小明
注意:Python中无论输入的是数字还是字符串,input()函数返回的结果都是字符串,例如:
>>>x = input("请输入:")
请输入:1
>>>print(type(x))
<class 'str'>
>>>x = input("请输入:")
请输入:'1'
>>>print(type(x))
<class 'str'>
>>>x = input("请输入:")
请输入:"1"
>>>print(type(x))
<class 'str'>
从上述代码可以看出,无论是输入整数1,还是字符串‘1’或者“1”,input()函数返回值都是字符串。如果需要接收数值,则可以通过类型转换来得到,例如:
>>>x = int(input("请输入:"))
请输入:1
>>>print(type(x))
<class 'int'>
2、print()函数
Python提供了内置函数print()将结果输出到控制台上,其基本语法格式如下:
print(输出的内容)
其中,输出的内容可以是数值和字符串,也可以是表达式,例如:
>>>print("abcd")
abcd
>>>x = 1
>>>print(x)
1
>>>y = 2
>>>print(y)
2
>>>print(x+y)
3
print()函数默认是换行的,即输出语句后自动切换到下一行,如果要实现输出不换行的功能,可以设置end=’ ',例如:
print("abc")
print("123")
print("def",end='')
print("xyz")
'''
执行结果如下:
abc
123
defxyz
'''
默认情况下,Python将结果输出到IDLE或者标准控制台,实际上,在输出时也可以重定向,例如可以把结果输出到指定文件,例如:
>>>fp = open(r'C:\abc.txt','a+')
>>>print("abc,123",file=fp)
>>>fp.close()
上述代码执行以后,可以看到在C盘生成了abc.txt文件,打开可以看到abc,123
除了上述之外,Python还可以使用%进行格式化输出
(1)整数的输出
%o:输出八进制整数;
%d:输出十进制整数;
%x:输出十六进制整数;
举例如下:
# 打印8进制的10
>>>print('%o'%10)
12
# 打印10进制的10
>>>print('%d'%10)
10
# 打印16进制的10
>>>print('%x'%10)
a
(2)浮点数的输出
%f:保留小数点后6位有效数字,如果是%.3f,则保留3位小数;
%e:保留小数点后6位有效数字,按照指数形式输出,如果是%.3e,则保留3位小数,使用科学记数法;
%g:如果有6位有效数字,则使用小数方式,否则使用科学记数法,如果是%.3g,则保留3位有效数字,使用小数方式或者科学记数法。
举例如下:
# 默认保留6位小数
>>>print('%f'%3.14)
3.140000
# 取1位小数
>>>print('%.1f'%3.14)
3.1
# 默认6位小数,用科学记数法
>>>print('%e'%3.14)
3.140000e+00
# # 默认6位小数,用科学记数法
>>>print('%.3e'%3.14)
3.140e+00
# 默认6位有效数字
>>>print('%g'%3.1415926)
3.14159
# 取7位有效数字
>>>print('%.7g'%3.1415926)
3.141593
# 取2位有效数字,自动切换为科学记数法
>>>print('%.2g'%3.1415926)
(3)字符串输出
%s:字符串输出;
%10s:右对齐,占位符10位;
%-10s;左对齐,占位符10位;
%.2s;截取2位字符串;
%10.2s;10位占位符,截取两位字符串。
举例如下:
# 字符串输出
>>>print('%s'%'hello world')
hello world
# 右对齐,取20位,用空格补位,空格不会显示出来
>>>print('%20s'%'hello world')
hello world
# 左对齐,取20位,用空格补位,空格不会显示出来
>>>print('%-20s'%'hello world')
hello world
# 取2位
>>>print('%.2s'%'hello world')
he
# 取2位,右对齐,同样补位
>>>print('%10.2s'%'hello world')
he
# 取2位,左对齐,同样补位
>>>print('%-10.2s'%'hello world')
he
使用“f-字符串"进行格式化输出,基本表达式如下:
print(f’{表达式}')
举例如下:
>>>name = '小明'
>>>age = 10
>>>print(f'姓名:{name}, 年龄:{age}')
姓名:小明, 年龄:10
使用"format函数"进行格式化输出,该函数可以把字符串作为一个模板,通过传入参数的参数进行格式化,使用”{}“作为特殊字符代替”%“,三种用法如下:
不带编号的“{}”;
带数字编号,可以调换显示的顺序,如“{1}”,“{2}”;
带关键字的,如“{a}”,“{b}”;
# 不带字段
>>>print('{} {}'.format('hello','world'))
hello world
# 带数字编号
>>>print('{0} {1}'.format('hello','world')) #
hello world
# 带数字编号,打乱顺序
>>>print('{0} {1} {0}'.format('hello','world'))
hello world hello
# 带数字编号,打乱顺序
>>>print('{1} {1} {0}'.format('hello','world'))
world world hello
# 带关键字,打乱顺序
>>>print('{a} {b} {a}'.format(b='hello',a='world'))
world hello world
文章详细介绍了Python中的input()函数用于接收用户输入并解释了其返回类型,以及print()函数的基本用法和格式化输出,包括整数、浮点数和字符串的输出格式。
9979

被折叠的 条评论
为什么被折叠?



