티스토리 뷰
만약 이 글을 보신다면 여기선 Java에서의 다른 문법만 취급하기 때문에 문법 내용이 부족할 수 있습니다. https://www.youtube.com/watch?v=kWiCuklohdY(6hour python basic youtube)
type() 함수를 사용하면 자료형을 쉽게 확인할 수 있습니다.
>>> type(6) # 정수
<type 'int'>
>>> type('A') # 문자열
<type 'str'>
파이썬의 자료형은 크게 숫자(numbers), 시퀀스(sequence), 매핑(mapping) 등으로 나눌 수 있습니다.
숫자
숫자를 나타내는 자료형으로는 정수(int), 부동소수점수(float), 복소수(complex)가 있습니다.
>>> type(100000000) # 정수
<class 'int'>
>>> type(2.8) # 부동소수점수
<type 'float'>
>>> type(3+4j) # 복소수
<type 'complex'>
시퀀스
문자열(str), 리스트(list), 튜플(tuple), 사용자 정의 클래스가 시퀀스에 속합니다.
>>> type("Love your Enemies, for they tell you your Faults.")
<class 'str'>
>>> type(['love', 'enemy', 'fault'])
<class 'list'>
>>> type(('love', 'enemy', 'fault'))
<class 'tuple'>
매핑
딕셔너리(dict)는 키(key)와 값(value)의 짝으로 이뤄집니다. 이런 것을 매핑이라고 합니다.
>>> type({'one': 1, 'two': 2, 'three': 3})
<class 'dict'>
불
>>> type(False)
<class 'bool'>
>>> type(3 >= 1)
<class 'bool'>
>>> type(True == 'True')
<class 'bool'>
세트
집합을 표현하는 세트(set)도 있습니다.
>>> fruits = {'apple', 'banana', 'orange'}
세트는 원소의 순서가 유지되지 않고 중복 원소를 갖지 않는 ‘집합’으로서의 특징이 있으며, 집합 연산을 사용할 수 있습니다.
----------------------------------------------------------------------------------------------------------------------------------
독특한 문자열 프린트
print("ㅋ" * 9) >>> ㅋㅋㅋㅋㅋㅋㅋㅋㅋ
print(not True) >>> False
sentence = """
나는 소년이고,
파이썬은 쉬워요
"""
print(sentence)
>>>
나는 소년이고,
파이썬은 쉬워요
주석
# 주석 한줄
...
주석
여러줄
...
연산자
print(2**3) >>> 8
print(15//2) >>> 7 (몫)
print(10 > 3) >>> True
그 외에
and = &, or = | 연산자를 쓸 수 있다.
기존에는 비트연산자만 저 위 처럼 썼지만 파이썬의 경우 java의 &&와 || 처럼 쓰인다.
숫자처리함수
print(abs(-5)) >>> -5 의 절대값 = 5
print(pow(4, 2)) >>> 4의 2제곱 = 4 * 4 = 16
print(max(5, 12)) >>> 5 와 12 중 큰 값 = 12
print(min(5, 12)) >>> 5 와 12 중 작은 값 = 5
print(round(3.14)) >>> 3.14 의 반올림 = 3
print(round(4.99)) >>> 4.99 의 반올림 = 5
from math import * # math 모듈 내의 모든 내용을 가져다 쓰겠다는 의미
print(floor(4.99)) >>> 4.99 의 내림 = 4
print(ceil(3.14)) >>> 3.14 의 올림 = 4
print(sqrt(16)) >>> 16 의 제곱근 = 4
랜덤함수
from random import *
print(random()) # 0.0 ~ 1.0 미만의 임의의 값 생성
print(int(random() * 10) + 1) # 1 ~ 10이하의 임의의 값 정수 생성
print(randrange(1, 46)) # 1 ~ 46미만의 임의의 값 정수 생성
print(randint(1, 45)) # 1 ~ 45이하의 임의의 값 정수 생성
슬라이싱
jumin = "980325-1234567"
print("성별 : " + jumin[7]) # 1
print("연 : " + jumin[0:2]) # 98
print("월 : " + jumin[2:4]) # 03
print("일 : " + jumin[4:6]) # 25
print("생년월일 : " + jumin[:6]) # 980325
print("뒤 7자리 : " + jumin[7:]) # 1234567
print("뒤 7자리 : " + jumin[-7:]) # 1234567
문자열 처리함수
python = "Python is Amazing"
print(python.lower()) # 전체문장 소문자
print(python.upper()) # 전체문장 대문자
print(python[0].isupper()) # 첫 문자가 대문자인지 ? True
print(python.replace("Python", "Java")) # Java is Amazing
index = python.index("n")
print(index) # 5
index = python.index("n", index + 1)
print(index) # 15
print(python.find("java")) # 없으면 -1
#print(python.index("java")) # 없으면 에러
print(python.count("n")) # n 문자 카운팅 => 2
문자열 포맷
# 방법1
print("내 나이는 %d살입니다." % 20)
print("내 나이는 %s살입니다." % 20)
print("내가 좋아하는 색은 %s색과 %s색입니다." %("빨강", "파랑"))
# 방법2
print("내 나이는 {}살입니다.".format(20))
print("내가 좋아하는 색은 {}색과 {}색입니다.".format("빨강", "노랑"))
print("내가 좋아하는 색은 {1}색과 {0}색입니다.".format("빨강", "노랑"))
print("나는 {age}살이며, 좋아하는 색은 {color}색입니다.".format(age=27, color="노랑"))
# 방법3 (v3.6이상)
age = 20
color = "파랑"
print(f"나는 {age}살이며, 좋아하는 색은 {color}색입니다.")
-----------------------------------------------------------------------------------------------------------------------------------
리스트
subway = ["유재석", "조세호", "박명수"]
print(subway.index("조세호")) #1
subway.append("하하")
print(subway) #["유재석", "조세호", "박명수", "하하"]
subway.insert(1, "정형돈")
print(subway) #["유재석", "정형돈", "조세호", "박명수", "하하"]
print(subway.pop()) #하하
print(subway) #["유재석", "정형돈", "조세호", "박명수"]
subway.append("유재석") # 유재석 2명
print(subway.count("유재석")) #2
# 정렬
numbers = [1, 9, 6, 5, 8]
numbers.sort()
print(numbers)
# 순서 뒤집기
numbers.reverse()
print(numbers)
# 모두 지우기
numbers.clear()
# 다양한 자료형 함께 사용
numbers = [5,2,4,3,1]
mix_list = ["조세호", 20, True]
# 리스트 확장
numbers.extend(mix_list)
print(numbers)
사전
# 사전은 키와 값으로 이루어진 자료구조
# 값 가져오기
cabinet = {3: "유재석", 100: "김태호"}
print(cabinet[3]) # 유재석
print(cabinet.get(3)) # 똑같이 유재석
# print(cabinet[5]) # error
print(cabinet.get(5)) # none
print(cabinet.get(5, "사용가능")) # 사용가능
# 존재여부확인
print(3 in cabinet) # True
print(5 in cabinet) # False
# 업데이트, 추가
cabinet[5] = "조세호"
cabinet[3] = "김종국"
print(cabinet) # {3: '김종국', 100: '김태호', 5: '조세호'}
# 삭제
del cabinet[5]
print(cabinet) # {3: '김종국', 100: '김태호'}
# key만 출력
print(cabinet.keys()) # dict_keys([3, 100])
# value만 출력
print(cabinet.values()) # dict_values(['김종국', '김태호'])
# key, value 둘다 출력
print(cabinet.items())
# 클리어
cabinet.clear()
튜플
# 튜플은 리스트와 다르게 내용 변경이나 추가를 할 수 없다.
# 대신 속도가 리스트보다 빠르다.
menu = ("돈까스", "치즈까스")
print(menu[0]) # 돈까스
# 한번에 튜플!
name, age, hobby = ("김종국", 20, "코딩")
print((name, age, hobby)) # ('김종국', 20, '코딩')
세트
# 집합(set)
# 중복 안되고 순서가 없다.
my_set = {1, 2, 3, 3, 3}
print(my_set) # {1, 2, 3}
java = {"유재석", "김종국", "조세호"}
python = set(["유재석", "박명수"])
# 교집합
print(java & python) # {'유재석'}
print(java.intersection(python))
# 합집합
print(java | python) # {'유재석', '박명수', '조세호', '김종국'}
print(java.union(python))
# 차집합
print(java - python) # {'김종국', '조세호'}
print(java.difference(python))
# 추가
python.add("김태호")
print(python) # {'박명수', '김태호', '유재석'}
# 삭제
java.remove("조세호")
print(java) # {'유재석', '김종국'}
자료구조의 변경
# 자료구조의 변경
menu = {"커피", "우유", "주스"}
print(type(menu)) # <class 'set'>
menu = list(menu)
print(type(menu)) # <class 'list'>
menu = tuple(menu)
print(type(menu)) # <class 'tuple'>
-----------------------------------------------------------------------------------------------------------------------------------
조건문
# java처럼 if else if else가 아닌, if elif else이다.
# 조건문 or and도 추가 가능하며 input("...")을 통해 값을 가져올 수 있다.
value = "화창"
value = input("오늘 날씨는 어때요? ")
if value == "비":
print("비옴")
elif value == "눈":
print("눈옴")
else:
print("화창")
반복문
for waiting_num in range(0, 5):
print(waiting_num)
for customer in ["아이언맨", "토르", "아이엠그루트"]:
print(customer)
# while문의 경우 자바와 비슷함.
# continue, break도 마찬가지.!
# 조건문에 리스트를 달아서 체크도 가능하다.
absent = [2, 5]
no_book = 7
for student in range(1, 12):
if student in absent:
continue
elif student in no_book:
break
else:
print("~")
# 한 줄 반복문
students = [1,2,3,4,5]
students = [i + 100 for i in students]
print(students) # [101, 102, 103, 104, 105]
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students]
print(students) #[8, 4, 10]
함수
# def 함수이름(매개변수)
# 반환시 return
def deposit(balance, money=0): # 기본값 설정도 가능하다.
print("입금이 완료되었습니다.")
return balance + money
# 가변 인자
def profile(name, age, *language):
for lang in language:
print(lang, end=" ")
# 전역 변수 사용 (권장되진 않음)
변수이름 = 값
def method():
global 변수이름
-----------------------------------------------------------------------------------------------------------------------------------
다양한 출력 포맷
print("Python", "Java", "JavaScript", \
sep=" vs ", end="?") # Python vs Java vs JavaScript?Python
print("Python", file=sys.stdout) # 표준 출력
print("Python", file=sys.stderr) # 에러 출력
scores = {"수학":0, "영어":50, "코딩":100}
for subject, score in scores.items():
print(subject.ljust(8), str(score).rjust(4), sep=",")
# ljust는 왼쪽 정렬 이후 n칸 여유를 가지게 하며, rjust는 오른쪽 정렬 이후 n칸 여유 가지게 한다.
for num in range(1, 21):
print(str(num).zfill(3)) # 001 ~ 020
print("{0: >10}".format(500)) # 왼쪽 정렬 10칸 후 찍힘
print("{0: >+10}".format(500)) # 왼쪽 정렬 10칸 후 +500
print("{0: >+10}".format(-500)) # 왼쪽 정렬 10칸 후 -500
print("{0:_<+10}".format(500)) # +500______ (오른쪽 정렬 후 + 500)
print("{0:,}".format(10000000)) # 세자리 마다 ,
print("{0:+,}".format(10000000)) # +10,000,000
print("{0:+,}".format(-10000000)) # -10,000,000
print("{0:^<+30,}".format(1000000000)) # +1,000,000,000^^^^^^^^^^^^^^^^
print("{0:.2f}".format(5/3)) # 1.67
파일 입출력
# 파일 입출력 w (쓰기) a (이어서) r(읽기)
score_file = open("score.txt", "w", encoding="utf-8")
print("수학".ljust(6), "0".rjust(3), sep=" : ", file=score_file)
print("영어".ljust(6), "50".rjust(3), sep=" : ", file=score_file)
score_file.close()
score.txt)
수학 : 0
영어 : 50
--
score_file = open("score.txt", "a", encoding="utf-8")
score_file.write("과학 : 70\n")
score_file.write("코딩 : 100")
score.txt)
수학 : 0
영어 : 50
과학 : 70
코딩 : 100
--
score_file = open("score.txt", "r", encoding="utf-8")
print(score_file.read()) # 전부 출력
score_file.close()
score_file = open("score.txt", "r", encoding="utf-8")
print(score_file.readline()) # 한 줄씩 출력! 반복문과 break를 통해 많이 쓰임
score_file.close()
Pickle
# 프로그램 데이터를 파일 형태로 전달하거나 사용. 특히 바이너리 형태이기에 용량이 작다는 것이 장점.
# 개인적으로 자바보다 편한듯?
import pickle
profile_file = open("profile.pickle", "wb")
profile = {"이름":"박명수", "나이":30, "취미": ["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file)
profile_file.close()
profile_file = open("profile.pickle", "rb")
profile = pickle.load(profile_file) # file에 있는 정보를 profile에 불러오기
print(profile)
profile_file.close()
# with를 통해 매번 파일 close를 해주지 않도록 설정 가능하다.
import pickle
with open("profile.pickle", "rb") as profile_file:
print(pickle.load(profile_file))
-----------------------------------------------------------------------------------------------------------------------------------
클래스
class Unit:
def __init__(self, name, hp, damage): # 생성자 함수
self.name = name
self.hp = hp
self.damage = damage
def getLocation(self, loc): # class안에 함수는 메서드이며 [self]를 붙여줘야함.
print(loc)
if __name__ == '__main__':
marine = Unit("마린", 50, 5)
print(marine.damage)
marine.upgrade = True
if marine.upgrade == True: # 외부에서 멤버변수 생성도 가능
print("업그레이드 !")
상속
class Unit:
def __init__(self, name, hp): # 생성자 함수
self.name = name
self.hp = hp
def getLocation(self, loc): # class안에 함수는 메서드이며 [self]를 붙여줘야함.
print(loc)
class AtkUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(name, hp)
self.damage = damage
def attack(self):
print(self.damage)
# 다중상속 #
class Unit:
def __init__(self, name, hp): # 생성자 함수
self.name = name
self.hp = hp
class AtkUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(name, hp)
self.damage = damage
class Flyable:
def __init__(self, speed):
self.speed = speed
class FlyAndAttackUnit(AtkUnit, Flyable):
def __init__(self, name, hp, damage, speed):
AtkUnit.__init__(name, hp, damage)
Flyable.__init__(speed)
키워드
super, pass
-----------------------------------------------------------------------------------------------------------------------------------
예외처리
try:
val1 = 5
val2 = 2
# raise Exception 해당 에러를 발생. 그러면 밑에 줄 코드는 실행 x
print(f"{val1} / {val2} = {val1 / val2}")
except Exception:
print("error")
finally:
print("fin")
# 사용자 정의 에러 처리.
class UserDefinedErr(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
=>
...
except UserDefinedErr as err:
print(err)
모듈
(import module_name as 약어)를 통해 모듈을 해당 작업하는 파일로 가져와 module_name.methodName( )이거나 별칭을 써서 쓸 수 있다.
또는
from module_name import*를 통해 해당 모듈에 함수 이름을 즉시 사용 가능하다.
패키지
import 패키지이름.패키지이름 ( 클래스나 메서드는 안됨)
__init__.py)
__all__ = ["module names"]
...
파이썬은 import *을 사용할 때
__init__.py를 통해 사용할 모듈 이름을 정해주지 않으면 해당 모듈을 찾을 수 없어 에러를 띄운다.
...
# 내외부 모듈 실행
if __name__ == '__main__':
print("직접실행")
else:
print("외부에서 모듈 실행")
패키지, 모듈 위치
import inspect
import random
if __name__ == '__main__':
print(inspect.getfile(random))
# C:\Users\0992m\AppData\Local\Programs\Python\Python39\lib\random.py
패키지 설치
pip : 패키지 관련 명령어
pip list : 설치되어있는 패키지 리스트들.
pip show packageName : 해당 이름의 패키지 정보
pip install --upgrade packageName : 업그레이드
pip uninstall packageName : 패키지 삭제
내장함수, 외장함수
엄청 많으니 문서를 찾아서 잘 사용해보기!
기초끝~! ^^
- Total
- Today
- Yesterday
- https://subicura.com/2017/01/19/docker-guide-for-beginners-1.html
- ㄴ
- https://react.vlpt.us/basic/11-render-array.html
- Co
- https://react.vlpt.us/
- https://velog.io/@juno7803/React%EA%B0%80-%ED%83%9C%EC%96%B4%EB%82%9C-%EB%B0%B0%EA%B2%BD
- https://wikidocs.net/68
- https://jwprogramming.tistory.com/52
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |