
우연한 계기로 남는 시간 짬을 내어 파이썬 기초 문법과 자료 구조 이해 여부를 확인하는 시간을 가지게 되었습니다.
참고
or i in range(5):
print(i)
0
1
2
3
4
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} equals {x} * {n//x}")
break
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3
for num in range(2, 10):
if num % 2 == 0:
print(f"짝수 찾기 : {num}")
continue
print(f"홀수 찾기 : {num}")
짝수 찾기 : 2
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
2 is a prime number
3 is a prime number
class MyEmptyClass:
pass
일반적으로 최소 클래스 (기본 생성자) 만드는데 사용
초간단 예시
for i in range(2,10): # 1번 for문
for j in range(1, 10): # 2번 for문
print(i*j, end=" ")
print('')
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
result = [x*y for x in range(2,10)
for y in range(1,10)]
>>> print(result)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16,
20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42
, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72,
9, 18, 27, 36, 45, 54, 63, 72, 81]
요약
append(): 리스트의 끝에 값을 추가
insert(): 지정한 위치에 값을 삽입
remove(): 리스트에서 첫 번째로 일치하는 값을 삭제
sort(): 리스트를 정렬
reverse(): 리스트의 순서를 반대로 뒤집기
count(대상): 리스트 내에서 대상의 개수 세기
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.append(points)
print(fruits)
['apple', 'banana', 'cherry', (1, 4, 5, 9)]
...
fruits.expends(points)
print(fruits)
['apple', 'banana', 'cherry', 1, 4, 5, 9]
get_list_len = ["apple", "banana", "cherry"]
print(len(get_list_len))
3
list.insert(i, x) : 주어진 변수를 리스트에 삽입
remove(x) : 값이 x와 동일한 첫번째 항목 삭제
pop([i]) :
clear
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
[]
index(x[start[ end]])
a = [10, 20, 30, 40, 50, 40, 60, 40, 70]
res = a.index(40, 4, 8)
print(res)
`5`
- count(x) : 리스트에서 x 등장 횟수 조회
- sort(*, key=None, reverse=False) : 리스트 요소 제자리 정렬
- reverse() : 리스트 요소 뒤집기. 역정렬
- copy() : 얕은 사본 돌려주기
```python
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.count('apple')
fruits.count('tangerine')
fruits.index('banana')
fruits.index('banana', 4) # 위치 4에서부터 다음 banana 를 찾습니다
fruits.reverse()
fruits
fruits.append('grape')
fruits
fruits.sort()
fruits
fruits.pop()
리스트를 스택, 큐로도 사용 가능
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
stack.pop()
stack
stack.pop()
stack.pop()
stack
from collections import deque
queue = deque(["배달이", "네이버", "커피빈"])
queue.append("애플") # 애플 도착
queue.append("아마존") # 아마존 도착
queue.popleft() # 처음 도착한 사람이 이제 떠납니다
queue.popleft() # 두번째 도착한 사람이 이제 떠납니다
queue # 도착한 순서대로 남아있는 큐
a = [3, 1, 2, 4]
print(sorted(a)) # [1, 2, 3, 4]
a = [3, 1, 2, 4]
a.sort()
print(a) # [1, 2, 3, 4]
a = ["cd", "ab", "bc"]
print(sorted(a)) # ["ab", "bc", "cd"]
a = ["cd", "ab", "bc"]
a.sort()
print(a) # ["ab", "bc", "cd"]
a = [1, 2, 3, 4]
print(*a) # 1 2 3 4
a = ["ab", "bc", "cd"]
print(*a) # ab bc cd
리스트 값 모두 합치기
a = [3, 1, 2, 4]
print(sum(a)) # 10
a = [3, 1, 2, 4]
print(len(a)) # 4
a = [3, 1, 2, 4]
print(sum(a)/len(a)) # 2.5
리스트의 최댓값
a = [3, 1, 2, 4]
print(max(a)) # 4
a = [3, 1, 2, 4]
print(min(a)) # 1
a = [3, 1, 2, 4]
print(a.index(2)) # 2
a = [1, 2, 3, 4]
for i in a:
print(i)
a = ["ab", "bc", "cd"]
for i in a:
print(i)
>>> t1 = (1, 2, 'a', 'b')
>>> t1[0]
1
>>> t1[3]
'b'
>>> t1 = (1, 2, 'a', 'b')
>>> t1[1:]
(2, 'a', 'b')
>>> t1 = (1, 2, 'a', 'b')
>>> t2 = (3, 4)
>>> t3 = t1 + t2
>>> t3
(1, 2, 'a', 'b', 3, 4)
>>> t2 = (3, 4)
>>> t3 = t2 * 3
>>> t3
(3, 4, 3, 4, 3, 4)
>>> t1 = (1, 2, 'a', 'b')
>>> len(t1)
4
directions = ("North", "South", "East", "West")
for direction in directions:
print(direction)
# North
# South
# East
# West
menu = ('짜장면', '짬뽕', '탕수육', '라조기', '팔보채', '깐풍기', '라조기')
menu.count('라조기')
tuple1 = (1, 2, 3)
tuple2 = ('짜장면', '짬뽕', '탕수육')
tuple3 = tuple1 + tuple2
print(tuple3) # 1, 2, 3, 짜장면, 짬뽕, 탕수육
| key | value |
|---|---|
| name | pey |
| phone | 010-9999-1234 |
| birth | 1118 |
| date | [0612, 0613, 0613] |
vd1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
d = { "name": "장남이", 1: "Python", (1, 2): [1,2,4] }
# Access using key
print(d["name"])
# Access using get()
print(d.get("장남이"))
d = {1: '장남이', 2: '반복', 3: '당근', '나이':30}
del d["나이"]
print(d)
# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)
# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")
# Clear all items from the dictionary
d.clear()
print(d)
>>> a = {'name': '장남이', 'phone': '010-9999-1234', 'birth': '0614'}
>>> a.get('name')
'장남이'
>>> a.get('phone')
'010-9999-1234'
grades = {"수학": 90, "과학": 85, "영어": 95}
for subject, score in grades.items():
print(subject, ":", score)
장점
단점
"Life is too short, You need Python"
"a"
"123"
>>> a = "Life is too short"
>>> a.split()
['Life', 'is', 'too', 'short']
>>> b = "a:b:c:d"
>>> b.split(':')
['a', 'b', 'c', 'd']
>>> d = {'name':'장남이', 'age':30}
>>> f'나의 이름은 {d["name"]}입니다. 나이는 {d["age"]}입니다.'
'나의 이름은 장남이입니다. 나이는 30입니다.
>>> y = 3.42134234
>>> "{0:0.4f}".format(y)
'3.4213'
>>> a = "hi"
>>> a.upper()
'HI'
>>> a = "HI"
>>> a.lower()
'hi'
>>> a = "Life is too short"
>>> a.replace("Life", "Your leg")
'Your leg is too short'
>>> s = "12345"
>>> s.isdigit()
True
>>> s = "1234a"
>>> s.isdigit()
False
>>> s = "12 34"
>>> s.isdigit()
False
>>> s = "12345"
>>> s.isdigit()
True
>>> s = "1234a"
>>> s.isdigit()
False
>>> s = "12 34"
>>> s.isdigit()
False
>>> s = "Life is too short"
>>> s.startswith("Life")
True
>>> s.startswith("short")
False
>>> s = "Life is too short"
>>> s.endswith("short")
True
>>> s.endswith("too")
False
>>> a = "hobby"
>>> a.count('b')
2
>>> a = "Python is the best choice"
>>> a.find('b')
14
>>> a.find('k')
-1
>>> a = "Life is too short"
>>> a.index('t')
8
>>> a.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> a = "20250614"
>>> year = a[:4]
>>> month = a[4:6]
>>> date = a[6:]
>>> date_format = "현재 날짜는 {}년 {}월 {}일 입니다."
>>> print(date_format.format(year, month, date))
현재 날짜는 2025년 06월 14일 입니다.
# 파일을 쓰기 모드('w')로 열어서 'Hello.txt' 파일을 생성
file = open('Hello.txt','w')
# 파일에 문자열 'Hello, world!'를 작성
file.write('Hello, world!')
# 파일 닫기
file.close()
# for문을 사용하여 파일에 문자열을 쓰기 위해 파일을 쓰기 모드('w')로 열기
file = open('Hello.txt', 'w')
# for문을 사용하여 1부터 10까지의 숫자를 각 줄에 쓰기 위해 반복
for i in range(1, 11):
data = f'{i}번째 줄입니다.\n' # 문자열에 개행 문자를 추가하여 줄바꿈합
file.write(data) # 파일에 문자열 작성
write 함수는 엔터 기능이 없으므로 개행 문자를 직접 추가해야 함
# 파일 닫기
file.close()

# mod1.py
def add(a, b):
return a + b
def sub(a, b):
return a-b
"""
작성자 : 장남이
작성일 : 2025-06-14
내용 : 재사용 가능한 사칙연산 모듈 생성
"""
# object.py
def add(a, b):
return a + b
def substraction(a, b):
return a-b
def multiple(a, b):
return a * b
def division(a, b):
return a / b
import object.py
table = object.multiplue(9,9)
print(table) # 81
import math
sqrt = math.sqrt(9) # 3.0
factorial = math.factorial(5) # 120
import requests
response = requests.get("www.naver.com")
valid_access = response.status_code
implement = response.text
print(valid_access) # 웹사이트 통신 상태 검증
print(implement) : 웹사이트 조회 내용
directory/
_init_.py
my_app.py
import my_app
from directory import my_app.py