一、內建函數
內建函數是python自帶的函數方法,拿來就可以用,比方說zip 、filter、isinstance等。
下面是Python官檔給出的內建函數列表,相當的齊全。
下面幾個是常見的內建函數:
1、<span style="font-size: 18px;"># enumerate</span>
##(iterable,start=0)
enumerate()是python的內建函數,是列舉、列舉的意思對於一個可迭代的(iterable)/可遍歷的物件(如列表、字串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值在python中enumerate的用法多用於在for循環中得到計數
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
2、<span style="font-size: 18px;">zip</span>
(*iterables,strict=False)
zip( ) 函數用於將可迭代的物件作為參數,將物件中對應的元素打包成一個個元組,然後傳回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則傳回列表長度與最短的物件相同,利用 * 號運算符,可以將元組解壓縮為列表。 zip(iterable1,iterable2, ...)
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
3、<span style="font-size: 18px;">filter</span>
(function,iterable)
filter是將一個序列過濾,傳回迭代器的對象,移除不滿足條件的序列。 filter(function,data)function作為條件選擇函數比如說定義一個函數來檢查輸入數字是否為偶數。如果數字為偶數,它將傳回True,否則傳回False。
def is_even(x): if x % 2 == 0: return True else: return False
然後使用filter對某個清單進行篩選:
l1 = [1, 2, 3, 4, 5] fl = filter(is_even, l1) list(fl)
4、<span style="font-size: 18px;">isinstance</span>
(object,classinfo)
「isinstance」是用來判斷某一個變數或是物件是不是屬於某種類型的一個函數
如果參數object是classinfo的實例,或是object是classinfo類別的子類別的一個實例, 傳回True。如果object不是給定類型的對象,則傳回結果總是 False
>>>a = 2 >>> isinstance (a,int) True >>> isinstance (a,str) False >>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True True
#5、<span style="font-size: 18px;">eval</span>
##(expression[,globals[,locals]])
eval用來將字串str當成有效的表達式來求值並傳回計算結果表達式解析參數expression並作為Python 表達式進行求值(技術上是條件列表),並採用globals和locals字典作為全域和局部命名空間。>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
常用句式
在日常程式碼過程中,其實有很多常用的句式,出現頻率非常高,也是大家約定俗成的寫法。
1、format字串格式化
format把字串當成一個模板,透過傳入的參數來格式化,非常實用且強大
# 格式化字符串 print('{} {}'.format('hello','world')) # 浮点数 float1 = 563.78453 print("{:5.2f}".format(float1))######2、連接字串################使用連接兩個字串#######
string1 = "Linux" string2 = "Hint" joined_string = string1 + string2 print(joined_string)
3、if...else条件语句
Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。其中if...else语句用来执行需要判断的情形。
# Assign a numeric value number = 70 # Check the is more than 70 or not if (number >= 70): print("You have passed") else: print("You have not passed")
4、for...in、while循环语句
循环语句就是遍历一个序列,循环去执行某个操作,Python 中的循环语句有 for 和 while。for循环
# Initialize the list weekdays = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday","Friday", "Saturday"] print("Seven Weekdays are:n") # Iterate the list using for loop for day in range(len(weekdays)): print(weekdays[day])
while循环
# Initialize counter counter = 1 # Iterate the loop 5 times while counter < 6: # Print the counter value print ("The current counter value: %d" % counter) # Increment the counter counter = counter + 1
5、import导入其他脚本的功能
有时需要使用另一个 python 文件中的脚本,这其实很简单,就像使用 import 关键字导入任何模块一样。「vacations.py」
# Initialize values vacation1 = "Summer Vacation" vacation2 = "Winter Vacation"
比如在下面脚本中去引用上面vacations.py中的代码
# Import another python script import vacations as v # Initialize the month list months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # Initial flag variable to print summer vacation one time flag = 0 # Iterate the list using for loop for month in months: if month == "June" or month == "July": if flag == 0: print("Now",v.vacation1) flag = 1 elif month == "December": print("Now",v.vacation2) else: print("The current month is",month)
6、列表推导式
Python 列表推导式是从一个或者多个迭代器快速简洁地创建数据类型的一种方法,它将循环和条件判断结合,从而避免语法冗长的代码,提高代码运行效率。能熟练使用推导式也可以间接说明你已经超越了 Python 初学者的水平。
# Create a list of characters using list comprehension char_list = [ char for char in "linuxhint" ] print(char_list) # Define a tuple of websites websites = ("google.com","yahoo.com", "ask.com", "bing.com") # Create a list from tuple using list comprehension site_list = [ site for site in websites ] print(site_list)
7、读写文件
与计算的交互式Python最常使用的场景之一,比如去读取D盘中CSV文件,然后重新写入数据再保存。这就需要python执行读写文件的操作,这也是初学者要掌握的核心技能。
#Assign the filename filename = "languages.txt" # Open file for writing fileHandler = open(filename, "w") # Add some text fileHandler.write("Bashn") fileHandler.write("Pythonn") fileHandler.write("PHPn") # Close the file fileHandler.close() # Open file for reading fileHandler = open(filename, "r") # Read a file line by line for line in fileHandler: print(line) # Close the file fileHandler.close()
8、切片和索引
形如列表、字符串、元组等序列,都有切片和索引的需求,因为我们需要从中截取数据,所以这也是非常核心的技能。
var1 = 'Hello World!' var2 = "zhihu" print ("var1[0]: ", var1[0]) print ("var2[1:5]: ", var2[1:5])
9、使用函数和类
函数和类是一种封装好的代码块,可以让代码更加简洁、实用、高效、强壮,是python的核心语法之一。定义和调用函数
# Define addition function def addition(number1, number2): result = number1 + number2 print("Addition result:",result) # Define area function with return statement def area(radius): result = 3.14 * radius * radius return result # Call addition function addition(400, 300) # Call area function print("Area of the circle is",area(4))
定义和实例化类
# Define the class class Employee: name = "Mostak Mahmud" # Define the method def details(self): print("Post: Marketing Officer") print("Department: Sales") print("Salary: $1000") # Create the employee object emp = Employee() # Print the class variable print("Name:",emp.name) # Call the class method emp.details()
10、错误异常处理
编程过程中难免会遇到错误和异常,所以我们要及时处理它,避免对后续代码造成影响。所有的标准异常都使用类来实现,都是基类Exception的成员,都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。异常的处理过程、如何引发或抛出异常及如何构建自己的异常类都是需要深入理解的。
# Try block try: # Take a number number = int(input("Enter a number: ")) if number % 2 == 0: print("Number is even") else: print("Number is odd") # Exception block except (ValueError): # Print error message print("Enter a numeric value")
小结
当然Python还有很多有用的函数和方法,需要大家自己去总结,这里抛砖引玉,希望能帮助到需要的小伙伴。
以上是Python最常用的函數、基礎語句有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。