💻
Albert's Til
GitHub
  • 매일매일 조금씩 성장하기
    • README
    • CS
      • Network
      • HTTP
        • NO-CACHE
      • 오류 코드
      • ORM 도구
      • Design Pattern
        • CQRS Pattern
          • Event Sourcing and CQRS pattern
        • Builder Pattern
    • DB
      • MySQL
        • Timeline
        • Pagination
        • Index
        • Database Performance Optimization Strategies
        • B+ tree
        • MySQL Connectors VS MySQL Shell(Scripting) VS MySQL Workbench
        • MySQL Storage Engine Architecture
      • Normalization & Denormalization
      • JPA
        • @Transactional
        • Why JPA?
        • About JPA
        • N+1 Issue
        • Index
        • ElementCollection&CollectionTable
        • orphanRemoval
        • CascadeType
        • Use Subselect
        • Dynamic Instance Creation
        • Paging
        • Order
        • Spefication
        • mappedBy
      • MongoDB
        • ObjectId
      • Why MySQL?
      • ACID properties of transactions
      • Between JPA and JDBC
      • Identifiers in Hibernate/JPA
    • Java
      • Jackson de/serialize
      • Collections.singletonList() vs List.of()
      • Manage dependencies in Gradle
      • Logging Level
      • Bean Validation
      • JVM Internals
        • Threads
          • Frame
        • Shared Between Threads
          • Classloader
            • Class Loader Hierarchy
            • Loading Linking Initialization
      • Java Collection Framework
      • Annotation
      • Generic
      • 디미터 법칙
    • Spring
      • Caching
      • Spring Integration Overview
        • ThreadPollTaskExecutor
        • Messaging Bridge
        • Channel Adapter
        • Poller
        • Configuration and @EnableIntegration
        • Message Endpoints
        • Message Channels
      • HATEOAS
      • @Autowired vs Constructor Dependency Injection
      • Spring Security
        • JWT 토큰 사용한 인가
        • OAuth 2 Login
        • OAuth 2 인증
        • 인가
        • 인증
        • PasswordEncoder
      • IoC Container
      • Filter,Interceptor,AOP,Argument Resolver
      • Spring Annotation
      • About Spring
    • Kafka
      • Error Channel
    • Infra
      • Scale Up || Scale Out
      • Docker
        • Dockerfile
        • Docker Hub Deploy
        • Command
      • Cloud 유형
        • Infrastructure as a Service
        • Platform as a Service
        • Software as a Service
      • 무중단 배포
        • 엔진엑스(Nginx)
      • 코드 자동 배포
        • Technical
      • AWS EC2
        • PEM(Privacy Enhanced Mail) 키
      • AWS RDS
      • AWS S3
    • CodeSquad
      • Spring Boot Project 1주차 회고
      • Spring Boot Project 2주차 회고
      • Spirng Boot Project 3주차 회고
      • Spring Boot Project 4주차 회고
    • Foody Moody 프로젝트
      • Query Performance Comparison
      • HeartCount Asynchronous Issue
      • DeferredResult
      • ResponseBodyEmitter
      • SseEmitter (Spring)
      • Server-Sent Events (SSE)
      • 기술 스택 적용 이유
      • NO-CACHE(HTTP)
      • Transactional
    • DDD
      • AggregateId
    • Test
      • RestAssured
    • Coding and Algorithmic Problems
      • 819. Most Common Word
      • 344. Reverse String
      • 125. Valid Palindrome
      • 937. Reorder Data in Log Files
    • Node
      • Async... Await...
      • Custom Transactional Decorator Challenger
    • Python
      • Python Basic Grammar
        • Comments and Input/Output
        • Variable
        • Data type
        • Operations and syntax
        • List,Tuple,Dictionary,Set
        • Function
        • Conditional statement
        • Loop
    • HTML
      • HTML Basic
      • HTML Basic Tags
      • HTML Form Tags
      • HTML Table Tags
    • CSS
      • CSS Basic
      • CSS Practice
Powered by GitBook
On this page
  • 구성 요소
  • 전역변수
  • pass
  • 자주 사용하는 내장 함수
  • 참조

Was this helpful?

  1. 매일매일 조금씩 성장하기
  2. Python
  3. Python Basic Grammar

Function

함수

Last updated 11 months ago

Was this helpful?

함수는 특정 작업을 수행하는 코드 블록으로, 필요할 때마다 호출하여 재사용할 수 있습니다.

구성 요소

전역변수

  • 전역 변수 읽기: 함수 내부에서 전역 변수를 읽기만 할 때는 global 키워드가 필요 없습니다.

  • 전역 변수 수정: 함수 내부에서 전역 변수를 수정하려면 global 키워드를 사용해야 합니다.

  • 지역 변수와 전역 변수 구분: 함수 내부에서 동일한 이름의 변수를 할당하면 지역 변수로 간주되며, 이는 전역 변수와는 별개의 변수입니다. 이로 인해 혼동이 발생할 수 있으므로 주의가 필요합니다.

pass

pass는 파이썬에서 아무런 작업도 하지 않는 문장입니다. 함수, 루프, 조건문 등의 블록을 작성할 때 임시로 사용하거나, 문법적으로 블록이 필요하지만 아무 작업도 수행하지 않도록 할 때 유용합니다.

자주 사용하는 내장 함수

함수 이름
설명
사용 예제

abs()

숫자의 절대값을 반환합니다.

abs(-5) # 결과: 5

all()

모든 요소가 참인지 검사합니다.

all([True, True, False]) # 결과: False

any()

하나 이상의 요소가 참인지 검사합니다.

any([True, False, False]) # 결과: True

bin()

정수를 2진수 문자열로 변환합니다.

bin(10) # 결과: '0b1010'

bool()

값을 불리언으로 변환합니다.

bool(0) # 결과: False

chr()

유니코드 코드 포인트를 문자로 변환합니다.

chr(97) # 결과: 'a'

dict()

새로운 딕셔너리를 생성합니다.

dict(a=1, b=2) # 결과: {'a': 1, 'b': 2}

dir()

객체의 속성 및 메서드 리스트를 반환합니다.

dir([]) # 결과: [..., 'append', ...]

divmod()

몫과 나머지를 튜플로 반환합니다.

divmod(9, 4) # 결과: (2, 1)

enumerate()

열거 객체를 반환합니다.

enumerate(['a', 'b']) # 결과: (0, 'a'), ...

eval()

문자열로 표현된 파이썬 코드를 실행합니다.

eval('1 + 2') # 결과: 3

filter()

조건에 맞는 요소를 걸러냅니다.

filter(lambda x: x > 0, [-1, 0, 1]) # 결과: [1]

float()

값을 부동 소수점 숫자로 변환합니다.

float('3.14') # 결과: 3.14

format()

값을 특정 형식으로 포맷합니다.

format(255, '02x') # 결과: 'ff'

getattr()

객체의 속성 값을 반환합니다.

getattr(obj, 'attr', default)

hasattr()

객체에 속성이 있는지 확인합니다.

hasattr(obj, 'attr') # 결과: True/False

hex()

정수를 16진수 문자열로 변환합니다.

hex(255) # 결과: '0xff'

int()

값을 정수로 변환합니다.

int('10') # 결과: 10

isinstance()

객체가 특정 클래스의 인스턴스인지 확인합니다.

isinstance(10, int) # 결과: True

len()

객체의 길이나 항목 수를 반환합니다.

len([1, 2, 3]) # 결과: 3

list()

새로운 리스트를 생성합니다.

list('abc') # 결과: ['a', 'b', 'c']

map()

각 요소에 함수를 적용합니다.

map(str, [1, 2, 3]) # 결과: ['1', '2', '3']

max()

최대값을 반환합니다.

max([1, 2, 3]) # 결과: 3

min()

최소값을 반환합니다.

min([1, 2, 3]) # 결과: 1

oct()

정수를 8진수 문자열로 변환합니다.

oct(8) # 결과: '0o10'

open()

파일을 엽니다.

open('file.txt', 'r')

ord()

문자의 유니코드 코드 포인트를 반환합니다.

ord('a') # 결과: 97

pow()

거듭제곱을 계산합니다.

pow(2, 3) # 결과: 8

print()

값을 출력합니다.

print('Hello')

range()

숫자 시퀀스를 생성합니다.

range(5) # 결과: [0, 1, 2, 3, 4]

reversed()

역순 반복자를 반환합니다.

reversed([1, 2, 3]) # 결과: [3, 2, 1]

round()

숫자를 반올림합니다.

round(3.14159, 2) # 결과: 3.14

set()

새로운 집합을 생성합니다.

set([1, 2, 2, 3]) # 결과: {1, 2, 3}

sorted()

정렬된 리스트를 반환합니다.

sorted([3, 1, 2]) # 결과: [1, 2, 3]

str()

값을 문자열로 변환합니다.

str(123) # 결과: '123'

sum()

합계를 계산합니다.

sum([1, 2, 3]) # 결과: 6

tuple()

새로운 튜플을 생성합니다.

tuple([1, 2, 3]) # 결과: (1, 2, 3)

type()

객체의 타입을 반환합니다.

type(123) # 결과: <class 'int'>

zip()

여러 이터러블을 묶어서 튜플의 이터레이터를 반환합니다.

zip([1, 2], ['a', 'b']) # 결과: [(1, 'a'), (2, 'b')]

참조

ChatGPT

견고한 파이썬
https://www.geeksforgeeks.org/python-functions/