1. 程式人生 > 實用技巧 >Python基本語法總結(三) 常用內建函式

Python基本語法總結(三) 常用內建函式

help()函式

help() 函式用於檢視函式或模組用途的詳細說明。

>>> help([].append) #列表的append()函式用法
Help on built-in function append:

append(object, /) method of builtins.list instance
    Append object to the end of the list.

>>> help(hash)  #hash()函式用法
Help on built-in function hash in module builtins:

hash(obj, /)
    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

>>> help('abc') #string用法
Squeezed text(339 lines). ....

input()函式

利用input()函式獲取使用者輸入的字串

str = input(tips)

input讀取到的資料會以字串的方式存入str中,tips表示提示資訊,告訴使用者要輸入什麼

a = input('請輸入數字a:')
b= input('請輸入數字b:')

print('a的型別為:',type(a))
print('b的型別為:',type(b))

c= int(a)+int(b)    #型別轉換
print('c的型別為:',type(c))
print('c = a+b = ', c) 

輸出

請輸入數字a:10
請輸入數字b:20
a的型別為: <class 'str'>
b的型別為: <class 'str'>
c的型別為: <class 'int'>
c = a+b =  30

print()函式

print()函式定義如下:

print (value,...,sep='',end='\n',file=sys.stdout,flush=False)
  • sep引數代表分隔符,預設為空格
  • end引數代表輸出結束後的追加值,預設為換行符\n
  • file引數指定print()函式的輸出目標,預設值為 sys.stdout,該預設值代表了系統標準輸出,也就是螢幕,可以改變該引數讓print()輸出到指定檔案
  • flush引數用於控制輸出快取,預設為False,一般不用管
    name = 'John'
    age = 18
    sex = 'man'
    print('Name:', name, 'Age:', 18, 'Sex:', sex)

    print('Name:', name, 'Age:', 18, 'Sex:', sex, sep='|')

    print('Name:', name, 'Age:', 18, 'Sex:', sex, end='****\n')

    f = open('D:\\test.txt', 'w')
    print('Name:', name, 'Age:', 18, 'Sex:', sex, file=f)
    f.close()

輸出結果:

Name: John Age: 18 Sex: man
Name:|John|Age:|18|Sex:|man #分割符換為了'|'
Name: John Age: 18 Sex: man**** #結尾變為了'****\n'

檔案被成功寫入

字串格式化輸出

print() 函式使用以%開頭的轉換說明符對各種型別的資料進行格式化輸出。

name = 'John'
age = 18
sex = 'man'

print('Name:%s'%name , 'Age:%d'%age, 'Sex:%s'%sex)
print('Name:%s Age:%d Sex:%s'%(name,age,sex))   #多個轉換符對應多個表示式,記得加小括號()

執行結果:

Name:John Age:18 Sex:man
Name:John Age:18 Sex:man

型別轉換函式

函式 作用
int(x) 將 x 轉換成整數型別
float(x) 將 x 轉換成浮點數型別
complex(real,[,imag]) 建立一個複數
str(x) 將 x 轉換為字串
repr(x) 將 x 轉換為表示式字串
eval(str) 計算在字串中的有效 Python 表示式,並返回一個物件
chr(x) 將整數 x 轉換為一個字元
ord(x) 將一個字元 x 轉換為它對應的整數值
hex(x) 將一個整數 x 轉換為一個十六進位制字串
oct(x) 將一個整數 x 轉換為一個八進位制的字串

在型別轉換時要保證傳入引數有效,否則會報錯,例如不能將'fff'傳入int()函式中:

.
>>> int('fff')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    int('fff')
ValueError: invalid literal for int() with base 10: 'fff'
>>> 

len()函式

len() 方法返回物件(字元、列表、元組等)長度或專案個數。


>>> a=10
>>> len(a)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    len(a)
TypeError: object of type 'int' has no len()
>>> b=[1,2,3,]
>>> len(b)
3
>>> c=('a',[1,2],1.4,'ffff')
>>> len(c)
4
>>> 

range()函式

python range() 函式可建立一個整數列表,一般用在 for 迴圈中。
range()函式定義如下:

range(start, stop[, step])
# start:計數開始,預設為0,range(5) 等價於 range(0,5)
# stop:計數結束,區間範圍為[start,stop)
# step:增加步長,預設為1
>>>range(10)        # 從 0 開始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 從 1 開始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步長為 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)  # 步長為 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 負數
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

常用寫法:

for idx in range(len(list))
    #...

type()函式

函式定義如下:

type(object)
type(name, bases, dict)

傳入一個引數則返回物件型別:

>>> type(1)
<class 'int'>
>>> type(1.0)
<class 'float'>
>>> type('a')
<class 'str'>

傳入三個引數返回新的型別物件

id()函式

id() 函式返回物件的唯一識別符號,識別符號是一個整數,即所謂的地址

>>> a=10
>>> b=a
>>> id(a)
140704039180224
>>> id(b)
140704039180224
>>> a=[1,2,3]
>>> b=a # b是a的引用
>>> c=a[:]  # c是a的拷貝
>>> id(a)
2420004672192
>>> id(b)
2420004672192   # id(b) = id(a)
>>> id(c)
2420004671744   # id(c) != id(a)
>>> 

dir()函式

dir() 函式不帶引數時,返回當前範圍內的變數、方法和定義的型別列表;帶引數時,返回引數的屬性、方法列表。如果引數包含方法__dir__(),該方法將被呼叫。如果引數不包含__dir__(),該方法將最大限度地收集引數資訊。

>>> dir()   #返回當前作用域內變數、方法和定義的型別列表
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir([]) #返回列表的屬性、方法列表
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

locals()函式

locals() 函式會以字典型別返回當前位置的全部區域性變數

>>> a=10
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 10}
>>> 

min()函式和max()函式

min()函式返回給定引數的最小值,引數可以是序列,但是要保證各引數之間兩兩可以比較,也可以傳入列表、元組等。

>>> min(10,20,-100) 
-100
>>> min(1,2,3.5,4)  # int 和f loat 可比較
1   
>>> min('a','b')    # str 可比較
'a' 
>>> min('a',10)     # str 和 int 不可比較
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    min('a',10)
TypeError: '<' not supported between instances of 'int' and 'str'
>>> li=[10,3,4,29,4,5]
>>> min(li) # 可傳入列表
3

max()函式和min()函式同理