TechTogetWorld

 daviduino.co.kr

techtogetworld.com

 david201207.blog.me

cafe.naver.com/3dpservicedavid

python 문법에 관한 글 입니다.

인공지능 tensor flow 코딩을 위해 python 문법에 대해 정리를 하고자 합니다.

글의 순서는 아래와 같습니다

==========================================

1. cheatsheet

 - python문법의 컨닝 페이퍼입니다.

2. 주제별 코딩예제 모음

3.  참고한 자료

==========================================

[cheatsheet]

cheatsheet.pdf

[주제별 코딩예제 모음]

auth.py

egoing.py

k8805.py

lib.py

python grammar.py

print('---수와 계산------------------------------------------------------------------------')
print(10 + 5)
print(10 - 5)
print(10 * 5)
print(10 / 5)

import math
print(math.ceil(2.2))
print(math.floor(2.7))
print(math.pow(2,10))
print(math.pi)

print('---문자와 데이터 타입----------------------------------------------------------------')
print('Hello')
print("Hello")
print("Hello 'world'")
print('Hello "world"')
print('Hello '+'world')
print('Hello '*3)
print('Hello'[0])
print('Hello'[1])
print('Hello'[2])

print('hello world'.capitalize())
print('hello world'.upper())
print('hello world'.__len__())
print(len('hello world'))
print('Hello world'.replace('world', 'programming'))

print("egoing's \"tutorial\"")
print("\\")
print("Hello\nworld")
print("Hello\t\tworld")
print("\a")
print('Hello\nworld')

print(10+5)
print("10"+"5")

print('---변수---------------------------------------------------------------------------')
x = 10
y = 5
print(x + y)

title = "python & ruby"
print("Title is " + title)

print('---문자열에서 변수의 사용---------------------------------------------------------------------------')
name = "이상효"
print("안녕하세요. "+name+"님")
print(name+"님을 위한 강의를 준비했습니다.")
print(name+"님 꼭 참석 부탁드립니다.")


print('---수계산 에서 변수의 사용---------------------------------------------------------------------------')
donation = 200
student = 10
sponsor = 100
print((donation*student)/sponsor)

print('---비교와 불리언---------------------------------------------------------------------------')
a=1
b=1
print(a==b)
print(1==2)
print(1>2)
print(1<2)
print(True)
print(False)

print('---조건문---------------------------------------------------------------------------')
if True:
print("code1")
print("code2")
print("code3")

print('---조건문의 활용---------------------------------------------------------------------------')
input = 11
real = 11
if real == input:
print("Hello!")

input = 11
real = 21
if real == input:
print("Hello!")
else:
print("Who are you?")

input = 33
real_egoing = 11
real_k8805 = "ab"
if real_egoing == input:
print("Hello!, egoing")
elif real_k8805 == input:
print("Hello!, k8805")
else:
print("Who are you?")

print('---입력과 출력---------------------------------------------------------------------------')
in_str = input("입력 해주세요.\n")
print(in_str.upper()+" World!")

print('---로그인 애플리케이션에 입력기능 추가하기-------------------------------------------------------------------------')
in_str = input("1 아이디를 입력해주세요.\n")
real_egoing = "11"
real_k8805 = "ab"
if real_egoing == in_str:
print("Hello!, egoing")
elif real_k8805 == in_str:
print("Hello!, k8805")
else:
print("Who are you?")

print('---논리 연산---------------------------------------------------------------------------')
in_str = input("2 아이디를 입력해주세요.\n")
real_egoing = "egoing"
real_k8805 = "k8805"
if real_egoing == in_str or real_k8805 == in_str:
print("Hello!")
else:
print("Who are you?")

input_id = input("아이디를 입력해주세요.\n")
input_pwd = input("비밀번호를 입력해주세요.\n")
real_id = "egoing"
real_pwd = "11"
if real_id == input_id:
if real_pwd == input_pwd:
print("Hello!")
else:
print("잘못된 비밀번호입니다")
else:
print("잘못된 아이디입니다")

input_id = input("아이디를 입력해주세요.\n")
input_pwd = input("비밀번호를 입력해주세요.\n")
real_id = "egoing"
real_pwd = "11"
if real_id == input_id and real_pwd == input_pwd:
print("Hello!")
else:
print("로그인에 실패했습니다")

print('---주석---------------------------------------------------------------------------')
'''
조건문 예제
egoing
2015
'''
# user input password
input = 33
real_egoing = 11
#real_k8805 = "ab"
if real_egoing == input:
print("Hello!, egoing")
#elif real_k8805 == input:
# print("Hello!, k8805")
else:
print("Who are you?")

print('---컨테이너---------------------------------------------------------------------------')
print(type('egoing')) # <class 'str'>
name = 'egoing'
print(name) # egoing
print(type(['egoing', 'leezche', 'graphittie'])) # <class 'list'>
names = ['egoing', 'leezche', 'graphittie']
print(names)
print(names[2]) # graphittie
egoing = ['programmer', 'seoul', 25, False]
egoing[1] = 'busan'
print(egoing) # ['programmer', 'busan', 25, False]

print('---사용설명서---------------------------------------------------------------------------')
al = ['A', 'B', 'C', 'D']
print(len(al)) # 4
al.append('E')
print(al) # ['A', 'B', 'C', 'D', 'E']
del (al[0])
print(al) # ['B', 'C', 'D', 'E']

print('---반복문---------------------------------------------------------------------------')
while False:
print('Hello world')
print('After while')

i = 0
while i < 3:
print('Hello world')
i = i + 1

i = 0
while i < 10:
print('print("Hello world ' + str(i * 9) + '")')
i = i + 1

i = 0
while i < 10:
if i == 4:
print(i)
i = i + 1

print('---컨테이너와 반복문-------------------------------------------------------------------------')
members = ['egoing', 'leezche', 'graphittie']
i = 0
while i < len(members):
print(members[i])
i = i + 1
members = ['egoing', 'leezche', 'graphittie']
for member in members:
print(member)
for item in range(5, 11):
print(item)
input_id = input("아이디를 입력해주세요.\n")
members = ['egoing', 'k8805', 'leezche']
for member in members:
if member == input_id:
print('Hello!, ' + member)
import sys
sys.exit()
print('Who are you?')

print('---함수---------------------------------------------------------------------------')
def a3():
print('aaa')
a3()
print('------------------------------------------------------------------------------------------')
def a3():
return 'aaa'
print(a3())
print('------------------------------------------------------------------------------------------')
def a(num):
return 'a' * num
print(a(3))
print('------------------------------------------------------------------------------------------')
input_id = input("아이디를 입력해주세요.\n")
def login(_id):
members = ['egoing', 'k8805', 'leezche']
for member in members:
if member == _id:
return True
return False
if login(input_id):
print('Hello, ' + input_id)
else:
print('Who are you?')
print('---모듈-------------------------------------------------------------------------------')
import math

print(math.ceil(2.9))
print(math.floor(2.9))
print(math.sqrt(16))

print('----모듈이 없을때-----------------------------------------------------------------------------------')
def a():
return 'B'
from egoing import a as z
import k8805 as k

print(z())
print(k.a())

print('---객체제작_객체사용---------------------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())

print('------객체제작_클래스-----------------------------------------------------------------')
class Cal(object):
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())
print('------객체제작_생성자-----------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
print(v1, v2)
c1 = Cal(10, 10)
# print(c1.add())
# print(c1.subtract())
c2 = Cal(30, 20)
# print(c2.add())
# print(c2.subtract())
print('------객체제작_인스턴스 변수와 메소드-----------------------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c2 = Cal(30, 20)
print(c2.add())
print(c2.subtract())
print('------객체와변수_인스턴스 변수의 특성-----------------------------------------------------------------')
class C(object):
def __init__(self, v):
self.value = v

def show(self):
print(self.value)
c1 = C(10)
print(c1.value)
c1.value = 20
print(c1.value)
c1.show()
print('------객체와변수_set/get 메소드--------------------------------------------------------------')
class C(object):
def __init__(self, v):
self.value = v

def show(self):
print(self.value)

def getValue(self):
return self.value

def setValue(self, v):
self.value = v
c1 = C(10)
print(c1.getValue())
c1.setValue(20)
print(c1.getValue())
print('------객체와변수_set/get 메소드를 사용해야하는 이유--------------------------------------------------')
class Cal(object):
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2

def setV1(self, v):
if isinstance(v, int): # v 가 int class의 인스턴스인지 확인
self.v1 = v

def getV1(self):
return self.v1
c1 = Cal(10, 10)
print(c1.add())
print(c1.subtract())
c1.setV1('one')
c1.v2 = 30
print(c1.add())
print(c1.subtract())

print('---------객체와변수_속성 : 실행않됨---------------------------------------------------------------------')
"""
class C(object):
def __init__(self, v):
self.__value = v
def show(self):
print(self.__value)
c1 = C(10)
print(c1.__value)
c1.show()

"""
print('---상속_상속의 문법---------------------------------------------------------------------------')
class Class1(object):
def method1(self): return 'm1'
c1 = Class1()
print(c1, c1.method1())
class Class3(Class1):
def method2(self): return 'm2'
c3 = Class3()
print(c3, c3.method1())
print(c3, c3.method2())

class Class2(object):
def method1(self): return 'm1'
def method2(self): return 'm2'
c2 = Class2()
print(c2, c2.method1())
print(c2, c2.method2())

print('-----상속_상속의 응용-------------------------------------------------------------------')
"""
클래스의 재활용/함수추가 : 타인의 또는 자신의 클래스를 상속하고, 새로운 기능추가, 상속은 변수까지도 이어받음
"""
class Cal(object):
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1


class CalMultiply(Cal):
def multiply(self):
return self.v1 * self.v2


class CalDivide(CalMultiply):
def divide(self):
return self.v1 / self.v2


c1 = CalMultiply(10, 10)
print(c1.add())
print(c1.multiply())
c2 = CalDivide(20, 10)
print(c2, c2.add())
print(c2, c2.multiply())
print(c2, c2.divide())

print('-------------clss멤버_클래스 매소드--------------------------------------------------------------')
class Cs:
@staticmethod
def static_method():
print("Static method")

@classmethod
def class_method(cls):
print("Class method")

def instance_method(self):
print("Instance method")

i = Cs()
Cs.static_method()
Cs.class_method()
i.instance_method()

print('-------------clss멤버_클래스 변수---------------------------------------------------------------')
class Cs:
count = 0

def __init__(self):
Cs.count = Cs.count + 1

@classmethod
def getCount(cls):
return Cs.count
i1 = Cs()
i2 = Cs()
i3 = Cs()
i4 = Cs()
print(Cs.getCount())

print('-------------clss멤버_clss member의 활용---------------------------------------------------------------')
class Cal(object):
_history = []

def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
result = self.v1 + self.v2
Cal._history.append("add : %d+%d=%d" % (self.v1, self.v2, result))
return result

def subtract(self):
result = self.v1 - self.v2
Cal._history.append("subtract : %d-%d=%d" % (self.v1, self.v2, result))
return result

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1

@classmethod
def history(cls):
for item in Cal._history:
print(item)
class CalMultiply(Cal):
def multiply(self):
result = self.v1 * self.v2
Cal._history.append("multiply : %d*%d=%d" % (self.v1, self.v2, result))
return result
class CalDivide(CalMultiply):
def divide(self):
result = self.v1 / self.v2
Cal._history.append("divide : %d/%d=%d" % (self.v1, self.v2, result))
return result
c1 = CalMultiply(10, 10)
print(c1.add())
print(c1.multiply())
c2 = CalDivide(20, 10)
print(c2, c2.add())
print(c2, c2.multiply())
print(c2, c2.divide())
Cal.history()
print('-------------override_형식---------------------------------------------------------------')
class C1:
def m(self):
return 'parent'
class C2(C1):
def m(self):
return super().m() + ' child'
pass
o = C2()
print(o.m())

print('-------------override_override 활용---------------------------------------------------------------')
class Cal(object):
_history = []

def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2

def add(self):
result = self.v1 + self.v2
Cal._history.append("add : %d+%d=%d" % (self.v1, self.v2, result))
return result

def subtract(self):
result = self.v1 - self.v2
Cal._history.append("subtract : %d-%d=%d" % (self.v1, self.v2, result))
return result

def setV1(self, v):
if isinstance(v, int):
self.v1 = v

def getV1(self):
return self.v1

@classmethod
def history(cls):
for item in Cal._history:
print(item)

def info(self):
return "Cal => v1 : %d, v2 : %d" % (self.v1, self.v2)
class CalMultiply(Cal):
def multiply(self):
result = self.v1 * self.v2
Cal._history.append("multiply : %d*%d=%d" % (self.v1, self.v2, result))
return result

def info(self):
return "CalMultiply => %s" % super().info()
class CalDivide(CalMultiply):
def divide(self):
result = self.v1 / self.v2
Cal._history.append("divide : %d/%d=%d" % (self.v1, self.v2, result))
return result

def info(self):
return "CalDivide => %s" % super().info()
c0 = Cal(30, 60)
print(c0.info())
c1 = CalMultiply(10, 10)
print(c1.info())
c2 = CalDivide(20, 10)
print(c2.info())

print('-------------객체와 모듈---------------------------------------------------------------')
import lib
obj = lib.A()
print(obj.a())

print('-------------다중상속_형식,단점---------------------------------------------------------------')
class C1():
def c1_m(self):
print("c1_m")

def m(self):
print("C1 m")
class C2():
def c2_m(self):
print("c2_m")
def m(self):
print("C2 m")

class C3(C2, C1):
def m(self):
print("C3 m")
c = C3()
c.c1_m()
c.c2_m()
c.m()
print(C3.__mro__)

print('-------------다중상속_다중상속의 활용---------------------------------------------------------------')
class CalMultiply():
def multiply(self):
return self.v1 * self.v2
class CalDivide():
def divide(self):
return self.v1 / self.v2
class Cal(CalMultiply, CalDivide): # 왼쪽부모가 우선순위가 높다
def __init__(self, v1, v2):
if isinstance(v1, int):
self.v1 = v1
if isinstance(v2, int):
self.v2 = v2
def add(self):
return self.v1 + self.v2

def subtract(self):
return self.v1 - self.v2
def setV1(self, v):
if isinstance(v, int):
self.v1 = v
def getV1(self):
return self.v1
c = Cal(100, 10)
print(c.add())
print(c.multiply())

print(c.divide())



[참고한 자료]


https://opentutorials.org/course/1750    생활코딩