OneBook(Python & Deep Learning)
  • 한곳에서 끝내는 파이썬 & 머신러닝 & 딥러닝
  • 문서 작업을 시작하며
  • 1. 인공지능(Artificial Intelligence) 시대
    • 1.1. 인공지능이란 도대체 무엇인가?
    • 1.2. 4차 산업혁명
    • 1.3. 인공지능의 역사
    • 1.4. 인공지능 > 머신러닝 > 딥러닝
    • 1.5. 머신러닝
    • 1.6. 머신러닝 알고리즘
      • 1.6.1. 지도 학습 (Supervised Learning)
      • 1.6.2. 비지도 학습 (Unsupervised learning)
      • 1.6.3. 강화 학습(Reinforcement Learning)
    • 1.7. 인공신경망(ANN)
    • 1.8. 딥러닝
  • 2. 기본 상식
    • 2.1. 기본 용어의 이해
      • 2.1.1. CPU와 GPU의 차이
      • 2.1.2. 오픈소스(Open Source)
      • 2.1.3. 깃허브(GitHub)
      • 2.1.4. 위키 Wiki
      • 2.1.5. 아나콘다(Anaconda)
      • 2.1.6. 활성화 함수
      • 2.1.5. 딥러닝 프레임워크 소개
    • 2.2. 텐서플로(Tensorflow)
    • 2.3. 케라스(Keras)
    • 2.4. 파이토치(PyTorch)
    • 2.5. 학습에 필요한 중요한 도구와 라이브러리들
      • 2.5.1. 주피터 노트북(Jupyter Notebook)
      • 2.5.2. 파이참(PyCharm)
      • 2.5.3. 스파이더(Spyder)
      • 2.5.4. 넘파이(NumPy)
      • 2.5.5. 싸이파이(SciPy)
      • 2.5.6. Matplotlib
      • 2.5.7. 판다스(Pandas)
      • 2.5.8. 장고(Django)
      • 2.5.9. 파이큐티(pyQT)
      • 2.5.10. 싸이킷런(Scikit-learn)(Sklearn)
      • 2.5.11. CUDA & cuDNN
      • 2.5.12. 파이썬 표준 내장 라이브러리
    • 2.6. AI공부에 필요한 기본지식 3가지
      • 2.6.1. 수학
      • 2.6.2. 프로그래밍 기술
      • 2.6.3. AI의 적용 대상 산업에 대한 지식
  • 3. 개발 환경설정
    • 3.1. 윈도우 환경에서 설치하기
      • 3.1.1. 아나콘다 설치 (파이썬 설치)
        • 1) 아나콘다 패키지 업데이트
        • 2) conda에서 파이썬 가상 환경 (virtual environments) 생성하기
        • 3) NVIDIA GPU 환경 설정하기
      • 3.1.2. 텐서플로 설치
      • 3.1.3. 케라스 설치
      • 3.1.4. Jupyter Notebook 설치
      • 3.1.5. Visual Studio Code 설치
      • 3.1.6. 파이참 설치
        • 1) 파이참 가상환경 설정
        • 2) 파이참 환경 설정
        • 3) 설치된 라이브러리들의 버전 확인 하기
    • 3.2. 리눅스 환경에서 설치하기
      • 3.2.1. 아나콘다 설치(파이썬 설치)
      • 3.2.2. 텐서플로 설치
      • 3.2.3. 케라스 설치
      • 3.2.4. 장고 설치
      • 3.2.5. 파이참(PyCharm) 설치
        • 1) 파이참 가상환경 설정
  • 4. 파이썬 기초 학습
    • 4.1. 파이썬(Python)
    • 4.2. 파이썬의 특징
    • 4.3. 파이썬 기본 문법
      • 4.3.1. 대화형과 스크립트 모드 프로그래밍
      • 4.3.2. 모듈의 사용(import)
      • 4.3.3. 파이썬 식별자(Identifiers)
      • 4.3.4. 예약어(Reserved Words)
      • 4.3.5. 행(Lines)과 들여쓰기(Indentation)
      • 4.3.6. 문자열 표시
      • 4.3.7. 주석
      • 4.3.8. 파이썬 변수(Variables)
    • 4.4. 자료형과 연산자
      • 4.4.1. 자료형
      • 4.4.2. 파이썬 연산자
    • 4.5. 조건문과 반복문
      • 4.5.1. 조건문
      • 4.5.2. 반복문
    • 4.6. 함수
      • 4.6.1. 함수의 종류
    • 4.7. 모듈(Modules)
      • 4.7.1. 모듈의 참조 위치
      • 4.7.2. 네임스페이스(Namespace)와 범위(Scoping)
      • 4.7.3. dir( ) 함수
      • 4.7.4. 패키지(Packages)
      • 4.7.5. 기본 내장 모듈
    • 4.8. 숫자형 활용
      • 4.8.1. 실습: 계산기 만들기
    • 4.9. 문자열(Strings) 활용
      • 4.9.1. Unicode 한글의 사용
      • 4.9.2. 이스케이프 문자
      • 4.9.3. 문자열 연산자
      • 4.9.4. 문자열 포맷 연산자
      • 4.9.5. 내장 문자열 함수
    • 4.10. 시퀀스(Sequence) 자료형 활용
      • 4.10.1. 리스트(Lists)
      • 4.10.2. 튜플(Tuple)
      • 4.10.3. 딕셔너리(Dictionary)
    • 4.11 Class
    • 4.12. Date & Time
    • 4.13. 파이썬 에러처리
  • 5. 기초수학
  • 6. 머신러닝을 위한 파이썬
  • 7. 텐서플로 2.x
  • 8. 딥러닝을 이용한 자연어 처리 입문
  • 9. 파이토치로 시작하는 딥 러닝 입문
  • 9.6 6. Pytorch lightning
  • A1. 필수 학습 라이브러리들
    • 4.1 NumPy
      • 4.1.1. Basic Operations
      • 4.1.2. Indexing, Slicing 그리고 Iterating
      • 3.13.3. Shape Manipulation
    • 4.2 Matplotlib
    • 4.3 SciPy
      • 4.3.1. Interpolation
      • 4.3.2. Optimization
      • 4.3.3. Fast Fourier transforms: scipy.fftpack
    • 4.4 Pandas
      • 4.4.1 Pandas 자료구조
      • 4.4.2 Pandas 활용하기
  • A2. 머신러닝 & 딥러닝
    • 5.1. 머신러닝 개념 소개
      • 5.1.1. 경사하강법(Gradient Descent )
      • 5.1.2. 분류 (Classification)
      • 5.1.3. MNIST Dataset 소개
    • 5.2. 딥러닝 개념 소개
      • 5.2.1. 퍼셉트론
      • 5.2.2. 인공 신경망
      • 5.2.3. 대표적인 딥러닝 모델
    • 5.3. Tensorflow를 사용한 학습
      • 5.3.1. TensorFlow 기본 메커니즘
      • 5.3.2. Tensorflow Types
      • 5.3.3. 기본 동작 실습
      • 5.3.4. 선형 회귀
      • 5.3.5 로지스틱 회귀
    • 5.4. Keras를 사용한 학습
      • 5.4.1. Keras로 분석한 선형 회귀
      • 5.4.2. CNN(Convolutional Neural Network)
      • 5.4.3. Fashion MNIST with Keras
    • 5.5. 웹 크롤링
      • 5.5.1. requests와 BeautifulSoup으로 웹 크롤러 만들기
Powered by GitBook
On this page

Was this helpful?

  1. 4. 파이썬 기초 학습
  2. 4.8. 숫자형 활용

4.8.1. 실습: 계산기 만들기

1) 간단한 사칙 연산 계산기

def add(x, y):
    return x + y

 def subtract(x, y):
    return x - y

 def multiply(x, y):
    return x * y

 def divide(x, y):
    return x / y

 print("사칙연산을 선택 하세요.")
 print("1.더하기")
 print("2.빼기")
 print("3.곱하기")
 print("4.나누기")

 choice = input("선택 하세요(1/2/3/4):")

 num1 = int(input("첫번째 숫자 : "))
 num2 = int(input("두번째 숫자 : "))

 if choice == '1':
    print(num1,"+",num2,"=", add(num1,num2))

 elif choice == '2':
    print(num1,"-",num2,"=", subtract(num1,num2))

 elif choice == '3':
    print(num1,"*",num2,"=", multiply(num1,num2))

 elif choice == '4':
    print(num1,"/",num2,"=", divide(num1,num2))
 else:
    print("잘못된 선택")

2) Tkinter를 사용한 GUI 계산기

tkinter는 GUI에 대한 표준 Python 인터페이스이며 Window 창을 생성할 수 있습니다. 이번 예제는 tkinter를 사용하여 GUI 계산기를 만들어 보겠습니다.

 import tkinter as tkt

 root = tkt.Tk()
 root.title("계산기")
 root.resizable(0, 0)                                # 윈도우 크기 고정한다
 root.wm_attributes("-topmost", 1)                   # 화면 상단에 유지된다.

 # 변수 선언
 equa = ""
 equation = tkt.StringVar()

 calculation = tkt.Label(root, textvariable=equation)
 equation.set("계산식을 입력하세요 : ")
 calculation.grid(row=2, columnspan=8)


 def btnPress(num):
     global equa
     equa = equa + str(num)
     equation.set(equa)

 def EqualPress():
     global equa
     total = str(eval(equa))
     equation.set(total)
     equa = ""

 def ClearPress():
     global equa
     equa = ""
     equation.set("")

 Button0 = tkt.Button(root, text="0", bg='white',command=lambda: btnPress(0), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button0.grid(row=6, column=2, padx=10, pady=10)
 Button1 = tkt.Button(root, text="1", bg='white',command=lambda: btnPress(1), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button1.grid(row=3, column=1, padx=10, pady=10)
 Button2 = tkt.Button(root, text="2", bg='white',command=lambda: btnPress(2), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button2.grid(row=3, column=2, padx=10, pady=10)
 Button3 = tkt.Button(root, text="3", bg='white',command=lambda: btnPress(3), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button3.grid(row=3, column=3, padx=10, pady=10)
 Button4 = tkt.Button(root, text="4", bg='white',command=lambda: btnPress(4), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button4.grid(row=4, column=1, padx=10, pady=10)
 Button5 = tkt.Button(root, text="5", bg='white',command=lambda: btnPress(5), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button5.grid(row=4, column=2, padx=10, pady=10)
 Button6 = tkt.Button(root, text="6", bg='white',command=lambda: btnPress(6), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button6.grid(row=4, column=3, padx=10, pady=10)
 Button7 = tkt.Button(root, text="7", bg='white',command=lambda: btnPress(7), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button7.grid(row=5, column=1, padx=10, pady=10)
 Button8 = tkt.Button(root, text="8", bg='white',command=lambda: btnPress(8), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button8.grid(row=5, column=2, padx=10, pady=10)
 Button9 = tkt.Button(root, text="9", bg='white',command=lambda: btnPress(9), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button9.grid(row=5, column=3, padx=10, pady=10)
 Plus = tkt.Button(root, text="+", bg='white',command=lambda: btnPress("+"), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Plus.grid(row=3, column=4, padx=10, pady=10)
 Minus = tkt.Button(root, text="-", bg='white',command=lambda: btnPress("-"), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Minus.grid(row=4, column=4, padx=10, pady=10)
 Multiply = tkt.Button(root, text="*", bg='white',command=lambda: btnPress("*"), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Multiply.grid(row=5, column=4, padx=10, pady=10)
 Divide = tkt.Button(root, text="/", bg='white',command=lambda: btnPress("/"), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Divide.grid(row=6, column=4, padx=10, pady=10)
 Equal = tkt.Button(root, text="=", bg='white',command=EqualPress, height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Equal.grid(row=6, column=3, padx=10, pady=10)
 Clear = tkt.Button(root, text="C", bg='white',command=ClearPress, height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Clear.grid(row=6, column=1, padx=10, pady=10)

 root.mainloop()

1번행에서 상단에 import tkinter as tkt를 사용하여 GUI 모듈을 포함시킵니다.

3번행 root = tkt.Tk()는 가장 기본적인 윈도우 창 root 가 생성됩니다.

4번행 윈도우이름.title("제목")을 이용하여 윈도우 창의 제목을 설정할 수 있습니다. root.title("계산기") 코드는 root 라는 윈도우의 제목이 “계산기”라고 지정하는 것입니다.

윈도우이름.geometry("너비x높이+x좌표+y좌표")를 이용하여 윈도우 창의 너비와 높이, 초기 화면 위치의 x좌표와 y좌표를 설정할 수 있습니다.

5번행 윈도우이름.resizeable(상하, 좌우)을 이용하여 윈도우 창의 창 크기 조절 가능 여부를 설정할 수 있습니다. True로 설정할 경우 윈도우 창의 크기를 조절할 수 있습니다. (0,0) 이라면 고정됩니다.

6번행에서 wm_attributes 로 윈도우의 속성을 지정할 수 있습니다.

tkinter 모듈 안에는 IntVar, DoubleVar, StringVar 클래스가 정의되어 있습니다. 이 클래스들은 사용되는 값들을 객제로 만들 때 이용합니다.

14번행 .grid(row, col)은 객체의 배치를 담당합니다.

tkinter.Button(윈도우 창, 파라미터1, 파라미터2, 파라미터3, ...)을 사용하여 해당 윈도우 창에 표시할 버튼의 속성을 설정할 수 있습니다. 파라미터를 사용하여 버튼의 속성을 설정합니다.

파라미터 중 command를 이용하여 사용자 정의 함수를 실행시킬 수 있습니다.

Button1 = tkt.Button(root, text="1", bg='white', command=lambda: btnPress(1), height=1, width=7, borderwidth=1, relief=tkt.SOLID)
 Button1.grid(row=3, column=1, padx=10, pady=10)

위의 함수는 Button1 이라는 객체를 tkinter.Button 을 이용해서 만드는데

Root 윈도우에 만들며, 버튼의 텍스트는 “1”, 배경색은 ‘white’, 버튼을 눌렀을 때 실행되는 명령은 btnPress(1), 높이는 1, 넓이는 7, 테두리 두께는 1, 3D 스타일은 그냥 SOLID로 만들고 3행, 1열, xy채우기는 10의 위치에 배치 하라는 명령입니다.

66번행 mainloop()는 이벤트 메시지 루프로서 키보드나 마우스 혹은 화면 Redraw와 같은 다양한 이벤트로부터 오는 메시지를 받고 전달하는 역할을 합니다.

Previous4.8. 숫자형 활용Next4.9. 문자열(Strings) 활용

Last updated 6 years ago

Was this helpful?