日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢(xún)
選擇下列產(chǎn)品馬上在線(xiàn)溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
13個(gè)Python必備的知識(shí),建議收藏!

Python在編程語(yǔ)言流行指數(shù)PYPL中已多次排名第一。

創(chuàng)新互聯(lián)網(wǎng)站建設(shè)服務(wù)商,為中小企業(yè)提供網(wǎng)站建設(shè)、網(wǎng)站制作服務(wù),網(wǎng)站設(shè)計(jì),成都網(wǎng)站托管等一站式綜合服務(wù)型公司,專(zhuān)業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競(jìng)爭(zhēng)對(duì)手中脫穎而出創(chuàng)新互聯(lián)。

由于其代碼可讀性和更簡(jiǎn)單的語(yǔ)法,它被認(rèn)為是有史以來(lái)最簡(jiǎn)單的語(yǔ)言。

NumPy、Pandas、TensorFlow等各種AI和機(jī)器學(xué)習(xí)庫(kù)的豐富性,是Python核心需求之一。

如果你是數(shù)據(jù)科學(xué)家或 AI/機(jī)器學(xué)習(xí)的初學(xué)者,那么Python是開(kāi)始你的旅程的正確選擇。

本次,小F會(huì)帶著大家探索一些Python編程的基礎(chǔ)知識(shí),雖然簡(jiǎn)單但都很有用。

  • 目錄
  • 數(shù)據(jù)類(lèi)型
  • 變量
  • 列表
  • 集合
  • 字典
  • 注釋
  • 基本功能
  • 條件語(yǔ)句
  • 循環(huán)語(yǔ)句
  • 函數(shù)
  • 異常處理
  • 字符串操作
  • 正則表達(dá)式

1、數(shù)據(jù)類(lèi)型

數(shù)據(jù)類(lèi)型是可以存儲(chǔ)在變量中的數(shù)據(jù)規(guī)范。解釋器根據(jù)變量的類(lèi)型為變量分配內(nèi)存。

下面是Python中的各種數(shù)據(jù)類(lèi)型。

2、變量

變量是存放數(shù)據(jù)值的容器。

變量可以使用短名稱(chēng)(如x和y)或更具描述性的名稱(chēng)(age、carname、total_volume)。

Python 變量命名規(guī)則:

  • 變量名必須以字母或下劃線(xiàn)字符開(kāi)頭
  • 變量名稱(chēng)不能以數(shù)字開(kāi)頭
  • 變量名只能包含字母數(shù)字字符和下劃線(xiàn)(A-z、0-9和_)
  • 變量名稱(chēng)區(qū)分大小寫(xiě)(age、Age和AGE是三個(gè)不同的變量)
var1 = 'Hello World'
var2 = 16
_unuseful = 'Single use variables'

輸出結(jié)果如下。

3、列表

列表(List)是一種有序和可更改的集合,允許重復(fù)的成員。

它可能不是同質(zhì)的,我們可以創(chuàng)建一個(gè)包含不同數(shù)據(jù)類(lèi)型(如整數(shù)、字符串和對(duì)象)的列表。?

>>> companies = ["apple","google","tcs","accenture"]
>>> print(companies)
['apple', 'google', 'tcs', 'accenture']
>>> companies.append("infosys")
>>> print(companies)
['apple', 'google', 'tcs', 'accenture', 'infosys']
>>> print(len(companies))
5
>>> print(companies[2])
tcs
>>> print(companies[-2])
accenture
>>> print(companies[1:])
['google', 'tcs', 'accenture', 'infosys']
>>> print(companies[:1])
['apple']
>>> print(companies[1:3])
['google', 'tcs']
>>> companies.remove("infosys")
>>> print(companies)
["apple","google","tcs","accenture"]
>>> companies.pop()
>>> print(companies)
["apple","google","tcs"]

4、集合

集合(Set)是一個(gè)無(wú)序和無(wú)索引的集合,沒(méi)有重復(fù)的成員。

對(duì)于從列表中刪除重復(fù)條目非常有用。它還支持各種數(shù)學(xué)運(yùn)算,例如并集、交集和差分。

>>> set1 = {1,2,3,7,8,9,3,8,1}
>>> print(set1)
{1, 2, 3, 7, 8, 9}
>>> set1.add(5)
>>> set1.remove(9)
>>> print(set1)
{1, 2, 3, 5, 7, 8}
>>> set2 = {1,2,6,4,2}
>>> print(set2)
{1, 2, 4, 6}
>>> print(set1.union(set2)) # set1 | set2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> print(set1.intersection(set2)) # set1 & set2
{1, 2}
>>> print(set1.difference(set2)) # set1 - set2
{8, 3, 5, 7}
>>> print(set2.difference(set1)) # set2 - set1
{4, 6}

5、字典

字典是作為鍵值對(duì)的可變無(wú)序項(xiàng)集合。

與其他數(shù)據(jù)類(lèi)型不同,它以【鍵:值】對(duì)格式保存數(shù)據(jù),而不是存儲(chǔ)單個(gè)數(shù)據(jù)。此功能使其成為映射JSON響應(yīng)的最佳數(shù)據(jù)結(jié)構(gòu)。

>>> # example 1
>>> user = { 'username': 'Fan', 'age': 20, 'mail_id': 'codemaker2022@qq.com', 'phone': '18650886088' }
>>> print(user)
{'mail_id': 'codemaker2022@qq.com', 'age': 20, 'username': 'Fan', 'phone': '18650886088'}
>>> print(user['age'])
20
>>> for key in user.keys():
>>> print(key)
mail_id
age
username
phone
>>> for value in user.values():
>>> print(value)
codemaker2022@qq.com
20
Fan
18650886088
>>> for item in user.items():
>>> print(item)
('mail_id', 'codemaker2022@qq.com')
('age', 20)
('username', 'Fan')
('phone', '18650886088')
>>> # example 2
>>> user = {
>>> 'username': "Fan",
>>> 'social_media': [
>>> {
>>> 'name': "Linkedin",
>>> 'url': "https://www.linkedin.com/in/codemaker2022"
>>> },
>>> {
>>> 'name': "Github",
>>> 'url': "https://github.com/codemaker2022"
>>> },
>>> {
>>> 'name': "QQ",
>>> 'url': "https://codemaker2022.qq.com"
>>> }
>>> ],
>>> 'contact': [
>>> {
>>> 'mail': [
>>> "mail.Fan@sina.com",
>>> "codemaker2022@qq.com"
>>> ],
>>> 'phone': "18650886088"
>>> }
>>> ]
>>> }
>>> print(user)
{'username': 'Fan', 'social_media': [{'url': 'https://www.linkedin.com/in/codemaker2022', 'name': 'Linkedin'}, {'url': 'https://github.com/codemaker2022', 'name': 'Github'}, {'url': 'https://codemaker2022.qq.com', 'name': 'QQ'}], 'contact': [{'phone': '18650886088', 'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com']}]}
>>> print(user['social_media'][0]['url'])
https://www.linkedin.com/in/codemaker2022
>>> print(user['contact'])
[{'phone': '18650886088', 'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com']}]

6、注釋

單行注釋?zhuān)跃址?#)開(kāi)頭,后面帶有消息并在行尾結(jié)束。

# 定義用戶(hù)年齡
age = 27
dob = '16/12/1994' # 定義用戶(hù)生日

多行注釋?zhuān)锰厥庖?hào)(""")括起來(lái),你可以將消息放在多行中。

"""
Python小常識(shí)
This is a multi line comment
"""

7、基本功能

print()函數(shù)在控制臺(tái)中打印提供的消息。此外你還可以提供文件或緩沖區(qū)輸入作為在屏幕上打印的參數(shù)。

print(object(s), sep=separator, end=end, file=file, flush=flush)
print("Hello World") # prints Hello World
print("Hello", "World") # prints Hello World?
x = ("AA", "BB", "CC")
print(x) # prints ('AA', 'BB', 'CC')
print("Hello", "World", sep="---") # prints Hello---World

input()函數(shù)用于收集來(lái)自控制臺(tái)的用戶(hù)輸入 。

這里需要注意,input()會(huì)把你輸入的任何內(nèi)容轉(zhuǎn)換為字符串。

因此,如果你將年齡作為整數(shù)值提供,但input()方法將其作為字符串返回,此時(shí)就需要手動(dòng)將其轉(zhuǎn)換為整數(shù)。

>>> name = input("Enter your name: ")
Enter your name: Codemaker
>>> print("Hello", name)
Hello Codemaker

len()可以查看對(duì)象的長(zhǎng)度。如果你輸入一個(gè)字符串,則可以獲取指定字符串中的字符數(shù)。

>>> str1 = "Hello World"
>>> print("The length of the string is ", len(str1))
The length of the string is 11

str()用于將其他數(shù)據(jù)類(lèi)型轉(zhuǎn)換為字符串值。

>>> str(123)
123
>>> str(3.14)
3.14

int()用于將字符串轉(zhuǎn)換為整數(shù)。

>>> int("123")
123
>>> int(3.14)
3

8、條件語(yǔ)句

條件語(yǔ)句是用于根據(jù)特定條件更改程序流程的代碼塊。這些語(yǔ)句只有在滿(mǎn)足特定條件時(shí)才會(huì)執(zhí)行。

在Python中,我們使用if,if-else,循環(huán)(for,while)作為條件語(yǔ)句根據(jù)某些條件來(lái)改變程序的流程。

if-else語(yǔ)句。

>>> num = 5
>>> if (num > 0):
>>> print("Positive integer")
>>> else:
>>> print("Negative integer")

elif語(yǔ)句。

>>> name = 'admin'
>>> if name == 'User1':
>>> print('Only read access')
>>> elif name == 'admin':
>>> print('Having read and write access')
>>> else:
>>> print('Invalid user')
Having read and write access

9、循環(huán)語(yǔ)句

循環(huán)是一個(gè)條件語(yǔ)句,用于重復(fù)某些語(yǔ)句(在其主體中),直到滿(mǎn)足某個(gè)條件。

在Python中,我們通常使用for和while循環(huán)。

for循環(huán)。

>>> # loop through a list
>>> companies = ["apple", "google", "tcs"]
>>> for x in companies:
>>> print(x)
apple
google
tcs
>>> # loop through string
>>> for x in "TCS":
>>> print(x)
T
C
S

range()函數(shù)返回一個(gè)數(shù)字序列,它可以用作for循環(huán)控制。

它基本上需要三個(gè)參數(shù),其中第二個(gè)和第三個(gè)是可選的。參數(shù)是開(kāi)始值、停止值和步進(jìn)數(shù)。步進(jìn)數(shù)是每次迭代循環(huán)變量的增量值。

>>> # loop with range() function
>>> for x in range(5):
>>> print(x)
0
1
2
3
4
>>> for x in range(2, 5):
>>> print(x)
2
3
4
>>> for x in range(2, 10, 3):
>>> print(x)
2
5
8

我們還可以使用else關(guān)鍵字在循環(huán)結(jié)束時(shí)執(zhí)行一些語(yǔ)句。

在循環(huán)結(jié)束時(shí)提供else語(yǔ)句以及循環(huán)結(jié)束時(shí)需要執(zhí)行的語(yǔ)句。

>>> for x in range(5):
>>> print(x)
>>> else:
>>> print("finished")
0
1
2
3
4
finished

while循環(huán)。

>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
0
1
2
3
4

我們可以在while循環(huán)的末尾使用else,類(lèi)似于for循環(huán),當(dāng)條件為假時(shí)執(zhí)行一些語(yǔ)句。

>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
>>> else:
>>> print("Count is greater than 4")
0
1
2
3
4
Count is greater than 4

10、函數(shù)

函數(shù)是用于執(zhí)行任務(wù)的可重用代碼塊。在代碼中實(shí)現(xiàn)模塊化并使代碼可重用,這是非常有用的。

>>> # This prints a passed string into this function
>>> def display(str):
>>> print(str)
>>> return
>>> display("Hello World")
Hello World

11、異常處理

即使語(yǔ)句在語(yǔ)法上是正確的,它也可能在執(zhí)行時(shí)發(fā)生錯(cuò)誤。這些類(lèi)型的錯(cuò)誤稱(chēng)為異常。我們可以使用異常處理機(jī)制來(lái)避免此類(lèi)問(wèn)題。

在Python中,我們使用try,except和finally關(guān)鍵字在代碼中實(shí)現(xiàn)異常處理。

>>> def divider(num1, num2):
>>> try:
>>> return num1 / num2
>>> except ZeroDivisionError as e:
>>> print('Error: Invalid argument: {}'.format(e))
>>> finally:
>>> print("finished")
>>>
>>> print(divider(2,1))
>>> print(divider(2,0))
finished
2.0
Error: Invalid argument: division by zero
finished
None

12、字符串操作

字符串是用單引號(hào)或雙引號(hào)(',")括起來(lái)的字符集合。

我們可以使用內(nèi)置方法對(duì)字符串執(zhí)行各種操作,如連接、切片、修剪、反轉(zhuǎn)、大小寫(xiě)更改和格式化,如split()、lower()、upper()、endswith()、join()和ljust()、rjust()、format()。

>>> msg = 'Hello World'
>>> print(msg)
Hello World
>>> print(msg[1])
e
>>> print(msg[-1])
d
>>> print(msg[:1])
H
>>> print(msg[1:])
ello World
>>> print(msg[:-1])
Hello Worl
>>> print(msg[::-1])
dlroW olleH
>>> print(msg[1:5])
ello
>>> print(msg.upper())
HELLO WORLD
>>> print(msg.lower())
hello world
>>> print(msg.startswith('Hello'))
True
>>> print(msg.endswith('World'))
True
>>> print(', '.join(['Hello', 'World', '2022']))
Hello, World, 2022
>>> print(' '.join(['Hello', 'World', '2022']))
Hello World 2022
>>> print("Hello World 2022".split())
['Hello', 'World', '2022']
>>> print("Hello World 2022".rjust(25, '-'))
---------Hello World 2022
>>> print("Hello World 2022".ljust(25, '*'))
Hello World 2022*********
>>> print("Hello World 2022".center(25, '#'))
#####Hello World 2022####
>>> name = "Codemaker"
>>> print("Hello %s" % name)
Hello Codemaker
>>> print("Hello {}".format(name))
Hello Codemaker
>>> print("Hello {0}{1}".format(name, "2022"))
Hello Codemaker2022

13、正則表達(dá)式

  • 導(dǎo)入regex模塊,import re。
  • re.compile()使用該函數(shù)創(chuàng)建一個(gè)Regex對(duì)象。
  • 將搜索字符串傳遞給search()方法。
  • 調(diào)用group()方法返回匹配的文本。
>>> import re
>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> mob = phone_num_regex.search('My number is 996-190-7453.')
>>> print('Phone number found: {}'.format(mob.group()))
Phone number found: 996-190-7453
>>> phone_num_regex = re.compile(r'^\d+$')
>>> is_valid = phone_num_regex.search('+919961907453.') is None
>>> print(is_valid)
True
>>> at_regex = re.compile(r'.at')
>>> strs = at_regex.findall('The cat in the hat sat on the mat.')
>>> print(strs)
['cat', 'hat', 'sat', 'mat']

好了,本期的分享就到此結(jié)束了,有興趣的小伙伴可以自行去實(shí)踐學(xué)習(xí)。


新聞標(biāo)題:13個(gè)Python必備的知識(shí),建議收藏!
分享地址:http://m.5511xx.com/article/codchjc.html