서문
Python은 지루한 크리스마스를 없애기 위해 1989년에 거북이 삼촌이 작성한 프로그래밍 언어로, 우아함, 명확성, 단순함이 특징입니다.
Python은 웹 웹 사이트 및 다양한 네트워크 서비스, 시스템 도구 및 스크립트를 개발하는 데 적합하며, 과학 컴퓨팅 등을 위해 다른 언어로 개발된 모듈을 패키지하는 "접착제" 언어로 사용될 수 있습니다.
편집자가 Python을 배우는 세 가지 이유는 다음과 같습니다.
필요한 모든 종류의 데이터를 크롤링하려면 Python을 배우는 것이 좋습니다.
데이터를 분석하고 마이닝하려면 Python을 배우는 것이 좋습니다.
재미있고 흥미로운 일을 하려면 Python을 배우는 것이 좋습니다.
준비
1. 편집기는 최신 버전인 3.6.0을 사용하고 있습니다.
2. Python의 통합 개발 환경인 Open IDLE은 간단하지만 매우 유용합니다. IDLE에는 구문에 대한 색상 강조 표시 기능이 있는 편집기, 디버깅 도구, Python 셸 및 Python 3에 대한 전체 온라인 문서 세트가 포함되어 있습니다.
hello world
1. IDLE에서 print('hello world')
를 입력하고 Enter를 누르면 hello world가 출력됩니다.
PS: 문장 끝에 세미콜론을 추가하든 안 추가하든 상관없습니다;
편집자는 세미콜론을 추가하지 않기로 결정했습니다.
2. sublime을 사용하여 다음 내용으로 hello.py라는 새 파일을 만듭니다.
print('hello world')
Windows에서는 Shift+마우스 오른쪽 버튼을 클릭하고 여기에서 명령 창을 열고 python hello.py
을 실행합니다. hello world를 입력하고 인쇄하세요.
3. sublime을 사용하여 다음 내용으로 hello.py라는 새 파일을 만듭니다.
#!/usr/bin/env python print('hello world')
Linux 또는 Mac 환경에서는 스크립트를 직접 실행할 수 있습니다. 먼저 실행 권한 chmod a+x hello.py
을 추가한 후 ./hello.py
을 실행하세요. 물론 python hello.py
을 사용하여 Windows처럼 스크립트를 실행할 수도 있습니다.
모듈 소개
1. 다음 내용으로 새 name.py를 만듭니다.
name='voidking'
2. python name.py
3. Python 쉘 모드로 들어가서
, import name
을 실행하면 voidking이 인쇄됩니다. print(name.name)
myList = ['Hello', 100, True]
2. 출력 배열print(myList)
3.
, print(myList[0])
4. 끝에 요소 추가 print(myList[-1])
5. 머리에 요소 추가 myList.append('voidking')
6. 🎜> , myList.insert(0,'voidking')
7. 요소 할당myList.pop()
myList.pop(0)
튜플 고정 배열myList[0]='hello666'
1. 배열 정의
, 올바른 정의: myTuple = ('Hello', 100, True)
2. 출력 배열 myTuple1=(1)
myTuple=(1,)
3. 출력 배열 요소 print(myTuple)
4. >
, print(myTuple[0])
if 문 t = ('a', 'b', ['A', 'B'])
ift[2][0]='X'
score = 75 if score>=60: print 'passed'를 누르고 Enter를 두 번 눌러 코드를 실행합니다. if-else
if score>=60:
print('passed')
else:
print('failed')
if-elif-else
if score>=90: print('excellent') elif score>=80: print('good') elif score>=60: print('passed') else: print('failed')loopfor 루프
L = [75, 92, 59, 68]
sum = 0.0
for score in L:
sum += score
print(sum / 4)
while 루프sum = 0
x = 1
while x
breaksum = 0
x = 1
while True:
sum = sum + x
x = x + 1
if x > 100:
break
print(sum)
continueL = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
if x
다중 루프for x in ['A', 'B', 'C']:
for y in ['1', '2', '3']:
print(x + y)
dictdict의 기능은 키 집합 간에 매핑 관계를 설정하는 것입니다. 그리고 일련의 값. d = {
'Adam': 95,
'Lisa': 85,
'Bart': 59,
'Paul': 75
}
print(d)
print(d['Adam'])
print(d.get('Lisa'))
d['voidking']=100
print(d)
for key in d:
print(key+':',d.get(key))
setset는 일련의 요소를 보유하며 이는 목록과 매우 유사하지만 set의 요소는 반복되지 않고 순서가 지정되지 않으므로 dict의 키와 매우 유사합니다. .
s = set(['Adam', 'Lisa', 'Bart', 'Paul']) print(s) s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul']) print(s) len(s) print('Adam' in s) print('adam' in s) for name in s: print(name)
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print(x[0]+':',x[1])
s.add(100) print(s) s.remove(('Adam',95)) print(s)함수내장 함수
del sum L = [x*x for x in range(1,101)] print sum(L)맞춤 함수
def my_abs(x):
if x >= 0:
return x
else:
return -x
my_abs(-100)
도입된 함수 라이브러리import math
def quadratic_equation(a, b, c):
x = b * b - 4 * a * c
if x
변수 매개변수 def average(*args):
if args:
return sum(args)*1.0/len(args)
else:
return 0.0
print(average())
print(average(1, 2))
print(average(1, 2, 2, 3, 4))
슬라이싱리스트 슬라이싱L = ['Adam', 'Lisa', 'Bart', 'Paul']
L[0:3]
L[:3]
L[1:3]
L[:]
L[::2]
역슬라이싱
L[-2:]
L[-3:-1]
L[-4:-1:2]
L = range(1, 101)
L[-10:]
L[4::5][-10:]
PS: range는 순서가 지정된 리스트이며 기본적으로 함수 형식으로 표현됩니다. range 함수를 실행하면 다음과 같은 작업을 수행할 수 있습니다. 목록 형태로 표현됩니다. 문자열 슬라이스def firstCharUpper(s):
return s[0:1].upper() + s[1:]
print(firstCharUpper('hello'))
반복Python의 for 루프는 목록이나 튜플뿐만 아니라 다른 반복 가능한 객체에서도 사용할 수 있습니다. 반복 연산은 집합에 대한 것입니다. 집합이 순서가 있든 없든 for 루프를 사용하여 집합의 각 요소를 순서대로 꺼낼 수 있습니다.
세트는 다음을 포함한 요소 세트를 포함하는 데이터 구조를 나타냅니다.
순서가 지정된 세트: 목록, 튜플, 문자열 및 유니코드
- 순서가 지정되지 않은 집합: set
- 키-값 쌍이 있는 순서가 지정되지 않은 집합: dict
for i in range(1,101): if i%7 == 0: print(i)
L = ['Adam', 'Lisa', 'Bart', 'Paul'] for index, name in enumerate(L): print(index+1, '-', name) myList = zip([100,20,30,40],L); for index, name in myList: print(index, '-', name)
迭代dict的value
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } print(d.values()) for v in d.values(): print(v)
PS:Python3.x中,dict的方法dict.keys(),dict.items(),dict.values()不会再返回列表,而是返回一个易读的“views”。这样一来,k = d.keys();k.sort()
不再有用,可以使用k = sorted(d)
来代替。
同时,dict.iterkeys(),dict.iteritems(),dict.itervalues()方法不再支持。
迭代dict的key和value
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key, value in d.items(): print(key, ':', value)
列表生成
一般表达式
L = [x*(x+1) for x in range(1,100)] print(L)
复杂表达式
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } def generate_tr(name, score): if score >=60: return '<tr> <td>%s</td> <td>%s</td> </tr>' % (name, score) else: return '<tr> <td>%s</td> <td>%s</td> </tr>' % (name, score) tds = [generate_tr(name,score) for name, score in d.items()] print('
Name | Score |
---|---|
条件表达式
L = [x * x for x in range(1, 11) if x % 2 == 0] print(L)
def toUppers(L): return [x.upper() for x in L if isinstance(x,str)] print(toUppers(['Hello', 'world', 101]))
多层表达式
L = [m + n for m in 'ABC' for n in '123'] print(L)
L = [a*100+b*10+c for a in range(1,10) for b in range(0,10) for c in range(1,10) if a==c] print(L)
后记
至此,Python基础结束。接下来,爬虫飞起!
更多Python,基础相关文章请关注PHP中文网!

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, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

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

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

드림위버 CS6
시각적 웹 개발 도구
