Python的基本输入和基本输出
基本输入
input函数用于获得用户输入数据
如:变量=input('提示字符串')
变量和提示字符串都可以省略,用户输入以字符串形式返回给变量。用户按Enter键完成输入,Enter之前所有内容作为输入字符串赋给变量。
如:
>>>a=input('请输入数据:')
请输入字符串:'abc' 123,456 "Python"
>>>a
'abc' 123,456 "Python"
a=input('请输入数据:')
请输入字符串:'abc' 123,456 "Python"
>>>a
'abc' 123,456 "Python"
如果输入为int或float型,则需要先输入字符串,然后使用变量时加int(a)。
如输入a后执行a+1操作,则:
>>>int(a)+1
>>>int(a)+1
否则会出现TypeError异常
如果使用input输入数据,没有输入任何数据,使用Ctrl+Z组合件终端输入,则会产生EOFError异常。
基本输出
使用print函数进行基本输出操作,基本格式如下
print([obj1,...][,sep=' '][,end='\n'][,file=sys.stdout])
[]表示可以省略的参数,即全部都可以省略,同时后三个参数省略表示使用上述的默认值(等号指定的默认值)
sep表示分隔符,即第一个参数中obj1,obj2...之间的分隔符,默认’ ‘
end表示结尾符,即句末的结尾符,默认为’\n‘
file表示输出位置,即输出到文件还是命令行,默认为sys.stdout即命令行(终端)
print()输出空行,即使用默认的结尾符,默认为\n,默认的输出文件为标准输出文件
print(123) #输出123
print(123,'abc',45,'book') #使用默认的分隔符sep=' ',即输出:123 abc 45 book
print(123,'abc', 45, 'book', sep='#', end='=');print('lalalala') #即输出:123#abc#45#book=lalalala
file1=open('data.txt','w') #打开文件
print(123,'abc',45,'book',file=file1) #用file参数指定输出到文件
file1.close() #关闭文件
print(open('data.txt'.read)) #输出从文件中读取的内容
>>>print()
>>>print(123)
123
>>>print(123,'abc',45,'book')
123 abc 45 book
>>>print(123,'abc', 45, 'book', sep='#', end='=');print('lalalala')
123#abc#45#book=lalalala
>>>file1=open('data.txt','w')
>>>print(123,'abc',45,'book',file=file1)
>>>file1.close()
>>>print(open('data.txt'.read))
123 abc 45 book
#这里有空行是因为本身写入时有换行,本次打印又有换行
>>>
print()
>>>print(123)
123
>>>print(123,'abc',45,'book')
123 abc 45 book
>>>print(123,'abc', 45, 'book', sep='#', end='=');print('lalalala')
123#abc#45#book=lalalala
>>>file1=open('data.txt','w')
>>>print(123,'abc',45,'book',file=file1)
>>>file1.close()
>>>print(open('data.txt','r').read())
123 abc 45 book
#这里有空行是因为本身写入时有换行,本次打印又有换行
>>>