Gmail의 경우 보안서비스를 해제해야 가능


import smtplib from email.mime.text import MIMEText senderAddr = "보내는메일" recipientAddr = "받는메일" text = "본문 test 파이썬" msg = MIMEText(text,_charset="utf8") msg['Subject'] = "smtp 테스트 Hello!" msg['From'] = senderAddr msg['to'] = recipientAddr s=smtplib.SMTP_SSL('smtp.gmail.com',465) s.login("보내는 메일주소","비밀번호") s.sendmail(senderAddr,recipientAddr,msg.as_string()) print("메일보내기 성공") s.quit()


'먼지 낀 책장사이 > Python' 카테고리의 다른 글

테이블 제작, 데이터입력  (0) 2016.11.08
SQLite  (0) 2016.10.18
쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20

py파일(파이썬)을 splite3와 같은 경로에 저장

#create_table.py

import sqlite3
#데이터베이스 만들기
con = sqlite3.connect('testDB')
cur = con.cursor()

#테이블 만들기
cur.execute("""
create table phonebook_0
(name char(32), phone char(32), email char(64)primary key)
""")

#테이블을 닫고 데이터베이스를 종료한다.
cur.close()
con.close()


#delete_record.py

import sqlite3
#데이터베이스 만들기
con = sqlite3.connect('testDB')
cur = con.cursor()

#데이터입력
cur.execute("""
delete from phonebook_0 where email=?
""",('kim@hanmail.net',))

con.commit()

cur.execute("select name, phone, email from phonebook_0 ")

rows = cur.fetchall()
for row in rows:
    print ("name : {0},phone : {1},email : {2}".format(row[0],row[1],row[2]))

cur.close()
con.close()


#inserte_record.py

import sqlite3
#데이터베이스 만들기
con = sqlite3.connect('testDB')
cur = con.cursor()

#데이터입력
cur.execute("""
insert into phonebook_0 (name, phone, email)
values(?,?,?)
""",('김동','030-124-4567','kon@naver.com'))

#id값 출력
id= cur.lastrowid
print(id)

#데이터입력
cur.execute("""
insert into phonebook_0 (name, phone, email)
values(?,?,?)
""",('김차동','010-154-4567','young@naver.com'))

#id값 출력
id= cur.lastrowid
print(id)

#데이터를 저장하고 종료한다.
con.commit()
cur.close()
con.close()


#select_record.py

import sqlite3
#데이터베이스 만들기
con = sqlite3.connect('testDB')
cur = con.cursor()

#데이터입력
cur.execute("select name, phone, email from PHONEBOOK_0")

rows = cur.fetchall()
for row in rows:
    print("name: {0},phone:{1},email:{2}".format(row[0],row[1],row[2]))

#종료한다.
cur.close()
con.close()


#update_record.py

import sqlite3
#데이터베이스 만들기
con = sqlite3.connect('testDB')
cur = con.cursor()

#데이터입력
cur.execute("""
update phonebook_0 set phone=?,email=? where name=?
""",('010-0000-0000','kim@hanmail.net','홍길동'))

con.commit()

cur.execute("""
select name, phone, email from phonebook_0 where name=?
""",('홍길동',))

rows = cur.fetchall()
for row in rows:
    print ("name : {0},phone : {1},email : {2}",fowmat(row[0],row[1],row[2]))

cur.close()
con.close()


'먼지 낀 책장사이 > Python' 카테고리의 다른 글

파이썬으로 메일보내기 SMTP  (0) 2016.11.08
SQLite  (0) 2016.10.18
쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20

쓰레드 하나의 프로그램 내에서 여러개의 실행흐름을 두기위한 모델로

각 독립적인 일의 단위



레포트

1.파이참 설치(Community)

2.이클립스를 이용한 파이썬 개발환경 구축

3.비주얼스튜디오는 제외

레포트.hwp

레포트.pdf



SQL(Structured Query Language 구조화된 )

DBMS가 대략적으로 하는 일

데이터베이스생성

테이블 생성


https://sqlite.org/download.html


SQL라이트 실행

데이터베이스생성

sqllite> .open Swa_DB

*대소문자 구분안함

명령어

.table : 현재 데이터베이스의 테이블 목록을 보여줌

.schema 테이블 이름 : 테이블의 열 및 데이터 형식등의 정보를 보여줌

.header on : SELECT문으로 출력할 때 헤더를 보여줌

.mode coloum : SELECT문으로 출력할 컬럼 모드로 해줌

.exit

테이블 생성 CREATE TABLE 테이블 이름(열이름1 데이터 형식, 열이름2 데이터형식...)

예1) CREATE TABLE Swa_Python(id char(4),username char(15),email char(15),birthYear int);

.table

.schema Swa_python

예2) create table Swa_python2(

id integer primary key autoincrement,

name text,

age integer);

.table

입력) insert into Swa_python2(name,age) values("김명준",25);

insert into Swa_python2(name,age) values("유현종",23);

insert into Swa_python2(name,age) values("김수환",24);

select * from Swa_python2;

SQLite 명령어 13개정도?


이름 전화번호 이메일

create table Swa_python3(

name text,

number text,

email text);

insert into Swa_python3(name,number,email) values("김수환","010-4567-9876","kkk1234@never.com");

select * from Swa_python3;


SELECT * FROM Table_name ORDER BY NAME ASC;

*Ascend : 오름차순 = ASC

*Descend : 내림차순 = DSC








상속(Inheritance) : 기존의 클래스가 가지고 있는 필드와 메소드를 그대로 물려받은 새로운 클래스를 만드는 것 






import sqlite3



#변수 선언 부분

con, cur = None, None

data1, data2, data3, data4 = "", "", "", ""

sql=""



#메인 코드 부분

con = sqlite3.connect("swaDB")

cur = con.cursor()



while(True) :

    data1 = input("사용자 ID ==> ")

    if data1 == "" :

        break;

    data2 = input("사용자 이름 ==> ")

    data3 = input("사용자 이메일 ==> ")

    data4 = input("사용자 출생년도 ==> ")

    sql = "INSERT INTO userTable VALUES('"+data1+"','"+data2+"','"+data3+"',"+ data4 + ")"

    cur.execute(sql)



con.commit()

con.close()


'먼지 낀 책장사이 > Python' 카테고리의 다른 글

파이썬으로 메일보내기 SMTP  (0) 2016.11.08
테이블 제작, 데이터입력  (0) 2016.11.08
쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20

a=(1+2j)-(3+4j)

a

(-2-2j)



import math

math.pi

3.14...


math.e

2.718...




abs(10)

10


round(1.4)

1

round(1.5)

2


math.factorial(3)

6

math.factorial(100)

100


math.degrees(math.pi)

180.0


math.sin(math radians(90))


try:                      #문제가 없을 경우에 실행할 코드

exept 예외형식1:    #문제가 생겼을때 실행할 코드

exept 예외형식2:    #문제가 생겼을때 실행할 코드

finally:                  #어떠한 일이 있더라도 실행된다.



import datetime

print(datetime.datetime.now())

2016-10-11 10:19:08.543717


import datetime

now = datetime.datetime.now()

print("%s년%s월%s일,%s시%s분%s초"%(now.year,now.month,now.day,now.hour,now.minute,now.second))



from datetime import datetime
now = datetime.now()
print("%s년%s월%s일,%s시%s분%s초"%(now.year,now.month,now.day,now.hour,now.minute,now.second())


#net_1_1

import socket

host_name = socket.gethostname()

IP_address = socket.gethostbyname(host_name)

print("host_name : %s,IP_address : %s"%(host_name,IP_address))



#net_1_2
import socket
remote_host = "www.google.co.kr"
print("IP address of %s : %s"%(remote_host,socket.gethostbyname(remote_host)))

#net_1_4

import socket

# protocol_name = 'tcp','udp'

# port_number = 25, 53, 80

print("port : 25 ---> service name : %s"%socket.getservbyport(25,'tcp'))

print("port : 53 ---> service name : %s"%socket.getservbyport(53,'tcp'))

print("port : 80 ---> service name : %s"%socket.getservbyport(80,'tcp'))


#threading

import threading

count = 0

def on_timer():

    global count

    count += 1

    print(count)

    timer = threading.Timer(1,on_timer)

    timer.start()

    if count == 100:

        print("cancling timer ...")

        timer.cancel()

print("Starting timer...")

on_timer()



상속(Inheritance) : 기존의 클래스가 가지고 있는 필드와 메소드를 그대로 물려받은 새로운 클래스를 만드는 것 

#threading

import threading

from datetime import datetime

def on_timer():

    now = datetime.now()

    print("%s년%s월%s일,%s시%s분%s초"%(now.year,now.month,now.day,now.hour,now.minute,now.second))

    timer = threading.Timer(1,on_timer)

    timer.start()

    key = int(now.minute)

    if key == 0:

        print("cancling timer ...")

        timer.cancel()

print("Starting timer...")

on_timer()




'먼지 낀 책장사이 > Python' 카테고리의 다른 글

테이블 제작, 데이터입력  (0) 2016.11.08
SQLite  (0) 2016.10.18
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20
문자열, 구구단, 그림그리기  (0) 2016.09.13

상속(Inheritance) : 기존의 클래스가 가지고 있는 필드와 메소드를 그대로 물려받은 새로운 클래스를 만드는 것 

## 클래스 선언
class Car :
    speed = 0

    def upSpeed(self, value) :
        self.speed = self.speed + value
        
    def downSpeed(self, value) :
        self.speed = self.speed - value

class Sedan(Car) :
    seatNum = 0

    def getSeatNum(self) :
        return self.seatNum

class Truck(Car) :
    capacity = 0
    
    def getCapacity(self) :
        return self.capacity

# 변수 선언
sedan1, truck1 = None, None

# 메인 코드 부분
sedan1 = Sedan()
truck1 = Truck()

sedan1.upSpeed(100)
truck1.upSpeed(80)

sedan1.seatNum=5
truck1.capacity=50

print("승용차의 속도는 %d km, 좌석수는 %d개입니다." % (sedan1.speed, sedan1.getSeatNum() ))
print("트럭의 속도는 %d km, 총중량은 %d개입니다." % (truck1.speed, truck1.getCapacity() ))


승용차의 속도는 100 km, 좌석수는 5개입니다.
트럭의 속도는 80 km, 총중량은 50개입니다.





오버라이딩(Overriding) : 상위 클래스 하위클래스에서 재정의


## 클래스 선언
class Car :
    speed = 0
    def upSpeed(self, value) :
        self.speed += value

        print("현재 속도(슈퍼 클래스) : %d km" % self.speed)
        
class Sedan(Car) :
    def upSpeed(self, value) :
        self.speed += value

        if self.speed > 150 :
            self.speed = 150

        print("현재 속도(서브 클래스) : %d km" % self.speed)

class Truck(Car) :
    pass

# 변수 선언
sedan1, truck1 = None, None

# 메인 코드 부분
truck1 = Truck()
sedan1 = Sedan()

print("트럭 --> ", end="")
truck1.upSpeed(200)

print("승용차 --> ", end="")
sedan1.upSpeed(200)


트럭 --> 현재 속도(슈퍼 클래스) : 200 km

승용차 --> 현재 속도(서브 클래스) : 150 km





from tkinter import *

window = Tk()
window.title("윈도창 연습")
# 이 부분에서 화면을 구성하고 처리
window.geometry("400x100")
window.resizable(width=FALSE, height=FALSE)

window.mainloop()



from tkinter import *

window = Tk()

# 함수 정의 부분
def myFunc() :
    if chk.get() == 0 :
        messagebox.showinfo("","체크버튼이 꺼졌어요.")
    else :
        messagebox.showinfo("","체크버튼이 켜졌어요.")

# 메인 코드 부분
chk = IntVar()
cb1 = Checkbutton(window, text="클릭하세요", variable=chk, command=myFunc)

cb1.pack()

window.mainloop()


'먼지 낀 책장사이 > Python' 카테고리의 다른 글

SQLite  (0) 2016.10.18
쓰레드  (0) 2016.10.11
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20
문자열, 구구단, 그림그리기  (0) 2016.09.13
가변 매개변수, 모듈  (0) 2016.09.06

Citrus.raw


from tkinter import *
## 변수 ##
window = None
canvas = None
XSIZE, YSIZE = 256, 256
## 메인코드 ##

window=Tk()
window.title("흑백 사진 보기")
canvas = Canvas(window, height=XSIZE, width=YSIZE)

paper=PhotoImage(width=XSIZE, height=YSIZE)
canvas.create_image((XSIZE/2,YSIZE/2), image=paper,state="normal")

#이부분에서 읽어올 파일 경로
fp=open('E:\swa\Citrus.raw','rb')       ## fp? =파일포지션

for i in range(0, XSIZE) :
    for k in range(0,YSIZE)  :
        data = int(ord(fp.read(1)))
        paper.put("#%02x%02x%02x" % (data,data,data) , (k, i))

fp.close()
canvas.pack()
window.mainloop()









class : 현실의 사물을 컴퓨터 안에서 구현하기 위하여 고안된 개념(설계도)

함수까지 포함

instance : 설계도에 의해 만들어진 실체

structure : 변수를 정의(형이 다른 데이터 집합)

array : 동질적인 데이터의 집합

클래스 안에 구현한 함수 메소드(methode)


#클래스 예제
#source_code11-2
#클래스 정의 부분
class Car :
    color = ""
    speed = 0

    def upSpeed(self, value) :  
        self.speed += value
        ##(A,) 괄호 앞부분이 자기자신에게 접근. 이때 정의한 대로 다음줄에서 A.speed로
    def downSpeed(self, value) :
        self.speed -= value

# 메인 코드 부분
myCar1 = Car()
myCar1.color = "빨간색"
myCar1.speed = 0

myCar2 = Car()
myCar2.color = "파란색"
myCar2.speed = 0

myCar3 = Car()
myCar3.color = "노란색"
myCar3.speed = 0

myCar1.upSpeed(30)
print("자동차1의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar1.color, myCar1.speed))
myCar2.upSpeed(60)
print("자동차2의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar2.color, myCar2.speed))
myCar3.upSpeed(0)
print("자동차3의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar3.color, myCar3.speed))

자동차1의 색상은 빨간색이며, 현재속도는 30 km 입니다.

자동차2의 색상은 파란색이며, 현재속도는 60 km 입니다.

자동차3의 색상은 노란색이며, 현재속도는 0 km 입니다.








#클래스 입력
#source_code11-2
#클래스 정의 부분
class Car :
    color = ""
    speed = 0

    def upSpeed(self, value) : 
        self.speed += value
        ##(A,) 앞부분이 자기자신에게 접근. 이때 정의한 대로 다음줄에서 A.speed로
    def downSpeed(self, value) :
        self.speed -= value

# 메인 코드 부분
myCar1 = Car()
myCar2 = Car()
myCar3 = Car()

while True:
    myCar1.color = input("자동차 1의 색상 입력 : ")
    myCar1.speed = int(input("자동차 1의 가속도 입력(km) : "))
    Continue = str(input("다음 차량으로 넘어가시겠습니까?(y/n) : "))
    if Continue == "y":
                  break
    if Continue == "n":
                  print("다시 입력")
                  continue
print("자동차1의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar1.color, myCar1.speed))

while True:
    myCar2.color = input("자동차 2의 색상 입력 : ")
    myCar2.speed = int(input("자동차 2의 가속도 입력(km) : "))
    Continue = str(input("다음 차량으로 넘어가시겠습니까?(y/n) : "))
    if Continue == "y":
                  break
    if Continue == "n":
                  print("다시 입력")
                  continue
print("자동차2의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar2.color, myCar2.speed))

while True:
    myCar3.color = input("자동차 3의 색상 입력 : ")
    myCar3.speed = int(input("자동차 3의 가속도 입력(km) : "))
    Continue = str(input("다음 차량으로 넘어가시겠습니까?(y/n) : "))
    if Continue == "y":
                  break
    if Continue == "n":
                  print("다시 입력")
                  continue
print("자동차3의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar3.color, myCar3.speed))

d








# 생성자는 인스턴스를 생성하면 무조건 호출되는 메소드
# 클래스 정의 부분
class Car :
    color = ""
    speed = 0

    def __init__(self) :
        self.color = "빨강"

    def upSpeed(self, value) :
        self.speed += value
        
    def downSpeed(self, value) :
        self.speed -= value

# 메인 코드 부분
myCar1 = Car("빨강",30)
myCar2 = Car("파랑",20)
myCar3 = Car("노랑",60)

print("자동차1의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar1.color, myCar1.speed))
print("자동차2의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar2.color, myCar2.speed))
print("자동차2의 색상은 %s이며, 현재속도는 %d km 입니다." % (myCar3.color, myCar3.speed))

d

d








class Car :
    name = "아우디"
    speed = 0
    count = "10억"

    def __init__(self, name, speed) :
        self.name = name
        self.speed = speed

    def getName(self) :
        return self.name

    def getSpeed(self):
        return self.speed

#변수선언
car1, car2 = None, None

#메인 코드 부분
car1 = Car("아우디", 0)
car2 = Car("벤츠", 30)


print("%s의 현재 속도는 %d입니다." % (car1.getName(), car1.getSpeed() ))
print("%s의 현재 속도는 %d입니다." % (car2.getName(), car2.getSpeed() ))
print("%s차의  가격은 %s입니다." % (car1.name, Car.count))

d

'먼지 낀 책장사이 > Python' 카테고리의 다른 글

쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
문자열, 구구단, 그림그리기  (0) 2016.09.13
가변 매개변수, 모듈  (0) 2016.09.06
연산자, while 반복, for문, 리스트/사전/튜플  (0) 2016.08.30

4+3
a=1
b=2
c=a+b
print("hello")
print(c)
a=int(input())
b=int(input())
result=a+b
print(a,"+",b,"=",result)




print(100+100)
print("%d",(100+100))
print("%d"%(100+100))
print("%d %d"%(100,100))

서식->%d(10진수),%x(16진수),%f(실수),%(문자),%s(문자열)



def fun_ex(num):
    n=1
    while n <=10:
        print(n,"x",num,"=",n*num)

fun_ex(숫자입력)

1 x 20 = 20

2 x 20 = 40

3 x 20 = 60

4 x 20 = 80

5 x 20 = 100

6 x 20 = 120

7 x 20 = 140

8 x 20 = 160

9 x 20 = 180

10 x 20 = 200



import time
n=1
while n < 9:
    m=1
    print(n+1,"단")
    n=n+1
    while m <= 9:
        print(n,"x",m,"=",n*m)
        m=m+1
    time.sleep(3)

8월23일자 구구단



i,k = 0,0
for i in range(2,10):
    print("--- %d 단 ---"%i)
    for k in range(1,10):
        guguLine = str("%2d X %2d = %2d"%(i,k,i*k))
        print(guguLine)

8월30일자 구구단



from tkinter import*

##변수##
window = None
canvas = None

x1, y1, x2, y2 = None, None, None, None

## 함수 ##
def mouseClick(event):
    global x1, y1, x2, y2
    x1 = event.x
    y1 = event.y
    
def mouseDrop(event):
    global x1, y1, x2, y2
    x2 = event.x
    y2 = event.y
    canvas.create_line(x1,y1,x2,y2,width=5,fill="red")

## 메인코드 ##
window = Tk()
window.title("그림그리기")
canvas = Canvas(window, height=300, width=300)
canvas.bind("",mouseClick)
canvas.bind("",mouseDrop)
canvas.pack()
window.mainloop()

0823 그림판

'먼지 낀 책장사이 > Python' 카테고리의 다른 글

쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20
가변 매개변수, 모듈  (0) 2016.09.06
연산자, while 반복, for문, 리스트/사전/튜플  (0) 2016.08.30

def para_func(*para):
    result = 0
    for num in para:
        result = result + num
    return result


변수선언

>>> hap = 0

실행

>>> hap = para_func(10,20,30)

>>> print(hap)

60




def para_func(*para):
    result = 0
    for num in para:
        result = result + num
    return result

#변수선언
hap = 0
v1,v2,v3 = 0,0,0

#메인코드
while True :
    v1 = int(input("v1 = "))
    v2 = int(input("v2 = "))
    v3 = int(input("v3 = "))
    hap = para_func(v1,v2,v3)
    print("hap=%d"%hap)
    if hap == 0 :
            print("프로그램 종료")
            break


v1 = 10

v2 = 20

v3 = 30

hap=60


#모듈 -> 함수의 집합으로 다른 프로그램에서도 활용하고자 할 때 사용
def func1() :
    print("func1()함수 실행")

def func2() :
    print("func2()함수 실행")

def func3() :
    print("func3()함수 실행")

def func4() :
    print("func4()함수 실행")

def func5() :
    print("func5()함수 실행")

func5() #실행할 함수


func5()함수 실행





#콘솔(console) : 키보드 + 모니터

#쓰기용 : 변수명 - open("파일명","w")

text = "통신응용프로그래밍실습"
f = open("e:\swa\swa2.txt","w")
f.write(text)   #write 함수
f.close()
print("파일저장 완료 : %s" %f)


파일저장 완료 : <_io.TextIOWrapper name='e:\\swa\\swa2.txt' mode='w' encoding='cp949'>


# Source_code 10-1
inFp = open("E:\swa\swa.txt","r",encoding="utf-8")
intStr = inFp.readline()
print(intStr, end="")


intStr = inFp.readline()
print(intStr, end="")


intStr = inFp.readline()
print(intStr, end="")

inFp.close()

손용호

밤새더니

학교와서

계속 잠만 자네 (세번째 줄까지만 출력)



# Source_code 10-2
# while 문에 의한 처리
inFp = None
inStr = ""

inFp = open("E:\swa\swa.txt","r",encoding="utf-8")
while True :
    inStr = inFp.readline()
    if inStr == "" :
        break
    print(inStr,end="")
inFp.close()

손용호

밤새더니

학교와서

쿨쿨자네

으이그



# Source_code 10-2
# list 문에 의한 처리
inFp = None
inList, inStr =[], ""

inFp = open("E:\swa\swa.txt","r",encoding="utf-8")
inList = inFp.readlines()
for inStr in inList :
    print(inStr,end="")
inFp.close()

손용호

밤새더니

학교와서

쿨쿨자네

으이그




#source_code10-6
#파일검색
import os
inFp = None
fName, inList, inStr = "",[],""
while True :
    fName = input("파일명을 입력하세요 : ")
    if os.path.exists(fName) :
        inFp = open("E:\swa\swa.txt","r",encoding="utf-8")
        inList = inFp.readlines()
        for inStr in inList :
            print(inStr,end="")
            inFp.close()
    if fName == "끝" :
        break
    if fName != "swa.txt" :
        print("%s 파일이 없습니다."%fName)
print("프로그램을 종료합니다.")


#source_code10-6
#파일쓰기
outFp = None
outStr = ""

outFp = open("E:\swa\swa2.txt","a",encoding="utf-8")
while True :
    outStr = input("내용 입력 : ")
    if outStr != "" :
        outFp.writelines(outStr+"\n")
    else :
        break
outFp.close()  
print("정상적으로 파일에 썼습니다.")









8>>1
8<<1
2&4    #and
2|4    #or
8^2    #ex or
~0



score = 1
while score != 0:
	score=int(input("점수입력 : "))
	if score>=90:
		print("A")
	elif score>=80:
		print("B")
	elif score>=70:
		print("C")
	elif score>=60:
		print("D")
	else:
		print("F")
	print("학점입니다.^^\n")
print("프로그램을 종료합니다")











score = 1
while True :
        score=int(input("점수입력 : "))
        if score == 0 :
                break
        if score>=90 :
                print("A")
        elif score>=80:
                print("B")
        elif score>=70:
                print("C")
        elif score>=60:
                print("D")
        else:
                print("F")
        print("학점입니다.^^\n")
print("프로그램을 종료합니다")













for i in range(0,3,1):             #0으로 시작해서 3사이에 1씩
    print("Hello")
Hello
Hello
Hello
for i in [0,3,1]:                  #0으로 시작해서 3사이에 1씩
    print("Hello")
Hello
Hello
Hello
for i in range(0,6,1):             #0으로 시작해서 6사이에 1씩
    print("%d"%i)                  #"십진수의 형태로" i 값을 불러온다
0
1
2
3
4
5
for i in [0,1,2,3,4,5,6,7,8,9]:    #배열지정
    print("%d"%i)nbsp;             #"십진수의 형태로" i 값을 불러온다
0
1
2
3
4
5
6
7
8
9
i,hap = 0,0
for i in range(1,11,1):
    hap=hap+i
    print("1에서 %d 까지의 합 = %d"%(i,hap))
1에서 1 까지의 합 = 1
1에서 2 까지의 합 = 3
1에서 3 까지의 합 = 6
1에서 4 까지의 합 = 10
1에서 5 까지의 합 = 15
1에서 6 까지의 합 = 21
1에서 7 까지의 합 = 28
1에서 8 까지의 합 = 36
1에서 9 까지의 합 = 45
1에서 10 까지의 합 = 55









num = 1
while True:
    num = int(input("num : "))
    if num == 0:
                  break
    if num == 1:
                  print("다시 입력")
                  continue
    print(num)
    print("0이면 종료")










import random
my_tuple = ("one","two","three","four")
while True:
    i=random.randint(0,3)
    print(my_tuple[i])
    key = int(input("key : "))
    if key == 0:
        break
print("프로그램 종료")

대괄호로 묶으면 리스트 중괄호로 묶으면 사전 소괄호로 묶으면 튜플




import random
i=0
key=1
my_list = ["one","two","three","four"]
while True:
    i=random.randint(0,3)
    print(my_list[i])
    key = int(input("key : "))
    if key == 0:
        break
print("프로그램 종료")

대괄호로 묶으면 리스트 중괄호로 묶으면 사전 소괄호로 묶으면 튜플


list값 변경

a_list = [10,20,30,40]

a_list [2] = 300


list값 삭제

a_list = [10,20,30,40]

del(a_list[1])


dictionary

dic_1 = {1:'a',2:'b',3:'c'}


student = {'학번':1000,'이름':'홍길동','학과':'모바일'}


dictionary값 추가/변경

student ['연락처']='010-9406-2682'


dictionary값 삭제

del(student[연락처])



데이터 읽기

student['학번']

list(student.keys())

student.values()

student.items()



#for문 활용 dictionary값 출력
mobile={}   #tuple->().list->[]
mobile['이름']='김수환'
mobile['학번']='130100682'
mobile['주소']='서울 용산구 보광동'
mobile['학점']='A+'
mobile['전화번호']='010-1234-5678'
for mo in mobile.keys():
    print('%s ---> %s' %(mo,mobile[mo]))




#함수정의
def calc(num1,num2,op):
    result = 0
    if op == '+' :
        result = num1 + num2
    if op == '-' :
        result = num1 - num2
    if op == '*' :
        result = num1 * num2
    if op == '/' :
        result = num1 / num2
    return result

##변수선언
res = 0
var1, var2, oper = 0, 0, ""

###메인코드
#res = calc(10,20,"+")
print(res)
print()
oper = input("연산자 입력(+,-,*,/) : ")
var1 = int(input("num1 값 입력 : "))
var2 = int(input("num2 값 입력 : "))

res = calc(var1,var2,oper)
print("계산기 : %d %s %d = %f "%(var1,oper,var2,res))


def para_func(val_1=0,val_2=0,val_3=0,val_4=0,val_5=0):    #매개변수
    result = 0
    result = val_1+val_2+val_3+val_4+val_5
    return result
value = para_func(10,20,30,40,50)
print(value)
150

para_func(10,20,30)

60


#함수의 가변 매개변수
def para_func(*para):
    result = 0
    for num in para:
        result = result + num
    return result
hap = para_func(10,20,30)
print(hap)


'먼지 낀 책장사이 > Python' 카테고리의 다른 글

쓰레드  (0) 2016.10.11
상속, 오버라이딩, 툴킷  (0) 2016.09.27
Raw파일 읽기, 클래스, 생성자  (0) 2016.09.20
문자열, 구구단, 그림그리기  (0) 2016.09.13
가변 매개변수, 모듈  (0) 2016.09.06