初学__Python——Python的基本输入输出函数
生活随笔
收集整理的這篇文章主要介紹了
初学__Python——Python的基本输入输出函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄
一、接受輸入的input函數(shù)
二、輸出內(nèi)容的print函數(shù)
一、接受輸入的input函數(shù)
input 函數(shù)將用戶輸入的內(nèi)容作為字符串形式返回,如果想要獲取數(shù)字,可以使用 int 函數(shù)將字符串轉(zhuǎn)為數(shù)字。
//在Python的交互式命令行中運(yùn)行 Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> input('Input your name:') Input your name:tutu 'tutu' >>> name = input('Input your name:') Input your name:tutu >>> print(name) tutu >>> year = input('The year:') The year:2013 >>> print(year) 2013 >>> year + 1 Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str //year 加 1,這里導(dǎo)致出錯(cuò),因?yàn)閥ear為字符串型 >>> int(year) + 1 //使用 int 函數(shù)將year轉(zhuǎn)換成整型 2014 >>>說明:位于“>>>”命令提示符之后的內(nèi)容為用戶輸入的語句。如果語句前沒有“>>>”命令提示符,則表示該語句為Python的輸出。但是由于使用了 input 函數(shù),因此在 input 函數(shù)的提示之后需要用戶輸入。
- 在Python中,除了 int 函數(shù)以外,還有以下用于類型相互轉(zhuǎn)換的函數(shù)
| float | 字符串或者整數(shù)? ——>? 浮點(diǎn)型 |
| str | 數(shù)字? ——>? 字符串 |
| chr | ASCLL值? ——>? ASCLL字符 |
| hex | 整數(shù)? ——>? 十六進(jìn)制的字符串 |
| long | 字符串? ——>? 長整型 |
| oct | 整數(shù)? ——>? 八進(jìn)制的字符串 |
| ord | ASCLL字符? ——>? ASCLL值 |
?
?
?
?
?
?
?
?
?
?
?
注:在Python2 中,使用的基本輸入函數(shù)是 raw_input
二、輸出內(nèi)容的print函數(shù)
使用 print 函數(shù)可以輸出Python中的所有數(shù)據(jù)類型的值,而不需要事先指定要輸出的數(shù)據(jù)類型。如果自定義了某一新的類型(或者類),則可以通過重載(__repr__),讓 print 函數(shù)支持對該自定義類型的輸出。
>>> a = 0 # 輸出類型 >>> print(a) # 輸出結(jié)果 0 >>> b = 1 >>> print(a + b) # 輸出表達(dá)式的值 1 >>> print(b) # 輸出 b 的值 1 >>> s = 'hello tutu' # 定義字符串 >>> print(s) # 輸出字符串 hello tutu >>> l = [1, 2, 3] # 定義列表 >>> print(l) # 輸出列表 [1, 2, 3] >>> t = ('a', 'b', 'c') # 定義元組 >>> print(t) # 輸出元組 ('a', 'b', 'c') >>> print(l,t) # 同時(shí)輸出列表和元組 [1, 2, 3] ('a', 'b', 'c') >>> print(l, '\n', t) # 使用換行符 [1, 2, 3]('a', 'b', 'c') >>> for i in t: # 循環(huán)輸出 ... print(i) ... # 在這一行的縮進(jìn)處按一下回車鍵,表示回車結(jié)束 a b c >>>注:在交互式命令狀態(tài)下,用“...”表示縮進(jìn)開始。這里使用的是Python自帶的交互式命令行,需要注意縮進(jìn)。
與50位技術(shù)專家面對面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的初学__Python——Python的基本输入输出函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初学__Python——Python代码
- 下一篇: 初学__Python——Python中文