13가지 필수 Python 지식 제안 모음

王林
풀어 주다: 2023-05-09 15:10:08
앞으로
1569명이 탐색했습니다.

13个 Python 必备的知识,建议收藏!

Python은 프로그래밍 언어 인기 지수 PYPL에서 여러 번 1위를 차지했습니다.

코드 가독성과 간단한 구문으로 인해 가장 간단한 언어로 간주됩니다.

NumPy, Pandas, TensorFlow와 같은 다양한 AI 및 기계 학습 라이브러리의 풍부함은 Python의 핵심 요구 사항 중 하나입니다.

데이터 과학자이거나 AI/기계 학습의 초보자라면 Python이 여정을 시작하기에 적합한 선택입니다.

이번에는 Xiao F가 Python 프로그래밍에 대한 몇 가지 기본 지식을 탐구하도록 안내할 것입니다. 이는 간단하지만 매우 유용합니다.

  • Directory
  • 데이터 유형
  • Variables
  • List
  • Collection
  • Dictionary
  • Annotation
  • 기본 기능
  • 조건문
  • 루프문
  • 함수
  • 예외 처리
  • 문자열 연산
  • 정규식

1. 데이터 유형

데이터 유형은 변수에 저장할 수 있는 데이터 사양입니다. 인터프리터는 유형에 따라 변수에 메모리를 할당합니다.

다음은 Python의 다양한 데이터 유형입니다.

13个 Python 必备的知识,建议收藏!

2. 변수

변수는 데이터 값을 저장하는 컨테이너입니다.

변수는 짧은 이름(예: x 및 y) 또는 더 설명적인 이름(age, carname, total_volume)을 가질 수 있습니다.

Python 변수 명명 규칙:

  • 변수 이름은 문자나 밑줄 문자로 시작해야 합니다.
  • 변수 이름은 숫자로 시작할 수 없습니다.
  • 변수 이름에는 영숫자와 밑줄(A-z, 0-9 및 _)만 포함될 수 있습니다.
  • 변수 이름은 대소문자를 구분합니다(age, Age 및 AGE는 서로 다른 변수입니다).
var1 = 'Hello World'
var2 = 16
_unuseful = 'Single use variables'
로그인 후 복사

출력 결과는 다음과 같습니다.

13个 Python 必备的知识,建议收藏!

3. 리스트

리스트(List)는 중복 회원을 허용하는 순서 있고 변경 가능한 모음입니다.

동질적이지 않을 수도 있지만 정수, 문자열, 객체와 같은 다양한 데이터 유형을 포함하는 목록을 만들 수 있습니다. ‍

>>> 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)는 중복된 멤버가 없는 순서가 없고 인덱스가 없는 세트입니다.

목록에서 중복된 항목을 제거하는 데 매우 유용합니다. 또한 합집합, 교차점, 차이 등 다양한 수학 연산을 지원합니다.

>>> 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. 사전

사전은 키-값 쌍으로 구성된 변경 가능한 순서 없는 항목 모음입니다.

다른 데이터 유형과 달리 개별 데이터를 저장하지 않고 [키:값] 쌍 형식으로 데이터를 저장합니다. 이 기능을 사용하면 JSON 응답을 매핑하는 데 가장 적합한 데이터 구조가 됩니다.

>>> # 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. 댓글

한 줄짜리 댓글로, 파운드 문자(#)로 시작하고 그 뒤에 메시지가 오고 줄 끝에서 끝납니다.

# 定义用户年龄
age = 27
dob = '16/12/1994' # 定义用户生日
로그인 후 복사

여러 줄 주석을 특수 따옴표(""")로 묶어 여러 줄에 메시지를 넣을 수 있습니다.

"""
Python小常识
This is a multi line comment
"""
로그인 후 복사

7. 기본 기능

print() 함수는 제공된 메시지를 콘솔에 인쇄합니다. 추가로 화면에 인쇄하기 위한 매개변수로 파일 또는 버퍼 입력을 제공할 수도 있습니다.

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() 함수는 콘솔에서 사용자 입력을 수집하는 데 사용됩니다.

여기서 input()은 입력한 내용을 인쇄합니다.

연령을 정수 값으로 제공했지만 input() 메서드가 이를 문자열로 반환하는 경우 수동으로 정수로 변환해야 합니다.

>>> name = input("Enter your name: ")
Enter your name: Codemaker
>>> print("Hello", name)
Hello Codemaker
로그인 후 복사

len()에서 개체를 볼 수 있습니다. 문자열을 입력하면 지정된 문자열의 문자 수를 얻을 수 있습니다.

>>> str1 = "Hello World"
>>> print("The length of the stringis ", len(str1))
The length of the stringis 11
로그인 후 복사

str()은 다른 데이터 유형을 문자열 값으로 변환하는 데 사용됩니다.

>>> str(123)
123
>>> str(3.14)
3.14
로그인 후 복사

int()는 문자열을 변환하는 데 사용됩니다.

>>> int("123")
123
>>> int(3.14)
3
로그인 후 복사

8. 조건문

조건문은 특정 조건에 따라 프로그램의 흐름을 변경하는 데 사용되는 코드 블록입니다.

Python에서는 if, if-else, 루프( for, while)은 특정 조건에 따라 프로그램의 흐름을 변경하는 조건문입니다.

>>> num = 5
>>> if (num > 0):
>>>print("Positive integer")
>>> else:
>>>print("Negative integer")
로그인 후 복사

9. 루프 문은 특정 문을 반복하는 데 사용됩니다.

Python에서는 일반적으로 for 및 while 루프를 사용합니다.

>>> 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
로그인 후 복사

range() 함수는 일련의 숫자를 반환하며

기본적으로 필요합니다. 두 번째 및 세 번째 매개변수는 시작 값, 중지 값 및 단계 수입니다.

>>> # 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
로그인 후 복사

else 키워드를 사용하여 마지막에 일부 명령문을 실행할 수도 있습니다.

>>> # 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
로그인 후 복사

for 루프와 유사하게 while 루프의 끝에 else를 사용하여 조건이 false일 때 일부 명령문을 실행할 수 있습니다.

>>> 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、函数

函数是用于执行任务的可重用代码块。在代码中实现模块化并使代码可重用,这是非常有用的。

>>> # This prints a passed string into this function
>>> def display(str):
>>>print(str)
>>>return
>>> display("Hello World")
Hello World
로그인 후 복사

11、异常处理

即使语句在语法上是正确的,它也可能在执行时发生错误。这些类型的错误称为异常。我们可以使用异常处理机制来避免此类问题。

在Python中,我们使用try,except和finally关键字在代码中实现异常处理。

>>> 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、字符串操作

字符串是用单引号或双引号(',")括起来的字符集合。

我们可以使用内置方法对字符串执行各种操作,如连接、切片、修剪、反转、大小写更改和格式化,如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、正则表达式

  • 导入regex模块,import re。
  • re.compile()使用该函数创建一个Regex对象。
  • 将搜索字符串传递给search()方法。
  • 调用group()方法返回匹配的文本。
>>> import re
>>> phone_num_regex = re.compile(r'ddd-ddd-dddd')
>>> 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']
로그인 후 복사

好了,本期的分享就到此结束了,有兴趣的小伙伴可以自行去实践学习。

위 내용은 13가지 필수 Python 지식 제안 모음의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:51cto.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!