Last active
January 31, 2023 08:15
-
-
Save Gomi-coder/2b48bd4f58e44f45ebe3571d8d0dd4e1 to your computer and use it in GitHub Desktop.
내가 보려고 작성한 Python 기본 문법의 모든 것(자료형 제외)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 기본 출력 | |
print("Hello World!") | |
# 변수 타입 확인 | |
A = "test" | |
print(type(A)) | |
A1 = 1 | |
A2 = 2 | |
A3 = A1/A2 | |
print(type(A3)) #<class 'float'> | |
# 기본 입력 | |
B = input() | |
print(type(B)) | |
# 정수 입력 받기 | |
C = int(input()) | |
D = input() | |
D = int(D) | |
# 연속된 정수 입력 받기 | |
v1, v2 = input().split() | |
v1 = int(v1) | |
v2 = int(v2) | |
v3, v4 = map(int, input().split()) | |
# 배열 입력 받기? | |
N = int(input()) | |
N_list = list(map(int, input().split())) | |
wordList = input().split() | |
print(type(word)) | |
# 배열의 출력? | |
testArr = ['a', 'b', 'c'] | |
print(testArr) #['a', 'b', 'c'] | |
# 2개 이상의 문자열 연결해서 출력 | |
print("s1", "s2") | |
print("s1", "s2", sep='') | |
print("s1", "s2", sep="_") | |
# 포매팅 : 문자열에서 특정 부분만 바꾸고 나머지 부분이 일정하다고 할 때 사용 | |
#다음과 같이 반복? | |
print(2022년 1월) | |
print(2022년 2월) | |
print(2022년 3월) | |
# f-string : f'문자열 {변수} 문자열' | |
# python 3.6부터만 가능! | |
month = 1 | |
while month<=12: | |
print(f'2022년 {month}월') | |
month += month+1 | |
like = 'cake' | |
often = 2 | |
oftenLike = f'나는 {like}를 좋아해. {often}주에 한 번은 먹어.' | |
print(oftenLike) | |
# % 포매팅 | |
# str.format | |
#특수문자 출력 | |
print("\\") | |
print(r" \ ") | |
# 중괄호 출력 | |
#기본 | |
print('\{hi\}') | |
tmpStr1 = 'hi' | |
#변수를 섞어서 출력 | |
print({tmpStr1}) # {'hi'} | |
tmpStr2 = 200 | |
print({tmpStr2}) # {200} | |
tmpStr3 = 300 | |
print({tmpStr2}, {tmpStr3}) #{200} {300} | |
# f-string에서 기본 중괄호는 {{ 연속 두 번 사용하면 하나만 출력. | |
printT1 = f'{{중괄호 출력}}' | |
print(printT1) #{중괄호 출력} | |
# f-string에서 변수와 중괄호 같이 출력 : f-string을 위한 중괄호까지 총 3개 사용 필요 | |
myAge = 25 | |
printT2 = f'{{{myAge}}}' | |
print(printT2) #{25} | |
# f-string을 이용해 dic 출력 | |
dicTest = {'name':'jully', 'gender':'women', 'age':'15'} | |
dicPrint = f'her name is {dicTest["name"]}, gender is {dicTest["gender"]}, age is {dicTest["age"]}' | |
print(dicPrint) | |
#별표(Asterisk, *) | |
cu = ('I', 'AM', 'GIRL') | |
print(cu) #('I', 'AM', 'GIRL') | |
#컨테이너 타입의 데이터 unpack 용도로 사용 가능 | |
print(*cu) #I AM GIRL (SET, LIST 전부 동일하게 동작) | |
################################################################################################## | |
# 응용1 - 전화번호 입/출력 | |
Number = input() | |
firstNumber = Number.split("-")[0] | |
secondNumber = Number.split("-")[1] | |
thirdNumber = Number.split("-")[2] | |
n1 = input().split("-")[0] | |
n2 = input().split("-")[1] | |
n3 = input().split("-")[2] | |
print(firstNumber) | |
print(secondNumber) | |
print(thirdNumber) | |
print(n1, n2, n3, sep="-") | |
# 응용2 - f-string을 이용한 정렬(왼쪽/오른쪽/중앙) | |
# {변수:정렬옵션기호 자리수} | |
sPosition1 = 'left' | |
sPosition2 = 'mid' | |
sPosition3 = 'right' | |
sLeft = f'{sPosition1:<10}' #왼쪽 정렬< | |
sMid = f'{sPosition2:^10}' #가운데 정렬^ | |
sRight = f'{sPosition3:>10}' #우측 정렬> | |
print(sLeft) | |
print(sMid) | |
print(sRight) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 두 정수의 값 비교하기 | |
A,B = map(int,input().split()) | |
# 기본 조건문 | |
if A > B: | |
print('>') | |
elif A < B: | |
print('<') | |
else: | |
print('==') | |
# in-line으로 각각 비교 | |
if(A > B) : print('>') | |
if(A < B) : print('<') | |
if(A==B): print('==') | |
# 삼항 연산자 사용 | |
# (내용1) if (조건1) else (내용2) .. if(조건2) else (내용3)... | |
print('>') if(A>B) else print('<') if (A<B) else print("==") | |
################################################################################################## | |
#응용1 - switch문 만들어보기 (*파이썬은 switch 없음 => dictionary 이용) | |
def switch(key): | |
telecom = {"011" : "SKT", "016": "KT", "019" : "LGU"}.get(key, "알 수 없는") | |
print(f'당신은 {telecom} 사용자입니다.') | |
firstNumber = input().split("-")[0] | |
switch(firstNumber) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# for문 | |
A = ['a1', 'a2', 'a3'] | |
for idx in A: | |
print(idx) | |
for i in range(1, 10): | |
print(f'2 * {i} = {2*i}') | |
# while문 | |
whileArr = ['sky', 'sea', 'sun'] | |
while whileArr: | |
print(whileArr.pop(-1)) #sun부터 거꾸로, 한 줄씩 출력 | |
#break, continue 사용 가능 | |
# Iterables : 반복 가능한 객체 | |
# string, list, tuple, dict, set, frozonset | |
testArr = ['a', 'b', 'c'] | |
print(testArr) | |
# iter() 함수를 통해 iterator로 변환됨. | |
itr = iter(testArr) | |
print(itr) #<list_iterator object at 0x000002118DF6AF80> | |
# 커스텀 클래스의 경우 클래스에 __iter__ 메서드를 정의하고 iterator 클래스를 반환해주면 해당 클래스가 iterable하게 할 수 있다. | |
check1 = itr.__next__() | |
print(check1) #a | |
#Iterators | |
# Iterable한 객체로부터 연속적인 값을 산출해내는 객체 | |
# Iterator 객체의 next 메서드를 통해 다음 값을 가져올 수 있다. | |
check2 = next(itr) | |
print(check2) #b | |
check3 = next(itr) | |
print(check3) #c | |
testArr2 = ['a2', 'b2', 'c2'] | |
itr2 = iter(testArr2) | |
print(itr2) #<list_iterator object at 0x000002118356AF80> | |
print(next(itr2)) #a2 | |
print(next(itr2)) #b2 | |
print(next(itr2)) #b3 | |
# Iterable 객체의 마지막 요소를 뱉은 후에는 StopIteration 예외가 발생한다. | |
check4 = next(itr) | |
print(check4) | |
''' | |
Traceback (most recent call last): | |
File "c:\Users\TK\Desktop\workplace\tkStudy\python\Untitled-1.py", line 16, in <module> | |
check4 = next(itr) | |
StopIteration | |
''' | |
############################################################# | |
# 응용1 - 백준 10951 빈 값 입력(EOF) 전까지 두 정수 입력 받아 합을 출력하기 | |
while True: | |
try: | |
testCase1, testCase2 = map(int, input().split()) | |
print(testCase1 + testCase2) | |
except: | |
break |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python Function | |
# 해당 함수의 기능을 추상화, 재사용(기능 모듈화) | |
# 함수 생성 -> own namespace 생성 | |
''' | |
def <함수명>([<parameter(s)>]): | |
body... | |
''' | |
def func(a,b,c): | |
return print(f'{a}, {b}, {c}') | |
func(1,3,5) # 1, 3, 5 | |
# python에서 함수의 인자 전달 방식? call by value, call by reference 둘 다 아닌 passed by assignment! | |
# 할당에 의한 전달(passed by assignment) : 파이썬에서 모든 값은 객체이고 모든 변수는 해당 객체를 가리키고 있기 때문. | |
# ex | |
# 3이라는 불변 객체 checkId? checkId = 3 | |
# checkId += 1 ? checkId라는 변수가 4로 변화한 게 아닌, 4라는 다른 새로운 객체를 가리킴 | |
print(id(3)) #2019624943920 | |
print(id(4)) #2019624943952 | |
checkId = 3 | |
print(id(checkId)) #2019624943920 | |
checkId += 1 | |
print(checkId) | |
print(id(checkId)) #2019624943952 | |
########################################################### | |
# 1. 위치 인자 (Positional Arguments) | |
# # 에러나는 코드 | |
# # def func_with_default(a, b="default1", c="default2", d): | |
# # print(f'{a}, {b}, {c}, {d}') | |
# # why?? default 값을 가진 인자 여러개가 default값을 가지지 않은 위치 인자 중간에 끼어있음(b, c, d) | |
# # 함수에 전달되는 인자들이 default값을 재설정하기 위한 것인지 본래 위치 인자에 넣고자 하는 것인지 알 수 없음. | |
# 제대로 사용하려면? default값이 설정된 인자들은 무조건 제일 뒤로 밀어넣기 | |
def func2(a, b, c="default"): | |
print(a, b, c) | |
func2(100, 200) | |
func2(100, 200, 300) | |
def func3(a, b, c="default", d="default2"): | |
print(a, b, c, d) | |
func3(100, 200) | |
func3(100, 200, 300) | |
# 응용1 - 가변 디폴트 변수를 함수의 위치 인자로 사용하기 | |
def my_strange_func(x=[]): | |
x.append("Hello Python") | |
print(x) # ['Hello Python'] -> ['Hello Python', 'Hello Python'] -> ['Hello Python', 'Hello Python', 'Hello Python'] 계속 증가 | |
# 문제점 : 원하는 출력값이 나오지 않을 수 있음. | |
# 함수 인자의 default값은 함수가 정의되었을 때 한 먼만 선언됨 (매번 함수가 실행될 때마다 선언되는 게 아님) | |
# 함수 인자에 default값으로 가변 객체(ex_empty list)를 주고 해당 값에 대한 작업을 수행하면 파라미터가 초기화되지 않고 변화가 누적됨. | |
# 해결 : default 값을 None으로 주고 default값이 변하지 않았을 시 함수 내부에서 default값 초기화 | |
def not_strange_anymore(x=None): | |
if x is None: | |
x = [] | |
x.append("Executed!") | |
print(x) | |
########################################################### | |
# 2. 가변 길이 인자 (Variable length arguments) | |
# *사용 (*의 역할은 basic1_inputOuput.py의 #별표 항목 참고) | |
# 구현하고자 하는 함수의 인자 수가 미리 주어지지 않을 때 사용 가능 | |
cu = ('I', 'AM', 'GIRL') | |
def use_variable_args(*args): | |
print(args) | |
use_variable_args(*cu) #('I', 'AM', 'GIRL') | |
# 응용2 - 인자를 여러 개 섞어서 함수 만들기 | |
''' | |
def func_param_with_var_args(name, *args, age): | |
print("name=",end=""), print(name) | |
print("args=",end=""), print(args) | |
print("age=",end=""), print(age) | |
func_param_with_var_args("정우성", "01012341234", "seoul", 20) # TypeError!! | |
''' | |
# 문제점 : 가변 인자의 개수를 알 수 없음(응용1과 비슷) => 위치 인자들에 잘못 할당될 수도 있음. | |
# 해결 : 가변 길이 인자를 위치 인자의 뒤로 보내줘서 위치 인자에 먼저 할당 될 수 있게 해줘야 한다 | |
def func_param_with_var_args2(name, age, *args): | |
print("name=",end=""), print(name) | |
print("args=",end=""), print(args) | |
print("age=",end=""), print(age) | |
func_param_with_var_args2("정우성", 20, "01012341234", "seoul") | |
########################################################### | |
# 가변 키워드 인자(Variable length keyword arguments) | |
# 위치 인자 뿐 아니라 키워드 인자 또한 가변 길이로 전달 가능. | |
# dictionary를 unpacking해서 전달. | |
kwargDic = {'1':'I', '2':'am', '3':'cute'} | |
def use_kwargs(**kwargs): | |
for i, j in kwargs.items(): | |
print(i, j) | |
#1 I | |
#2 am | |
#3 cute | |
use_kwargs(**kwargDic) | |
# 응용3 - 가변 길이 인자와 가변 키워드 인자를 동시에 전달 | |
# 인자 위치 주의 할 것 | |
def useTwoArgs(a, b, *args, **kwargs): | |
print(F'a = {a}') | |
print(F'b = {b}') | |
print(F'args = {args}') | |
print(F'kwargs = {kwargs}') | |
#a = 1 | |
#b = 2 | |
#args = ('star', 'moon', 'jupiter', 'earth') | |
#kwargs = {'x': 100, 'y': 200, 'z': 300} | |
useTwoArgs(1, 2, 'star', 'moon', 'jupiter', 'earth', x=100, y=200, z=300) |
몫 : //
나머지 : %
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
입출력 속도 향상 _ ex 리스트 입력 받기
import sys
n = int(input())
card = list(map(int, sys.stdin.readline().split()))
m = int(input())
check = list(map(int, sys.stdin.readline().split()))