DATA ANALYSIS/TIL

[Day3] Python 기초(1)

yel1nk 2023. 4. 28. 01:32

변수의 type

def hello():
    return

class A:
    pass

a = 10              # int, 정수형
b = 10.1            # float, 실수
c = -1
d = True            # bool, 논리형(부울형, 참거짓형)
f = '10'            # str, 문자열
j = 10 + 2j         # complex, 복소수
k = 0b110           # int, 2진법 
l = 0o56            # int, 8진법
m = 0xAC            # int, 16진법
n = hello           # function
o = print           # bulit-in function
p = lambda x:x**2   # function
q = A               # class
r = A()             # instance

변수의 속성

  • 영문과 숫자를 사용할 수 있지만, 숫자로 시작하지는 못합니다.

  • 특수문자는 사용하지 않아요.(언더바(_)는 사용합니다. 스네이크 표기법, 특수문자나 이미중 사용 가능한 것들이 있기는 합니다. 권하지 않습니다.)

  • 예약어는 사용하지 않습니다.(if, elif, while, for, etc)

  • 대소문자는 구분합니다.

  • 언더바로만 사용하거나 언더바로 시작할 수 있습니다.

  • 대문자로 시작하는 변수를 사용할 수 있지만(파스칼 표기법), 관습적으로 대문자로 시작하는 변수는 Class로 만들기 때문에 소문자로 시작하는 변수를 만들기를 권합니다.

  • 카멜 표기법(Camel Case)
    int totalNumber;

  • 파스칼 표기법(Pascal Case)
    int TotalNumber;

  • 헝가리안 표기법(Hungarian Notation)
    String strName;

  • 스네이크 표기법(Snake Case)
    int total_number;

입력과 출력

type(print)
# builtin_function_or_method

[Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

docs.python.org](https://docs.python.org/3/library/functions.html)

PEP(Python Enhancement Proposal)

  • pep8 : Style Guide for Python Code
  • pep20 : The Zen of Python
  • [PEP 0 – Index of Python Enhancement Proposals (PEPs) | peps.python.org

PEP 0 – Index of Python Enhancement Proposals (PEPs) Author: python-dev Status: Active Type: Informational Created: 13-Jul-2000 Table of Contents This PEP contains the index of all Python Enhancement Proposals, known as PEPs. PEP numbers are assigned by

peps.python.org](https://peps.python.org/)

str (문자열)

upper(), isupper(), isdigit(), isalpha()
count('x')

a = ''
print('test'.count(a))
print(a.count(''))
# ' t e s t ' => 빈 문자가 5번 카운팅

center(10), rjust(10), rleft(10)

index('x'): 못찾으면 error
find('x'): 못찾으면 -1
strip() : 공백 지우기
zfill(10) : 채우기
join() : 합치기 - str 에서만 가능
split(' ') : 나누기 => list 반환

'010-0000-0000'.split('-')
# ['010', '0000', '0000']

replace('a', 'b') : 바꾸기 - str 에서만 가능, 메서드 체이닝

formatting

  • % 용법

  • format 용법

  • f-string 용법 (3.6 ver ~)

    print(f'{"hello":!<10}')
    print(f'{"hello":=>10}')
    print(f'{"hello":~^10}')
    
    # hello!!!!!
    # =====hello
    # ~~hello~~~
  • a = 10 # 아래 3개는 모두 string 입니다. print('hello world {}'.format(a)) # format 용법 print(f'hello world {a}') # f-string 용법 print(r'hello world {a}')` # raw : 날것의

문자열의 활용

s = 'hello world'
s[:-1]    # 마지막 글자만 제거
s[::-1]   # 거꾸로

형변환

s = [('name','kimyelin'),('age',10)]
print(dict(s))
print(set('kimyelin'))

# {'name': 'kimyelin', 'age': 10}
# {'i', 'n', 'y', 'l', 'm', 'k', 'e'}
num = 1234567890
print(list(str(num))[3])

# '4'

연산

  • 산술연산
    • +, -, /, //(몫), , *, %(나머자)
  • 비교연산
    • ==, !=, >, >=, <, <=
  • 논리연산
    • True, False, and, or, not
    • or : 첫 피연산자가 True이면 다음 피연산자를 보지않아도 값이 True
    • and : 첫 피연산자가 False이면 다음 피연산자를 보지않아도 값이 False
    • 10 and 20 # 20 0 and 20 # 0 10 or 20 # 10 4 and 10 or 20 # 10
  • 비트연산
  • 할당연산
    • +=
  • 식별연산
    • is, is not
    • a = [1,2,3] b = [1,2,3] id(a), id(b) # 139732084551744 139732082864832 a is b # False a == b # True - 메모리 주소(id)가 아니라 '값'만 비교함 -> 유저의 입장
  • 멤버연산
    • in, not in, issubset()
    • {10, 20, 30} in {10, 20, 30} # False {10, 20, 30} in [{10, 20, 30}] # True [10, 20, 30] in [[10, 20, 30]] # True [10, 20, 30] in [[10, 20, 30], 20, 30] # True

'DATA ANALYSIS > TIL' 카테고리의 다른 글

[Day7] Python 기초(5)  (0) 2023.05.04
[Day6] Python 기초(4)  (0) 2023.05.03
[Day5] Python 기초(3)  (0) 2023.05.02
[Day4] Python 기초(2)  (0) 2023.04.29
[Day2] 데이터 분석 개론/Github 기초  (0) 2023.04.26