龙空技术网

Python入门教程04——基本输入输出

快来学英语 119

前言:

而今看官们对“python标准输入输出”大约比较注意,朋友们都需要剖析一些“python标准输入输出”的相关内容。那么小编同时在网摘上搜集了一些对于“python标准输入输出””的相关内容,希望大家能喜欢,各位老铁们快快来了解一下吧!

基本输入

Python使用input()函数输入数据,其基本语法如下:

 a = input("请输入数据:") print(a)

input()函数将用户输入的内容作为字符串返回。用户按【Enter】键结束输入,【Enter】键之前的全部字符均作为输入内容。指定变量时,变量将保存输入的字符串。

如果需要输入整数或小数,则应使用int()float()函数转换数据类型,例如:

 a=input('请输入一个整数:')        # 请输入一个整数:5 print(type(a))                  # 输出a的类型 <class 'str'> a+1                             # 因为a中是一个字符串,试图执行加法运算,所以出错 ''' 结果: 请输入一个整数:1 <class 'str'> Traceback (most recent call last): File "/home/lyujch/mu_code/py/run.py", line 3, in <module> '''int(a) + 1    # 使用int()函数将a转化为整数类型

eval()函数可返回字符串运算后的内容,例如:

 a = eval('123')          # 等同于a=123 print(a)                 # 123 print(type(a))           # <class 'int'> x = 10 a=eval('x+20')           # 等同于a=x+20 print(a)                 # 30 a = eval(input('请输入一个整数或小数:'))    # 请输入一个整数或小数:12 print(a)                                     # 12 print(type(a))                               # <class 'int'> a=eval(input('请输入一个整数或小数:'))      # 请输入一个整数或小数:12.34 print(a)                                     # 12.34 print(type(a))                               # <class 'float'>
基本输出

Python使用print()函数进行输出,其语法格式如下:

 print([obj1, ...][, sep=''] [, end='\n'][, file=sys.stdout])
print()函数的所有参数均可省略。无参数时,print()函数输出一个空行。print()函数可同时输出一个或多个数据,默认使用空格分隔,例如:
print(123) # 输出一个数据 123print(123, 'abc', 45, 'book') # 输出多个数据 123 abc 45 book
print()函数可用sep参数指定分隔符号,例如:
 print(123, 'abc', 45, 'book', sep='#') # 指定符号'#'作为输出分隔符 123#abc#45#book
print()函数可用end参数指定输出结尾符号,默认为换行符,例如:
print('price');print(100) # 默认输出结尾,两个数据输出在两行'''结果:price100'''print('price',end='_');print(100) # 指定下划线为输出结尾符号,两个数据输出在一行'''结果:price_100'''
print()函数可用file参数指定输出到文件,默认是标准输出流sys.stdout,即命令行。例如:
datafile = open(r'd:\data.txt', 'w') # 打开文件print(123, 'abc', 45, 'book', file=datafile) # 用file参数指定输出文件data.txtdatafile.close() # 关闭文件

上述代码创建了一个data.txt文件,print()函数将数据输出到该文件。可用记事本打开data.txt文件查看其内容。

如果觉得我写的还不错,就请关注我吧,我主页会更新Python系列完整课程。您的鼓励和支持是我创作的最大动力。

标签: #python标准输入输出 #python中标准输入输出分别用哪几个函数 #python中基本输入输出函数有 #python 结束input