쫑가 과정

Python 기초 이론 박살내기! 본문

프로그래밍 공부/파이선_정보취합하기

Python 기초 이론 박살내기!

쫑가 2021. 5. 17. 18:39

목차

[python] [variable] [sequence type] 1.list 2.tuple 3.dictionary [functions] 1.bulit-in 2.creating python 3.return 4.argument 5.if -else, elif 6.for in [module]

Python?

세계에서 인기 있는 프로그래밍 언어 중 하나

 

1. 초보자 이해하기 아주 쉬운데 전문가도 계속 파이썬 사용

 

자동화, 데이터 얻고 정리, 도큐먼트 압축

데이터베이스 migrate, 유튜브 비디오 다운

오디오 압축 이미지 폴더 옮길 때

등 아주 많이 사용 가능

 

Google, dropbox, Youtube, Reddit, NASA 등 다 파이썬 사용

 

2. 아름다움과 강력함 사이의 조화가 좋아

 

읽기 굉장히 쉽게 생겼다

파이썬 커뮤니티가 아주 잘 되어있다.

다양한 분야 사람들이 모두 파이썬 커뮤니티에 온다.

그 분야 코드들을 다 읽을 수 있다.

파이썬을 배우면 모든 옵션이 가능하다

 

variable(변수)

수학에서 배운 것과 아주 비슷하다.

1. 변수에 저장할 수 있는 타입

#정수 = integer(int)
print(type(111))

#문자 = string(str) of text
print(type("문자"))

#참거짓 = boolean(bool) / True(1) or False(0)
#(0은 꺼짐, 1은 켜짐, 코딩할 때 0을 제외한 모든 정수는 True)
print(type(True))

#소수= float
print(type(11.1))

#존재하지않음 = None(NoneType)
print(type(None))
------------------
class 'int'
class 'str'
class 'bool'
class 'float'
class 'NoneType'

2. 변수를 길게 지어야 할 때

Python 사용자들의 암묵적인 약속

단어 사이에 _ = snake case

 

super_long_variable

 

Sequence Type

열거형 타입

1. list

많은 값을 하나의 list에 저장한다.

대괄호[]로 묶어주고 하나씩 ""(string)을 해준다.

a = ["월", "화", "수", "목"]
print(type(a))
print(a)
------------------------------
<class 'list'>
['월', '화', '수', '목']
  • 사용법

https://docs.python.org/3/library/stdtypes.html#list

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

리스트는 공통변할 수 있는 배열 활동들을 모두 시행할 수 있다.

(Lists implement all of the common and mutable sequence operations)

 

1. common sequence

 

https://docs.python.org/3/library/stdtypes.html#typesseq-common

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

 

x = 값

s = sequence

a = ["월", "화", "수", "목"]
print("수" in a)

a = ["월", "화", "수", "목"]
print("금" in a)
-----------------------------
True
False

i = index로 원하는 값을 얻게 해 줌

a = ["월", "화", "수", "목"]
print(a[3])

#index는 0부터 시작, 0부터 카운트
print(a[0])
-------------------------------
목
월

2. mutable sequence

변할 수 있는!

https://docs.python.org/3/library/stdtypes.html#typesseq-mutable

 

Built-in Types — Python 3.9.5 documentation

 

docs.python.org

 

a = ["월", "화", "수", "목"]
print(a)

a.append("금")
print(a)
------------------------------
['월', '화', '수', '목']
['월', '화', '수', '목', '금']

2. tuple

수정 불가능

괄호()로 묶어주고 하나씩 ""(string)을 해준다.

a = ("월", "화", "수", "목")
print(type(a))
print(a)
-----------------------------
<class 'tuple'>
['월', '화', '수', '목']
  • 사용법

https://docs.python.org/3/library/stdtypes.html#tuple

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

튜플은 공통 배열 활동들만 모두 시행할 수 있다.

(Tuples implement all of the common sequence operations.)

 

Dictionary(dicts)

사전이란 뜻처럼 하나로 묶어주는 역할

중괄호{} 사용 /  =(equal) -> :(colon) 사용

하나씩  ""(string)해줄 것

행 넘어갈 때 , (comma)

https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

name = "Dalbong"
age = 1
KoreanShortHair = True
fav_food = ["Boreal", "tiger"]
#매우 안좋은 방식
#왜냐하면 흩어져있는 변수들이기때문
#dictionary로 묶어준다.
dalbong = {
	"name": "Dalbong",
	"age": 1,
   	 "KoreanShortHair": True,
   	 "fav_food": ["Boreal", "tiger"]
	}
print(dalbong)
print(dalbong["name"])

dalbong["handsome"] = True
print(dalbong)
---------------------------------------
{'name': 'Dalbong', 'age': 1, 'KoreanShortHair': True, 'fav_food': ['Boreal', 'tiger']}
Dalbong
{'name': 'Dalbong', 'age': 1, 'KoreanShortHair': True, 'fav_food': ['Boreal', 'tiger'], 'handsome': True}

Functions

어떤 행동을 가지고 있고 계속 반복해서 사용할 수 있는 것.

1. bulit-in functions

기본적으로 사용할 수 있는 함수들.

print(), type() 등

https://docs.python.org/3/library/functions.html

 

Built-in Functions — Python 3.9.5 documentation

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. abs(x) Return the absolute value of a number. The argument may be an integer, a floating poin

docs.python.org

ex)

print(len("abcdefgh"))

age = "28"
print(age)
print(type(age))

n_age = int(age)
print(n_age)
print(type(n_age))
-------------------
8
28
<class 'str'>
28
<class 'int'>

2. creating python Function

파이썬에서는 function을 만든다고 하지 않고 define(정의, def)한다고 한다.

def say_ho():	
	#tap키로 들여쓰기해 function의 안이라는걸 표시
	#python은 들여쓰기로 function의 시작과 끝을 판단.
	print("sayhooo")
	print("hooh")
say_ho()
say_ho()
say_ho()

def say_ho(who):
	print("sayhooo", who)
say_ho("Dalbong")
say_ho(True)

def say_ho(name="jong"):
	print("sayhooo", name)
say_ho()
say-ho("Dalbong")
----------------------
sayhooo
hooh
sayhooo
hooh
sayhooo
hooh

sayhooo Dalbong
sayhooo True

sayhooo jong
sayhoo Dalbong

3. return

결과를 얻고 그 결과를 변수에 저장하길 원할 때

print 대신 return을 사용한다.

 

#return을 해서 function의 밖으로 돌려보낸다.

def p_plus(a, b):
	print(a + b)    
def r_plus(a, b):
	return a + b
    
p_result = p_plus(1, 4)
r_result = r_plus(1, 4)
print(p_result, r_result)

------------------------------
5
(None, 5)

r_plus(1, 4)는 return 1 + 4를 호출하고

그 값(5)은 r_plus(1, 4) 자리에 치환되고 저장된다.

 

이해가 안 된다면 더보기

더보기

return부분을 print로 바꿔서 살펴보면 이해하기 쉽다.


print()는 출력을 해버리고 끝나는 function
p_plus(1, 4)가 p_plus(a, b)에 들어가 print(1 + 4)를 뽑아낸다 (결과값에 5가 나온 부분)
return과 달리 print는 저장되지 않기에 결과가 나오고 없어진다.
p_result = None이 되는 것

def p_plus(a, b):
	print(a + b)
      
def r_plus(a, b):
	print(a + b)
    
p_result = p_plus(1, 4)
r_result = r_plus(1, 4)

print(p_result, r_result)
-------------------------
5
5
None None

#return은 function을 종료한다.

def r_plus(a, b):
	return a + b
	print("asdfasdfgasdf",True)

r_result = r_plus(2, 3)

print(r_result)
-------------------------
5

return밑에 print는 출력되지 않았음

왜냐하면 return 하는 순간 그 function이 종료됨

한 번에 하나의 값만 return 할 수 있다.

 

4. Positional Argument (위치 인자)

위치(순서)에 따라 값이 정해진다.

#1. 연산자를 이용해 알아보자
def plus(a, b):
	print(a + b)
#b=0 이런걸 default value
#자리가 비어있는데 지정해주지 않으면 error
def minus(a,b=0):
	print(a-b)    
#5는 a, 7은b에 대입된다.
plus(5,7)
minus(5)

#2. string을 이용해 알아보자
def say_ho(name, age):
	#string안에 변수를 넣고 싶다면
	#string앞에 f(fomal)를 붙이고 변수를 대괄호{}로 감싼다.
    return f"yoho {name} you are {age} years old"

ho = say_ho("Dalbong", "1")
print(ho)
--------------------------
12
5
yoho Dalbong you are 1 years old

위치에 의존적인 인자

첫 번째 위치(5)가 a, 두 번째 위치(7)가 b에 들어간다.

 

#b=0 이런 걸 default value
자리가 비어있는데 지정해주지 않으면 error

#string안에 변수를 넣고 싶다면
string앞에 f(formal)를 붙이고 변수를 대괄호{}로 감싼다.

5. keywored Argument

argument의 이름으로 짝을 맞춘다.

위치와 상관없이 이름에 따라 결정 

 

순서를 신경 쓸 필요 없다는 장점

argument가 많을수록 위치 인자를 사용하기 힘들다.

그래서 이름 인자가 더 많이 사용됨

 

#1. 연산자를 이용해 알아보자
def minus(a,b):
	print(a-b)    

minus(b=5, a=7)

#2. string을 이용해 알아보자
def say_ho(name, age, are_from, fav_food):
  
    return f"yoho {name} you are {age} years old, you are from {are_from} you like {fav_food}!"

ho = say_ho(are_from = "street", fav_food = "boreal", name = "Dalbong", age = "1")
print(ho)
-----------------------------
2
yoho Dalbong you are 1 years old, you are from street you like boreal!

 

6. if -else, elif

조건문

만약(if) ~라면 something 아니라면(else) something

조건문 추가할 때는 elif를 사용한다.

if = True 면 if 밑 print 출력

if = False -> elif = True 면 elif 밑 print 출력

if = False -> elif = False -> else 밑 print 출력

def age_check(age):
    print(f"you are {age}")
    if age < 18:
        print("you cant drink")
    elif age == 18 or age == 19:
        print("you ate new to this!")
    elif age > 20 and age < 25:
        print("you are still kind of young")
    else:
        print("enjoy your drink")

age_check(23)
age_check(19)
age_check(17)
age_check(30)
-----------------
you are 23
you are still kind of young
you are 19
you ate new to this!
you are 17
you cant drink
you are 30
enjoy your drink

https://docs.python.org/3/library/stdtypes.html#comparisons

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

 

7. for x(변수) in seqence

seqence 배열을 순차적으로 변수에 대입한다.

https://docs.python.org/3/tutorial/controlflow.html#for-statements

 

4. More Control Flow Tools — Python 3.9.5 documentation

 

docs.python.org

 

days = ("Mon", "Tue", "Wed", "Thu", "Fri")

#for x(변수) in Sequence(days):
for potato in days:
    print(potato)
#순차적으로 변수 대입
#print("Mon"), print("Tue") ... print("Fri")

#for loop를 멈춰야한다면
#if문을 사용해서 멈춰준다.
for day in days:
    if day is "Wed":
        break
    else:
        print(day)
----------------------------
Mon
Tue
Wed
Thu
Fri

Mon
Tue

 

Modules

기능의 집합

프로그램에 import해서 사용할 수 있다.

 

편리하게 쓰일 수 있는 수학 기능으로 알아보자.

기본으로 제공되는 module이라 따로 설치할 필요가 없다.

https://docs.python.org/3/library/math.html

 

math — Mathematical functions — Python 3.9.5 documentation

math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for co

docs.python.org

ex)

import시 주의해야할 사항

import math를 하면 math기능들을 다 가져오는데

사용하지 않는 것들도 있어서 비효율적

쓸것만 import하는게 좋다

ex) from math import ceil, fsum

 

import math
print(math.ceil(1.2))
#math를 모두 import하는 건 비효율적

from math import ceil, fsum
print(ceil(1.2))
print(fsum([1, 2, 3, 4, 5]))

#이름을 변경해서 사용할 수 있다.
from math import fsum as good_sum
print(good_sum([1, 2, 3, 4, 5]))
-----------------------------------
2
2
15.0
15.0

 

 

다른 파일에서 정의된 기능을 import해서 사용할 수 있다.

 

#만약 AAA.py 파일을 새로 만들어 다음과 같이 정의한다면
def plus(a, b):
    return a + b
def minus(a, b):
    return a - b

#다른 파일에서 import해 AAA.py에서 정의한 것을 불러올 수 있다.
#불러올 때는 .py를 붙이지 않아도 된다.
from AAA import plus, minus

print(plus(1,2), minus(1,2)) 
------------------------------------
3 -1

Comments