본문 바로가기
카테고리 없음

Python 파이썬 기초 문법 총 정리, 기초 문법만 빠르게 확인하기

by 엘파뉴e 2021. 7. 8.

Python 파이썬 기초 문법 총 정리, 기초 문법만 빠르게 확인하기

파이썬기초문법

 

파이썬 기초문법 빠르게 한번에 확인하고 싶어 한페이지에 모두 작성했습니다.

 

변수선언, 자료구조(리스트, 튜플, 딕셔너리), 조건문, 반복문, 내장함수, 함수, 클래스, 파일읽기,쓰기(json파일기준) 로 구성되어 있습니다.

 

이미 다른 프로그래밍 언어를 할줄 아는 상황에서 파이썬을 추가고 배우려고 할때, 책이나 인강 등을 보면 문법외 기초내용설명까지 많아서 시간이 오래걸려 문법만 확인하려 검색을 하면 자료가 많지만 다 항목별로 나뉘어져 있는편이고, 다 따로 검색해야 하는 상황이라, 전체문법 기초만 우선 빠르게 한번에 떼고 싶은 생각이 간절했던 사람입니다.

 

저의 상황은 자바스크립트, PHP, JAVA 를 이미 할줄 아는 상황에서  파이썬을 추가로 공부하려니, 일단 기초문법과 정규표현식만 빠르게 확인하고 싶었지만 한번에 모든 기초문법과 정규표현식이 있는 자료를 찾기 어려워 결국 제가 직접 나름 노가다(유료인강, 무료강의, 검색) 끝에 정리 하였습니다.

 

저처럼 기초문법 과 정규표현식만 빠르게 보고 싶은분들은 참고했다가 활용하세요!

 

!내용중 몇 안되는 프롬프트 명령어는 윈도우기준입니다. OS에 따라 명령어 규칙이 달라 안될경우 사용중인 OS 에 맞는 명령어규칙에 맞춰 작성해야 합니다.

 

! 파이썬 설치는 Anaconda(아나콘다) 추천

이유, 개발 시 자주쓰거나 유명한 연동 모듈 이 모두 내장

 

! 에디터는 비쥬얼스튜디오(VScode)

이유, 편함, 진짜 편함 평생 써봐왔던 에디터들 중 단연코 최고

 

 

파이썬 기초문법 (+ 정규표현식) 시작!

 

출력하기

print()
print('Hello World')

> Hello World

 

 

 

변수선언

x = 3
x = 3
y = '안녕'

print(x)
print(y)

3
안녕

 

 

 

연산

3+2
print(3+2)

> 5

 

!파이썬 IDLE 쉘 에서는 print() 필요 없음

ex)

3+2
>>>5

 

파이썬 버전 확인하기

python --version

! 명령 프롬프트(Prompt)에 입력 Enter

python --version

 

 

 

데이타 타입 확인

type()
a = 1
print(type(a))

<class 'int'>

 

! 데이타 형 정수 = int, 실수 = float, 문자 = str,  Boolean(True or False) = bool

 

 

 

입력 받기 (입력폼)

input()
name = input('name : ')
print(name)

name :  

 

 

 

리스트

= []
a_list = [] # 빈리스트
text_list = ['사과', '바나나', '메론'] #str 
int_list = [1, 2, 3, 5, 7, 9] #int or float

 

 

 

리스트에 데이터 추가하기

.append()
list = []

name = '홍길동'

list.append(name)

print(list)

['홍길동']

 

 

리스트 데이터 불러오기

names = [ 'tom', 'miki', 'jill', 'jane' ]

print(names[0]) # 리스트의 0번 인덱스에 해당하는 데이터를 출력
print(names[-1]) # 리스트의 가장 마지막 인덱스 데이터를 출력
print(names[0:2] # 리스트의 0번부터 2번 전까지 데이터를 출력​
print(names[1:] # 리스트 1번부터 끝까지

tom

jane

tom, miki

miki, jill, jane

 

 

 

엘리먼트 갯수 구하기 (배열 갯수)

len()
names = [ 'tom', 'miki', 'jill', 'jane' ]

print(len(names))

4

 

 

 

인덱스 찾기

.index()
names = [ 'tom', 'miki', 'jill', 'jane' ]

print(names.index('miki'))

1

 

 

 

배열의 정보변경

리스트 내 일부 값(데이터) 수정하기 (특정한 엘리먼트 값을 변경)

names = [ 'tom', 'miki', 'jill', 'jane' ]

names[1] = 'gigi'

print(names)

tom, gigi, jill, jane

 

 

 

리스트 배열의 불규칙값을 내림차순 정렬

sorted
x = [4,2,3,1]
y = sorted(x) # 불규칙 적인 값을 자동으로 내림 순차 정렬
print(y)

[1, 2, 3, 4]

 

 

 

리스트 이차원 배열 

names = [ 'tom', 'miki', 'jill', 'jane' ]

scores = [ 10, 50, 90, 60 ]

highscores  = [names, scores]

print(highscores)

[[ 'tom', 'miki', 'jill', 'jane' ], [ 10, 50, 90, 60 ]]

 

 

 

이차원 배열 리스트 에서 특정 데이터 (엘리먼트 값) 가져오기

names = [ 'tom', 'miki', 'jill', 'jane' ]

scores = [ 10, 50, 90, 60 ]

highscores  = [names, scores]

print(highscores)

print(highscores[0][0])

[[ 'tom', 'miki', 'jill', 'jane' ], [ 10, 50, 90, 60 ]]

'tom'

 

 

print(highscores[1][0])

10

 

 

 

딕셔너리

= {}

# 딕셔너리, 딕셔너리는 key와 values로 이루어짐, 키는 불변하는 값만 넣을 수 있다.

dic = {'사과': 1, '바나나': 2, '포도': 3}
print(dic)

{'사과': 1, '바나나': 2, '포도': 3}

 

 

 

빈 딕셔너리에 값 추가하기 1

dic = {}

dic['홍길동'] = '123-4657'
dic['김을자'] = '012-4567'
dic['이순영'] = '568-5670'

print(dic)

{'홍길동': '123-4657', '김을자': '012-4567', '이순영': '568-5670'}

 

 

 

빈 딕셔너리에 값 추가하기 2

dic = {}

dic['이름'] = '홍길동'
dic['전화번호'] = '123-4567'
dic['주소'] = '서울특별시 동작구 사당로 87'

print(dic)

 

{'이름': '홍길동', '전화번호': '123-4567', '주소': '서울특별시 동작구 사당로 87'}

 

 

 

딕셔너리에 값 추가하기 2

dic = {'사과': 1, '바나나': 2, '포도': 3}

dic['망고'] = 5

print(dic)

{'사과': 1, '바나나': 2, '포도': 3, '망고': 5}

 

 

 

딕셔너리 키값 체크, 벨류체크

dic = {'사과': 1, '바나나': 2, '포도': 3}

print(dic.keys()) #키값체크
print(dic.values()) #벨류체크

dict_keys(['사과', '바나나', '포도'])
dict_values([1, 2, 3])

 

 

 

튜플 tuple

리스트와 비슷한, 엘레먼트를 못바꾼다. 리스트는 가변, 튜플은 불변

r = tuple('1''2')
x = (1,2,3)
y = ('a','b','c')
z = (1,"hello","there")

print (r)
print( x + y )
print('a' in y )
print(z.index(1))

('1', '2')
(1, 2, 3, 'a', 'b', 'c')
True
0

 

 

 

조건문

조건문 주의: 들여쓰기 가 아주 엄격하다.
대소문자 구분이 엄격하다.

if
if 2 > 1:
  print("조건문 hello")

조건문 hello

 

 

if not 
if not 1 > 2:
  print("조건문 not hello2")

조건문 not hello2

 

 

elif
a = 0

if a > 1:
    print("a는 1보다 큽니다")

elif a < 1:
    print("a는 1보다 작습니다")

else:
    print("a는 1보다 크지도 작지도 않습니다.")

a는 1보다 작습니다

 

 

else
a = 1

if a > 1:
    print("a는 1보다 큽니다")

elif a < 1:
    print("a는 1보다 작습니다")

else:
    print("a는 1보다 크지도 작지도 않습니다.")

a는 1보다 크지도 작지도 않습니다.

 

 

 

조건문 연산자 

and
if 1 > 0 and 2 >1:
  print("조건문 and 연산자 hello")

조건문 and 연산자 hello

 

 

or 
if 1 > 0 or 0 >1:
  print("조건문 or 연산자 hello")

조건문 or 연산자 hello

 

 

순서대로 치환
print('포지셔닝포맷팅, 순서대로 치환 , aram hello {}say how are you {} fine not'.format('진아', 12))

포지셔닝포맷팅, 순서대로 치환 , aram hello 진아say how are you 12 fine not

 

 

위치기반 치환
print('to {name}. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim apple veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. {age:d} Duis aute irure dolor in {name} reprehenderit apple computer in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui {name} officia deserunt mollit anim id est laborum.'.format(name='egoing', age=12))

to egoing. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim apple veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 12 Duis aute irure dolor in egoing reprehenderit apple computer in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui egoing officia deserunt mollit anim id est laborum.

 

 

 

 

반복문

for 문 
for i in range(3):
  print("안녕 for")

안녕 for
안녕 for
안녕 for

 

 

name = ['서울', '대전', '대구', '부산', '경기도', '인천']
for i in name:
    print(i)

서울 
대전 
대구 
부산 
경기도 
인천

 

 

while
i = 0
while i < 5:
  print("안녕  while")
  i = i + 1

안녕  while
안녕  while
안녕  while
안녕  while
안녕  while

 

 

while 문 무한루프 와 break
i = 0
while True:
  print("안녕 무한루프 와 브레이크")
  i = i + 1

  if i > 2:
    break

안녕 무한루프 와 브레이크
안녕 무한루프 와 브레이크
안녕 무한루프 와 브레이크

 

 

for 문으로 구구단 하기
for i in range(2,10):
    for s in range(1,10):
        print("%2d x%2d = %5d" %(i, s, i*s))

 2 x 1 =     2
 2 x 2 =     4
 2 x 3 =     6
 2 x 4 =     8
 2 x 5 =    10

(이하생략)

 

 

while 문으로 구구단 하기
i = 2
while i < 10:
    j = 1
    while j < 10:
        print( "%2d x %2d = %5d" %(i, j, i*j))
        j += 1
    i += 1

 

 

continue 와 조건문, 반복문
# continue 와 조건문, 반복문
for i in range(3):
  print(i)
  print("안녕 컨티뉴1")
  print("안녕 컨티뉴2")

  if i == 1:
    continue

  print("안녕 컨티뉴3")

0
안녕 컨티뉴1
안녕 컨티뉴2
안녕 컨티뉴3
1
안녕 컨티뉴1
안녕 컨티뉴2
2
안녕 컨티뉴1
안녕 컨티뉴2
안녕 컨티뉴3

 

 

 

 

존재 여부만 확인하기 있으면 True 가 출력된다

# 존재 여부만 확인하기  있으면 True 가 출력된다
print("hello" in y)

 

 

 

과일개수 세는 프로그램-대기없기술면접질문

fruit = ["사과","사과","바나나","바나나","딸기","키위","복숭아","복숭아","복숭아"] # 배열을 만들어 변수 fruit 에 담음

d = {} # 빈 딕셔너리 만들어 , 변수 d 에 저장

for f in fruit: # 배열내 데이터 존재 여부 체크, 후 f 에 담는다.
 if f in d: # f에 사과라는 key 가 , d 딕셔너리에 있어?
   d[f] += 1 # 그렇다면, f(key 값 사과) 의 value 갯수를 하나 올려줘
 else:
   d[f] = 1 #만약 d 딕셔너리에 사과라는 key 가 없다면, 그걸 d 딕셔너리  에 넣고 밸류는 1로 만들어줘

print(d) # d 딕셔너리 내용을 출력해

{'사과': 2, '바나나': 2, '딸기': 1, '키위': 1, '복숭아': 3}

 

 

 

 

 

예외처리

연산 이나 파일 접근시 포맷이 맞지 않거나, 파일이 및 데이터가 없을수도 있을 경우 등 다양한 이유로 에러가 발생시 프로그램이 종료 되는데, 이때 종료 되지 않고 다른 예외처리로 에러 방지를 할 수 있는 예외처리문

 

try, except ,finally

try:
    print(100/0) # 예외로 인해 에러가 날 수도 있는 코드를 try 안에 작성, 에러가 나도 멈추지 않고 다음 코드를 실행한다.
except:
    print("100은 0으로 나눌 수 없습니다.") # 예외가 발생한 경우 처리
finally:
    print("다음 작업을 실행합니다") # 에러 발생 여부상관없이 무조건 실행되는 구문 필요시

100은 0으로 나눌 수 없습니다.
다음 작업을 실행합니다

 

 

 

파이썬 내장함수 

엘리먼트 숫자 확인

len()
a = ['사과', '바나나', '토마토', '포도', '멜론']

print(len(a))

5

 

 

가장 큰 값 확인

max()
a = [1000, 2000, 500, 800, 3500]

print(max(a))

3500

 

 

가장 작은값 확인

min()
a = [1000, 2000, 500, 800, 3500]

print(min(a))

500

 

 

합계값 확인

sum()
a = [1000, 2000, 500, 800, 3500]

print(sum(a))

7800

 

 

반복문에 인덱스 붙히기 

enumerate()
st = ['청량리', '성북', '의정부', '소요산']

for idx, station in enumerate(st): #숫자 붙히기(인덱스), 이누미레이트
    print(idx, station)

0 청량리
1 성북
2 의정부
3 소요산

 

 

람다 함수

lambda
su = lambda a, b : a+b #람다함수 
print(su(2,3))

5

 

 

 

함수(펑션 Function) 기본문법

 

함수의 기본문법

def
def chat():
  print("함수의 기본문법")
chat()

 

함수의 인자 전달 1 (구구단을 함수로 구현 한 예)

def multiply(num):
    for i in range(1,10):
        print(num, 'x', i, '=', num*i)

multiply(2) # 2단 실행
multiply(5) # 5단 실행

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45

 

 

함수의 인자 전달 2

# 함수의 인자 전달
def chat_demo(name1, name2):
  print("%s : 안녕 영희야 뭐해?" %name1)
  print("%s : 그냥있어" %name2)
chat_demo("철수","영희")

철수 : 안녕 영희야 뭐해?
영희 : 그냥있어

 

 

함수의 리턴

return
# 함수의 return
def dsum(a, b):
 result = a + b
 return result

d = dsum(2, 4)
print(d)

6

 

 

클래스

Class
class Person: # Person 이란 이름으로 클래스 선언
  name = "홍길동" # 변수 name 에 정보 저장

  def say_hello(self): # say_hello 란 이름의 함수(펑션) 선언
    print("안녕! 나는 " + self.name ) # 안녕! 나는 "아람(변수 name 에 담긴 내용을 인자로 받은 값)" 을 출력

p = Person() # person 을 p 라는 변수에 담는다.
p.say_hello() # 클래스 person 의 펑션 sayhello 를 실행해라

안녕! 나는 홍길동

 

 

 

클래스 사용 문법

class Car:
    color = ""
    speed = 0

    def __init__(self, color, speed): # 생성자
        self.color = color
        self.speed = speed

    def upSpeed(self, value):
        self.speed += value

    def downSpeed(self, value):
        self.speed -= value

    def getColor(self):
        return self.color

    def getSpeed(self):
        return self.speed

myCar1 = Car("Red", 30)
myCar1.upSpeed(30)
myCar2 = Car("Blue", 60)

print("%s %d" %(myCar1.color, myCar1.speed))
print("%s %d" %(myCar2.getColor(), myCar2.getSpeed()))

Red 60
Blue 60

 

 

 

인스턴스 변수와 클래스 변수

self.

class Car:
    color = ""
    speed = 0
    count = 0

    def __init__(self):
        self.speed = 0    # 인스턴스 변수
        Car.count += 1    # 클래스 변수

 

 

 

클래스 인자로 의 전달 문법

class Person2:
  def __init__(self, user, age):
    self.user = user
    self.age = age

  def say_hello2(self, to_name):
    print("안녕! " + to_name + " 나는 " + self.user +  "이야")

  def introduc(self, to_name):
    print("안녕! " + to_name + " 나는 " + self.user + " 그리고" + str(self.age) + " 살이야") # !주의: age 숫자타입을 문자로 캐스팅 하지 않으면 에러가 뜬다.

yonga = Person2("영아", 20)
sua = Person2("수아", 20)
youjin = Person2("유진", 35)

yonga.say_hello2("영희")
sua.say_hello2("보람")
youjin.introduc("진수")

안녕! 영희 나는 영아이야
안녕! 보람 나는 수아이야
안녕! 진수 나는 유진 그리고35 살이야

 

 

 

클래스의 상속(inheritance)

class Person2:
  def __init__(self, user, age):
    self.user = user
    self.age = age

  def say_hello2(self, to_name):
    print("안녕! " + to_name + " 나는 " + self.user +  "이야")

  def introduc(self, to_name):
    print("안녕! " + to_name + " 나는 " + self.user + " 그리고" + str(self.age) + " 살이야") # !주의: age 숫자타입을 문자로 캐스팅 하지 않으면 에러가 뜬다.

yonga = Person2("영아", 20)
sua = Person2("수아", 20)
youjin = Person2("유진", 35)

yonga.say_hello2("영희")
sua.say_hello2("보람")
youjin.introduc("진수")

# 클래스의 상속(inheritance)

class Police(Person2): # Person2 상속적용
  def arrest(self, to_arrest):
    print("넌 체포됐다, " + to_arrest )

class Programmer(Person2): # Person2 상속적용
  def Program(self, to_Program):
    print("다음엔 뭘만들지? 아 이걸 만들어야겠다! " + to_Program )


jina = Person2("지나", 17)
sora = Police("소라", 21)
miss = Programmer ("미스", 35)

jina.introduc("수잔") # Person2 상속 하기 때문에 introduc 를 사용 가능하다.
sora.arrest("김종국")
miss.introduc("쥬쥬")
miss.Program("이메일 클라이언트")

안녕! 영희 나는 영아이야
안녕! 보람 나는 수아이야
안녕! 진수 나는 유진 그리고35 살이야
안녕! 수잔 나는 지나 그리고17 살이야
넌 체포됐다, 김종국
안녕! 쥬쥬 나는 미스 그리고35 살이야
다음엔 뭘만들지? 아 이걸 만들어야겠다! 이메일 클라이언트

 

 

 

 

 

 

json 파일 데이터 읽기

 

test.json 파일내용

{
	"K5": {
		"price": "7000",
		"year": "2015"
	},
	"Avante": {
		"price": "3000",
		"year": "2014"
	}
}

최 상단에 import json 해줘야 함

import json


with open('test.json', 'r') as f:

    json_data = json.load(f) #load 딕셔너리 로 로드

print(json.dumps(json_data)) #.dumps 문자열로 바뀜

{"K5": {"price": "7000", "year": "2015"}, "Avante": {"price": "3000", "year": "2014"}}

 

 

 

json 파일 읽기, 내용수정, 파일저장 

import json


with open('test.json', 'r') as f:

    json_data = json.load(f) #load 불러오기

print(json.dumps(json_data)) #.dumps 문자열로 변환해서 출력




json_data['K5']['price'] = "7000" 

print(json_data['K5']['price'])


json_data['K8'] = {} #dict()
json_data['K8']['price'] = "9000"
json_data['K8']['year'] = "2019"

print(json_data)




with open('test.json', 'w', encoding='utf-8') as make_file:

    json.dump(json_data, make_file, indent="\t") #.dump 저장하기 


with open('test.json', 'r') as f:

    json_data = json.load(f)

print(json.dumps(json_data, indent="\t") )

f.close()

 

{"K5": {"price": "7000", "year": "2015"}, "Avante": {"price": "3000", "year": "2014"}}
7000
{'K5': {'price': '7000', 'year': '2015'}, 'Avante': {'price': '3000', 'year': '2014'}, 'K8': {'price': '9000', 'year': '2019'}}
{
        "K5": {
                "price": "7000",
                "year": "2015"
        },
        "Avante": {
                "price": "3000",
                "year": "2014"
        },
        "K8": {
                "price": "9000",
                "year": "2019"
        }
}

 

 

 

프로그램 상에서 딕셔너리 만들고, json 파일로 저장하기

import json



car_group = dict()



k5 = dict()
k5["price"] = "5000"

k5["year"] = "2015"

car_group["K5"] = k5



avante = dict()

avante["price"] = "3000"

avante["year"] = "2014"

car_group["Avante"] = avante



#json 파일로 저장

with open('C:\\test.json', 'w', encoding='utf-8') as make_file:

    json.dump(car_group, make_file, indent="\t")



	

# 저장한 파일 출력하기

with open('C:\\test.json', 'r') as f:

    json_data = json.load(f)

print(json.dumps(json_data, indent="\t") )

 

 

json 파일저장 다른 방법

import json


with open('test.json', 'r') as f:

    json_data = json.load(f) #load 불러오기


json_data['K5']['price'] = "7000" 

print(json_data['K5']['price'])


json_data['K8'] =  dict()
json_data['K8']['price'] = "9000"
json_data['K8']['year'] = "2019"

print(json_data)




with open('test.json', 'w', encoding='utf-8') as f:

    makefile = json.dumps(json_data, indent="\t", ensure_ascii=False) # ensure_ascii 로 유니코드 에러 방지 
    f.write(makefile) #저장하기

f.close()



with open('test.json', 'r') as f:

    json_data = json.load(f)

print(json.dumps(json_data, indent="\t") )

f.close()

 

{"K5": {"price": "7000", "year": "2015"}, "Avante": {"price": "3000", "year": "2014"}}
7000
{'K5': {'price': '7000', 'year': '2015'}, 'Avante': {'price': '3000', 'year': '2014'}, 'K8': {'price': '9000', 'year': '2019'}}
{
        "K5": {
                "price": "7000",
                "year": "2015"
        },
        "Avante": {
                "price": "3000",
                "year": "2014"
        },
        "K8": {
                "price": "9000",
                "year": "2019"
        }
}

 

 

 

 

 

 

2021.07.10 - [분류 전체보기] - Python 데이터로 파이썬 차트 개발 하기(Column, Bar, Hue)

댓글