詳解Python中最常用的10個內(nèi)置函數(shù)
1. print()
print()
函數(shù)是Python中最基本的函數(shù)之一,用于將文本內(nèi)容輸出到終端。它通常用于調(diào)試和輸出程序的運行結(jié)果。
示例代碼:
print("Hello, World!")
2. len()
len()
函數(shù)用于獲取數(shù)據(jù)結(jié)構(gòu)(如字符串、列表、元組、字典等)的長度。它返回數(shù)據(jù)結(jié)構(gòu)中元素的數(shù)量。
示例代碼:
my_list = [1, 2, 3, 4, 5] length = len(my_list) print("Length of the list:", length)
3. input()
input()
函數(shù)用于從用戶獲取輸入,并將輸入的內(nèi)容以字符串的形式返回。這對于與用戶進行交互非常有用。
示例代碼:
name = input("Enter your name: ") print("Hello, " + name)
4. range()
range()
函數(shù)用于生成一個整數(shù)序列,通常與for
循環(huán)一起使用,用于迭代一定范圍內(nèi)的整數(shù)。
示例代碼:
for i in range(5): print(i)
5. list(), tuple(), dict()
這些函數(shù)用于創(chuàng)建列表、元組和字典,分別從可迭代對象(如字符串、列表、元組等)中生成新的數(shù)據(jù)結(jié)構(gòu)。
示例代碼:
string = "Hello" my_list = list(string) my_tuple = tuple(string) my_dict = dict(name="Alice", age=30)
6. max() 和 min()
max()
和min()
函數(shù)分別用于查找可迭代對象中的最大值和最小值。
示例代碼:
numbers = [10, 5, 8, 20, 3] maximum = max(numbers) minimum = min(numbers) print("Max:", maximum) print("Min:", minimum)
7. sum()
sum()
函數(shù)用于計算可迭代對象中的所有元素的和。
示例代碼:
numbers = [1, 2, 3, 4, 5] total = sum(numbers) print("Sum:", total)
8. abs()
abs()
函數(shù)用于獲取數(shù)字的絕對值,無論數(shù)字是正數(shù)還是負數(shù)。
示例代碼:
number = -10 absolute_value = abs(number) print("Absolute value:", absolute_value)
9. sorted()
sorted()
函數(shù)用于對可迭代對象進行排序,返回一個新的已排序列表??梢灾付ń敌蚺判?。
示例代碼:
numbers = [5, 3, 8, 1, 2] sorted_numbers = sorted(numbers) print("Sorted numbers:", sorted_numbers)
10. type()
type()
函數(shù)用于獲取變量或?qū)ο蟮念愋汀?/p>
示例代碼:
x = 5 y = "Hello" print("Type of x:", type(x)) print("Type of y:", type(y))
這些內(nèi)置函數(shù)是Python編程中的基本工具,它們在日常編程中頻繁使用。了解它們的用途和用法可以使您更有效地編寫Python代碼。
到此這篇關(guān)于詳解Python中最常用的10個內(nèi)置函數(shù)的文章就介紹到這了,更多相關(guān)Python最常用的內(nèi)置函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3 使用函數(shù)求兩個數(shù)的和與差
這篇文章主要介紹了python3 使用函數(shù)求兩個數(shù)的和與差,具有很好的參考價值,希望對大家有所幫助。2021-05-05Gradio構(gòu)建交互式Python應(yīng)用使用示例詳解
這篇文章主要為大家介紹了Gradio構(gòu)建交互式Python應(yīng)用使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12pandas中.loc和.iloc以及.at和.iat的區(qū)別說明
這篇文章主要介紹了pandas中.loc和.iloc以及.at和.iat的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04django 按時間范圍查詢數(shù)據(jù)庫實例代碼
這篇文章主要介紹了django 按時間范圍查詢數(shù)據(jù)庫實例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02