💻Python Basic

지난 주 codelion을 이용한 파이썬 학습 이후, 본격적인 수업이 시작되었다.
파이썬을 여러번 배웠던만큼, 새롭게 알게 된 내용과 헷갈리는 내용만 정리한다.

Zen of Python

파이썬의 철학이다. 파이썬을 2020년에 처음 배웠지만, 이런 건 배웠었던가...?

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

되게 멋진 말들이다.

  • 복잡한 것보다 단순한 것이 낫다.
  • 암시적인 것보다 복잡한 것이 낫다.
  • 가독성은 중요하다.

위의 말들은, 파이썬이 추상적인 언어라는 걸 쉽게 푼 것 같다.
괜히 파이썬이 배우기 쉬운게 아니다.

이 중 박조은 강사님이 가장 좋아하는 말은,

Now is better than never.
안하는 것보다 하는게 낫다

이 덕에 내가 velog를 쓰고 있다.

변수명

파이썬은 다양한 예약어가 존재한다. 그렇기에 변수명을 설정하는데 제약이 있다는 것은 모두가 안다. 그런데, 이러한 예약어와 함수명의 종류를 볼 수 있는 코드가 있다.

import keyword # 파이썬 키워드

keyword.kwlist
['False',
 'None',
 'True',
 'and',
 'as',
 'assert',
 'async',
 'await',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']
import builtins # 파이썬 함수명

dir(builtins)		# dir(arg): arg의 변수와 method 나열
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BlockingIOError',
 'BrokenPipeError',
 'BufferError',
 'BytesWarning',
 'ChildProcessError',
 'ConnectionAbortedError',
 'ConnectionError',
 'ConnectionRefusedError',
 'ConnectionResetError',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FileExistsError',
 'FileNotFoundError',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'InterruptedError',
 'IsADirectoryError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'ModuleNotFoundError',
 'NameError',
 'None',
 'NotADirectoryError',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'PermissionError',
 'ProcessLookupError',
 'RecursionError',
 'ReferenceError',
 'ResourceWarning',
 'RuntimeError',
 'RuntimeWarning',
 'StopAsyncIteration',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'TimeoutError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__build_class__',
 '__debug__',
 '__doc__',
 '__import__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'abs',
 'all',
 'any',
 'ascii',
 'bin',
 'bool',
 'breakpoint',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'display',
 'divmod',
 'enumerate',
 'eval',
 'exec',
 'execfile',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'repr',
 'reversed',
 'round',
 'runfile',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'vars',
 'zip']

bool을 이용한 코드

조건문에서 bool값을 이용한 코드를 짤 수 있다.
bool값에서 0이면 False, 0이 아닌 값이 True임을 이용해 홀짝 구분을 하는 코드를 작성해보자

import random
for i in range(10):
	n = ramdom.randint(0, 100)
 	if n % 2:
		print(f"{n}" : 홀수 ")
	else:
		print(f"{n}" : 짝수 ")

추가적으로 f-strang을 적극적으로 이용하면 코드가 한결 아름다워질 수 있다.

기타 학습에 참고할 코드

function?  	# 도움말 
function?? 	# 소스코드
dir(arg)	# arg의 변수, method 확인

참고문헌

profile
데이터 분석가를 꿈꿈

0개의 댓글