max(x) 함수란?

max 함수는 인수로 받은 x 값안에서 가장 큰 값을 찾아 반환하는 파이썬 내장 함수입니다.

인수 x로는 list, dictionary, 튜플, 문자열 등 iterable 자료형을 넣을 수 있습니다.

 

또는 max(x, y, ... , z) 와 같이 인자를 두 개 이상 넣고 비교할 수 있습니다.

 

iterable한 자료형은 말 그대로 반복 가능한 자료형으로

list와 같이 자료형 내부 값을 순서대로 하나씩 접근할 수 있는 자료형을 말합니다.

 

이제 max 함수의 사용 예시를 보여드리겠습니다.

 

1
2
3
print(max(1234))
 
결과: 4
cs

 

list
1
2
3
4
5
list = [1234]
 
print(max(list))
 
결과: 4
cs

 

tuple
1
2
3
4
5
tuple = (1234)
 
print(max(tuple))
 
결과: 4
cs

 

문자열
1
2
3
4
5
string = "hello"
 
print(max(string))
 
결과: "o"
cs

문자열은 위와 같이 abcd 알파벳 순서를 기준으로

a가 가장 작은 값, z가 가장 값으로 되어 있습니다.

 

위의 예시외로 dictionary 자료형과 key, default를 이용한 다양한 사용법이 있습니다.

이것들은 다음번에 소개해드리도록 하겠습니다.

 

'개발 > Python' 카테고리의 다른 글

__name__ 변수는 무엇인가  (0) 2021.08.07

파이참으로 새로운 프로젝트를 만들고 나서 기본 파일 main.py에 선언되지 않은 __main__이라는 변수가 있었다.

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

파일명이 main.py였기 때문에 파일명이 들어가는 줄 알고 a.py라는 파일을 만들어봤다.

a.py에서는 if문이 False가 될 줄 알았지만 아니였다.

 

찾아보니 __name__ 변수는 파이썬에 기본적으로 내장된 변수이고, 다른 곳에서 해당 파일(__name__ 변수가 사용된 파일)을 import해서 사용할 대 모든 코드들이 실행되는 것을 방지하기 위해 사용된다고 한다.

 

import해서 사용하면 __name__에는 모듈(파일)의 이름이 들어가고, import가 아닌 해당 파일에서 실행할 경우 __main__이라는 값이 들어간다고 한다.

 

 

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':  # __name__ 변수는 파이썬에 이미 존재하는 내장변수이다.
    # 이 파일을 다른 곳에서 import해서 사용하면 __name__에 파일의 이름 (여기서는 a)이 담긴다.
    # 하지만 다른 곳이 아닌 여기서 실행하면 __name__에는 __main__이 담긴다.
    # 다른 곳에서 이 파일을 import해서 사용할 때 모든 코드들이 실행되는 것을 방지하기 위해 사용된다.
    print_hi('PyCharm')

a.py 파일

'개발 > Python' 카테고리의 다른 글

[python] max 함수 사용법  (0) 2022.12.20

+ Recent posts