Python은 프로그래밍 언어 인기 지수 PYPL에서 여러 번 1위를 차지했습니다.
코드 가독성과 간단한 구문으로 인해 가장 간단한 언어로 간주됩니다.
NumPy, Pandas, TensorFlow와 같은 다양한 AI 및 기계 학습 라이브러리의 풍부함은 Python의 핵심 요구 사항 중 하나입니다.
데이터 과학자이거나 AI/기계 학습의 초보자라면 Python이 여정을 시작하기에 적합한 선택입니다.
이번에는 Xiao F가 Python 프로그래밍에 대한 몇 가지 기본 지식을 탐구하도록 안내할 것입니다. 이는 간단하지만 매우 유용합니다.
- Directory
- 데이터 유형
- Variables
- List
- Collection
- Dictionary
- Annotation
- 기본 기능
- 조건문
- 루프문
- 함수
- 예외 처리
- 문자열 연산
- 정규식
1. 데이터 유형
데이터 유형은 변수에 저장할 수 있는 데이터 사양입니다. 인터프리터는 유형에 따라 변수에 메모리를 할당합니다.
다음은 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'
출력 결과는 다음과 같습니다.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.

ToaccesselementsInapyThonlist, 사용 인덱싱, 부정적인 인덱싱, 슬라이스, 오리 화.

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
