Development/Python

파이썬 기초 (6분 컷)

juniz 2020. 8. 20. 22:54
반응형

파이썬 특징

  • 인터프리터 언어
  • 객체지향적
  • 동적 타이핑 (실행 시 자료 검사)
  • C와 같은 언어랑 비교해서 속도가 다소 느리다.
    (하지만, 일반인은 큰차이를 느끼기 어렵다..)
  • ; 대신에 들여쓰기(tab)으로 구분한다

파이썬의 철학 

The Zen of Python으로 PEP20 에서 찾아볼수 있다. 

시간이 나면 한번씩 읽어보는 것도 나쁘지 않습니다. 

import this
'''
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!
'''

 

파이썬 기본 [참조 : w3resource]

Syntax

Tab 으로 각 라인을 구분합니다. 

x = 1
if x>0:
	print(x)
    
# 아래 코드는 실행되지 않습니다.
if x>0:
print(x)

Print

# Single Line Print
print('Hello World')

# Multiline Print
>>> print('''
Hello World\n # \n : new line
Hello World
\tHello World # \t : tab
''')

Hello World

Hello World
        Hello World

# Print with variable
name = 'Niz'
print('Hello {name}')

# Print multiple things
>>> print('Hello' + 'Niz') # only str + str is allowed
HelloNiz

>>> print('hello','Niz')
hello Niz 

# Difference
>>> print('Hello' + 1) 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str # 가장 중요한 부분

>>> print('Hello',1)
Hello 1 

 

Variable

  • Must start with: a_z, A_Z, _
  • Case sensitive
  • Rules
    • my_name (o)
    • MyName (x) : Using uppercase for first String is recommended for class 
    • myName(x)
# 기본 
>>> a = 123
>>> type(a)
<class 'int'>
>>> b = 1.01
>>> type(b)
<class 'float'>
>>> c = (1,2,3)
>>> type(c)
<class 'tuple'>

# 연산 
>>> a = 9
>>> b = 3
>>> a + b
12
>>> a - b
6
>>> a / b
3.0
>>> a // b
3
>>> a % b
0
>>> a * b
27
>>> a ** b
729

 

If, elif, else, for, while

위에서 적은대로 indent만 신경써서 하시면 됩니다. 

# If elif else

>>> a = 1
>>> if a>0:
...     print(f'{a} is bigger than 0')
... elif a==0:
...     print(f'{a} is 0')
... else:
...     print(f'{a} is smaller than 0')
...
1 is bigger than 0

# Nested if statements with or 
>>> age = 38
>>> if (age >= 11):
...   print ("You are eligible to see the Football match.")
...   if (age <= 20 or age >= 60): # or  / and 사용 가능합니다. 
...       print("Ticket price is $12")
...   else:
...       print("Tic kit price is $20")
... else:
...     print ("You're not eligible to buy a ticket.")
...
You are eligible to see the Football match.
Tic kit price is $20


# While
1 is bigger than 0
>>> a = 10
>>> while a > 5:
...    print(f'a : {a}')
...    a -= 1
...
a : 10
a : 9
a : 8
a : 7
a : 6



# For
>>> for i in range(0,10): # start, end(exclude)
...     print(i)
...
0
1
2
3
4
5
6
7
8
9
>>> for i in range(0,10,2): # start, end(exclude), increment 
...     print(i)
...
0
2
4
6
8

 

Lists, Tuples, Dictionary, Sets

  • List [ ] 
    • Can store multiple values (doesn't have to be the same type)
  • Dictionary { }
    • key : value
  • Tuple ( )
    • Same as List but immutable
  • Sets : set()
    • Store only unique values
# List
>>> first_list = [1,2,3]
>>> first_list[0] # First index
1

# Slicing
>>> first_list[0:2] # start : end(exclude)
[1, 2]
>>> first_list[:] # everything
[1, 2, 3]
>>> first_list[:1] # end(exclude)
[1]
>>> first_list[-1] # Last index
3
>>> min(first_list)
1
>>> max(first_list)
3

# Tuples 
>>> first_tuple = (1,2,3) 
>>> first_tuple[1]
2

# Same as list except tuples are immutable(최초 지정 후 데이터 변경 불가능)
>>> first_tuple[1] = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


>>> complex_list = [i for i in range(11)] # One line for statement (optional)
>>> len(complex_list) # get Length
11
>>> complex_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> complex_list[1:6:2] # start : stop : end
[1, 3, 5]


# Dict {'key':value}
>>> first_dict = {'first':1, 'second':2,'third':3}

# For loop will return the keys only
>>> for key in first_dict:
...    print(f'key : {key}')
...
key : first
key : second
key : third

# To get the key and values
>>> for key, value in first_dict.items():
...     print(f'key : {key} \n value : {value}')
...
key : first
 value : 1
key : second
 value : 2
key : third
 value : 3
 

# Sets
# Keep unique values only 
>>> first_set = set([1,2,2,2,3,4,5]) # 2,2는 삭제
>>> first_set
{1, 2, 3, 4, 5}

 

여기까지가 기본입니다. 

공부를 더 하고 싶으시다면

pythonic coding, built-in functions, library 등을 보시면 좋습니다. 

모든 문법을 무조건 외우고 사용하시는 것 보다,

본인이 하고싶은신 걸 (간단한거부터...) 구현하면서 

찾아보고 손에 익숙해지는게 중요합니다. 

반응형