Python的基本輸入和基本輸出

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
#這裏有空行是因爲本身寫入時有換行,本次打印又有換行
>>>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章