본문 바로가기

m

240508

**지역변수

함수 내에서 선언되고 해당 함수 내에서만 접근 가능한 변수.

함수가 실행될 때 생성되고, 함수의 실행이 종료되면 소멸

다른 함수에서 같은 이름의 변수를 사용해도 서로 영향을 주지않음.


**전역변수

프로그램 전체에서 접근 가능한 변수로, 어디서든 사용

프로그램 규모가 커지면 변수의 상태를 추적하기 어려워지고 버그를 일으키기 쉬우므로 되도록 사용을 최소화해야


**매개변수

함수에 전달되는 값을 받아들이는 변수. 함수가 호출될 때 인수로 전달된 값에 의해 초기화됨.

함수 내에서 지역 변수처럼 사용

 

***jqmonster

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>몬스터 만들기</title>    
    <style>
        body {
            background-color: #000;
        }
        .lighting {
            display: none;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 0;
        }
        #top {
            position: relative;
            left: 0;
            top: 0;
            height: 80px;
            z-index: 10; /*번개보다 위*/
        }
        #top>img {
            position: absolute;
            left: 200px;
            top: 10px;
        }
        #top>p {
            position: absolute; /*겹치지 않게 */
            left: 140px;
            top: 30px;
            color: #33ff66; /*배경이 검은색이라 안보여서*/
        }
        #container {
            position: relative;
            left: 0;
            top: 0;
            height: 700px;
        }
        .frame {
            position: absolute;
            left: 100px;
            top: 0;
            width: 546px;
            height: 629px;
            background-image: url(images/frame.png); 
        }
        .pic_box {
            position: absolute;
            left: 91px;
            top: 84px;
            width: 367px;
            height: 460px;
            overflow: hidden;
        }
        .face { /*div들의 공통적 이름*/
            position: relative; /*옆으로 슬라이드/ 포지션*/
            left: 0;
            top: 0;
        }
        .head {
            height: 172px; /*이미지 높이만큼 div크기로 한다*/
        }
        .eyes {
            height: 79px;
        }
        .nose {
            height: 86px;
        }
        .mouth {
            height: 124px;
        } /*얼굴의 틈새들이 채워짐*/
    </style>
    <script src="js/jquery-3.7.1.min.js"></script> 
    <script>
        $(function() { 
            let headclix=0, eyesclix=0, noseclix=0, mouthclix=0 //각각 값을 줌
            //머리 이미지 슬라이드
            $('.head').click(function() {
                headclix++;
                if(headclix<10) {
                    $(this).animate ({
                        left:-(headclix*367) //1이면 왼으로 367가고,2면 367x2만큼 이동,..
                    },'slow');
                }else {
                    $(this).animate({ //끝에 빈거 아니고 처음으로 돌아와(초기값)
                        left:0
                    },'slow');
                    headclix=0;
                }
            });
            //눈 이미지 슬라이드
            $('.eyes').click(function() {
                eyesclix++;
                if(eyesclix<10) {
                    $(this).animate ({
                        left:-(eyesclix*367) 
                    },'slow');
                }else {
                    $(this).animate({ 
                        left:0
                    },'slow');
                    eyesclix=0;
                }
            });
            //코 이미지 슬라이드
            $('.nose').click(function() {
                noseclix++;
                if(noseclix<10) {
                    $(this).animate ({
                        left:-(noseclix*367) 
                    },'slow');
                }else {
                    $(this).animate({ 
                        left:0
                    },'slow');
                    noseclix=0;
                }
            });
            //입 이미지 슬라이드
            $('.mouth').click(function() {
                mouthclix++;
                if(mouthclix<10) {
                    $(this).animate ({
                        left:-(mouthclix*367) 
                    },'slow');
                }else {
                    $(this).animate({ 
                        left:0
                    },'slow');
                    mouthclix=0;
                }
            });
            //번개 구현
            setInterval(function() {
                $('.lighting1').fadeIn(250).fadeOut(250); //번개가 잠깐 치는 것처럼
            },4000);
            setInterval(function() {//1한다음 1초후
                $('.lighting2').fadeIn(250).fadeOut(250);
            },5000);
            setInterval(function() {//2한다음 2초후
                $('.lighting3').fadeIn(250).fadeOut(250); 
            },7000);
        });
    </script>
</head>
<body> 
    <img class="lighting lighting1" src="images/lightning-01.jpg" alt="lightning-01">
    <img class="lighting lighting2" src="images/lightning-02.jpg" alt="lightning-02">
    <img class="lighting lighting3" src="images/lightning-03.jpg" alt="lightning-03">
    <header id="top">
        <img src="images/Monster_Mashup.png" alt="Monster_Mashup">
        <p>Make your own face by clicking on the picture</p>
    </header>
    <div id="container">
        <div class="frame">
            <div class="pic_box">
                <div class="head face">
                    <img src="images/headsstrip.jpg" alt="head">
                </div>
                <div class="eyes face">
                    <img src="images/eyesstrip.jpg" alt="eyes">
                </div>
                <div class="nose face">
                    <img src="images/nosesstrip.jpg" alt="nose">
                </div>
                <div class="mouth face">
                    <img src="images/mouthsstrip.jpg" alt="mouth">
                </div>
            </div>
        </div>
    </div>
</body>
</html>

 

***jqmonster2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>몬스터 만들기</title>    
    <style>
        body {
            background-color: #000;
        }
        .lighting {
            display: none;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 0;
        }
        #top {
            position: relative;
            left: 0;
            top: 0;
            height: 80px;
            z-index: 10; /*번개보다 위*/
        }
        #top>.text_top {
            position: absolute;
            left: 200px;
            top: 10px;
        }
        #top>p {
            position: absolute; /*겹치지 않게 */
            left: 140px;
            top: 30px;
            color: #33ff66; /*배경이 검은색이라 안보여서*/
        }
        #top>.random_top { 
            position: absolute;
            left: 580px;
            top: 20px;
            cursor: pointer;
        }
        #container {
            position: relative;
            left: 0;
            top: 0;
            height: 700px;
        }
        .frame {
            position: absolute;
            left: 100px;
            top: 0;
            width: 546px;
            height: 629px;
            background-image: url(images/frame.png); 
        }
        .pic_box {
            position: absolute;
            left: 91px;
            top: 84px;
            width: 367px;
            height: 460px;
            overflow: hidden;
        }
        .face { /*div들의 공통적 이름*/
            position: relative; /**/
            left: 0;
            top: 0;
        }
        .head {
            height: 172px; /*이미지 높이만큼 div크기로 한다*/
        }
        .eyes {
            height: 79px;
        }
        .nose {
            height: 86px;
        }
        .mouth {
            height: 124px;
        } /*얼굴의 틈새들이 채워짐*/
    </style>
    <script src="js/jquery-3.7.1.min.js"></script> 
    <script>
        $(function() { //객체(obj), 배열이 중요!
            let clix=[0,0,0,0]; //배열방이 각각 인덱스 위치
            let index; //매개변수
            lighting(); //번개함수 호출
            //랜덤하게 몬스터 구현 
            $('.random_top').click(function() { //썸네일 누르면 자동으로 랜덤 만듦 
                $('.face').each(function(index) {
                    clix[index]=Math.round(Math.random()*9);
                    monsterMove(index,this);
                });
            });
            $('.face').click(function() { //인) 머리0, 눈1, 코2, 입3
                index=$(this).index(); //인덱스별로 누구 클릭했는지 알 수 있다
                monsterMove(index,this); //클릭한 당사자 나를 전달
            });
            //몬스터 이미지 슬라이드 구현 함수
            function monsterMove(index, obj) { //obj-클릭한당사자 this로 받음
                clix[index]++;
                if(clix[index]<10) {
                    $(obj).animate ({ //obj-머리 받았으면 머리, 입 받음 입
                        left:-(clix[index]*367) //1이면 왼으로 367가고,2면 367x2만큼 이동,..
                    },'slow');
                }else { //클릭스의 몇번째방이 움직인값10이되면 다시 0으로 돌아가
                    $(obj).animate({ //초기값
                        left:0
                    },'slow');
                    clix[index]=0;
                }
            }
            //번개 구현
            setInterval(function() {
                $('.lighting2').fadeIn(250).fadeOut(250);
            },5000);
            setInterval(function() {
                $('.lighting3').fadeIn(250).fadeOut(250); 
            },7000);
            //번개 치는 함수
            function lighting() { 
                $('.lighting1').fadeIn(250).fadeOut(250); //시작하자마자 번개침
                setTimeout(function() { //치고 나서 4초후
                    lighting(); //재귀호출(자기자신 호출)
                },4000);
            }
        });
    </script>
</head>
<body> 
    <img class="lighting lighting1" src="images/lightning-01.jpg" alt="lightning-01">
    <img class="lighting lighting2" src="images/lightning-02.jpg" alt="lightning-02">
    <img class="lighting lighting3" src="images/lightning-03.jpg" alt="lightning-03">
    <header id="top">
        <img class="text_top" src="images/Monster_Mashup.png" alt="Monster_Mashup">
        <p>Make your own face by clicking on the picture</p>
        <img class="random_top" src="images/monster.png" alt="title" title="클릭하면 랜덤하게 몬스터가 만들어집니다.">
    </header>
    <div id="container">
        <div class="frame"><!--액자안의 이미지 수동으로 몬스터 만들기-->
            <div class="pic_box">
                <div class="head face">
                    <img src="images/headsstrip.jpg" alt="head">
                </div>
                <div class="eyes face">
                    <img src="images/eyesstrip.jpg" alt="eyes">
                </div>
                <div class="nose face">
                    <img src="images/nosesstrip.jpg" alt="nose">
                </div>
                <div class="mouth face">
                    <img src="images/mouthsstrip.jpg" alt="mouth">
                </div>
            </div>
        </div>
    </div>
</body>
</html>

 

***jqobject

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 라이브러리</title>
    <script src="js/jquery-3.7.1.min.js"></script>
    <script> //$(function() {})은 내부함수안의 함수가 들어가서 쓰면 안됨/ 이 식은 외부함수
        let product={ //프로덕트 라는 객체/ jsB>obj2
            name: '냉장고',
            price: 1950000,
            type: '양문형'
        };
        let result=prodInfo.bind(product); 
        function prodInfo() {
            alert(this, name); //밖에 있어서 this쓰면 안되지만
        }
        let pcode={
            code : 'ss5123',
            number : 123
        }
        $.extend(product,pcode); //확장해서 피코드를 프로덕트에 집어넣음
        console.log(product); //5개 속성가진 객체
        alert(product.code)
    </script>
</head>

<body>
    <h2 onclick="result();">제품정보</h2> <!--리절트 누르면 호출, 프로덕인포의 냉장고 정보 찍힘-->
</body>
</html>

 

***jqobject2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 라이브러리</title>
    <script src="js/jquery-3.7.1.min.js"></script>
    <script> 
        let wh= {
            width: 500,
            height: 700
        }
        let size= {
            width: 300,
            height: 200
        }
        $.extend(wh, size); //원본객체에 뒤에 있는거 추가해 확장
        console.log(wh);
    </script>
</head>

<body>
    
</body>
</html>

 

***jqobject3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 라이브러리</title>
    <script src="js/jquery-3.7.1.min.js"></script>
    <script> 
        $(function() {
            $('button').click(function() {
                $('.koala').wrap('<div></div>'); //img가 div를 묶음
            });
            let nums=[10,20,30];
            nums.push(40);
            //console.log(nums);
            let nums2=[10,20,30];
            let nums3=Array.from(nums2); //Array.from은 괄호안 2를 복사해 3에 넘김(새로운 객체 넘스3 만듦) 
            nums3.push(40);
            //console.log(nums3);
            let nums4=[10,20,30]
            let nums5=nums4.concat(40); //4에 40결합해 새로운5를 만듦
            console.log(nums5);
        });
    </script>
</head>

<body>
    <button>영역만들기</button>
    <img class="koala" src="../images/Koala.jpg" alt="">
</body>
</html>

 

*공공데이터포털- 한국 정부가 운영하는 온라인 플랫폼으로, 다양한 공공 데이터를 제공(필요한 프로그램 개발, 활용)

 

pip install faker (pip: 파이썬 인스톨 명령어/ 외부 라이브러리 설치

***faker.py

# 테스트용 가짜 데이터 생성 라이브러리 (인스톨 한번에 내컴포터에 저장됨)
from faker import Faker #페이커: 테스트용 가짜 데이터 만들어줌
#fake=Faker()
fake=Faker('ko-KR')
#print(fake.name())
#print(fake.address())
test_data=[(fake.name(), fake.address()) for i in range(30)]
print(test_data)

 

name() 이름
address() 주소
postcode() 우편번호
country() 국가명
company() 회사명
job() 직업명
phone_number() 휴대전화 번호
email() 이메일
text() 임의의 문장(catch_phrase())
color_name() 색상명

 

***sympy01.py

# 방정식 사용하게 해주는 라이브러리
from fractions import Fraction #Fraction: 유리수를 분자분모 형태로
import sympy
a=Fraction(2,5)
print(a) #결과 2/5로 밑에 코드 수행결과와 같음
#a=Fraction('2/5')
#print(a)
x=sympy.symbols("x") #x는 임의의 수
f=sympy.Eq(x*Fraction('2/5'),3500) #x의 5분의2 가지고 3500원 커피 사먹음/ x*(5/2)=3500
result=sympy.solve(f) #결과값
print("철수가 원래 가진 돈=", result)
remain=result[0]-3500
print("커피사고 남은 돈은=", remain)

pip install sympy

 

***sympy02.py

# 2차 방정식의 해 
import sympy #분자분모/ 연립방정식 구함
'''
x=sympy.symbols("x")
f=sympy.Eq(x**2,1)
result=sympy.solve(f)
print(result)  '''

# 연립방정식의 해 
x,y=sympy.symbols("x y")
f1=sympy.Eq(x+y, 10)
f2=sympy.Eq(x-y, 4)
result=sympy.solve([f1,f2]) #딕셔너리 구함
print(result)
'''
문) 농장에서 오리와 돼지를 도축한 다리수가 56족이고 마리수가 17마리다. 돼지와 오리는 몇 마리?
x,y=sympy.symbols("x y")
f1=sympy.Eq(2*x+4*y, 56)
f2=sympy.Eq(x+y, 17)
result=sympy.solve([f1,f2]) 
print(result)  '''

 

***tkwin01.py

# GUI 툴킷에 대한 파이썬 바인딩 (인스톨없이)
from tkinter import * #tkinter-내장된. 기능이 한정됨
main=Tk()  #크로스 플랫폼을 지원하는 GUI 툴킷
main.title("파이썬 테스트") #윈도 창의 제목
main.geometry("300x200") #크기 주기
#main.mainloop() #윈도우창 하나 생성
main.resizable(False, False) #적용시 크기 고정됨. 못 늘림
#lbl=Label(main,text="오후 수업중", font="Arial 20")
lbl=Label(main)
lbl["text"]="오후 수업중"
lbl["font"]="궁서체 20"
lbl.pack()
def helloclick():
    lbl["text"]="안녕하세요"
hello=Button(main, text="인사하기", foreground="Red", command=helloclick) #버튼 만들기/ text: 버튼에 들어갈 글씨/ foreground-글씨색
hello.pack()
def byeclick():
    lbl["text"]="잘가세요"
bye=Button(main, text="보내기", foreground="Green", command=byeclick)
bye.pack()
main.mainloop()

 

***tkwin02.py

from tkinter import *
import tkinter.messagebox
main=Tk()
main.title("입장 테스트 화면") 
main.geometry("300x200")
main.resizable(False, False)
def testclick():
    if tkinter.messagebox.askyesno("질문","당신은 미성년자입니까?"): #예,아니오 버튼 나옴
        tkinter.messagebox.showwarning("경고","애들은 가라")
    else:
        tkinter.messagebox.showinfo("환영","어서오세요, 고객님")  
btn=Button(main, text="입장여부",foreground="Blue",background="#ffff00", command=testclick)
btn.pack()
main.mainloop()

 

***tkwin03.py

from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog #창이 뜨는
main=Tk()
main.title("입장 테스트 화면") 
main.geometry("300x200")
main.resizable(False, False)
def testclick():
    name=tkinter.simpledialog.askstring("질문","이름을 입력하세요")
    age=tkinter.simpledialog.askstring("질문", "나이를 입력하세요")  
    if name and age:
        if int(age) <=19:
            tkinter.messagebox.showwarning("경고","애들은 가라")
        else:
            tkinter.messagebox.showinfo("환영",name+"님 환영합니다.") #메시지 타이틀 적어야 제대로 나옴 
    else:
        tkinter.messagebox.showwarning("오류","입력값이 없습니다.")          
btn=Button(main, text="입장여부",foreground="Blue",background="#ffff00", command=testclick)
btn.pack()
main.mainloop()

 

***tkwin04.py

from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog #창이 뜨는
main=Tk()
main.title("입장 테스트 화면") 
main.geometry("400x300")
main.resizable(False, False)
can=Canvas(main, width=400, height=200) #그리는 도화지
can.pack() #메인에 들어간다
can.create_line(10,10,100,100) #start x,y(시작좌표), end x,y/ 시작위치와 끝이 선으로 이어짐
can.create_line(10,100,100,10, fill="blue")
can.create_rectangle(110,10,200,100, outline="red", width=5)
can.create_oval(210,10,300,100, width=3,fill="yellow")
menubar=Menu(main)
main.config(menu=menubar)
popup=Menu(menubar)
menubar.add_cascade(label="정보",menu=popup) #캐스케이드: 눌렀을때 펼쳐지는
def testclick():
    name=tkinter.simpledialog.askstring("질문","이름을 입력하세요")
    age=tkinter.simpledialog.askstring("질문", "나이를 입력하세요")  
    if name and age:
        if int(age) <=19:
            tkinter.messagebox.showwarning("경고","애들은 가라")
        else:
            tkinter.messagebox.showinfo("환영",name+"님 환영합니다.") #메시지 타이틀 적어야 제대로 나옴 
    else:
        tkinter.messagebox.showwarning("오류","입력값이 없습니다.")          
popup.add_command(label="입장여부", command=testclick)
popup.add_command(label="종료", command=quit)
main.mainloop()

 

***tkwin05.py

from tkinter import *
main=Tk()
main.title("입장 테스트 화면") 
main.geometry("500x400")
can=Canvas(main, width=500,height=400)
can.pack()
img=PhotoImage(file="D:/kyj/pythonStudy/pylib/smile.png")
can.create_image(10,10, image=img, anchor=NW) #10,10-이미지의 x, y 좌표/ anchor-이미지의 위치
main.mainloop()

 

***turtle01.py

import turtle as t #터틀그래픽-아이들 교육용
t.shape("turtle")  #커서 역할
t.right(60)
t.forward(100)  #forward()- 괄호안의 픽셀만큼 전진/ backward-뒤로 후진
t.right(120) #right(각도)- 오른쪽 회전/ left- 왼쪽 회전
t.forward(100)
t.right(120)
t.forward(100)
t.done()

 

turtle 거북이
classic 화살표
triangle 화살표
arrow 화살표
square 사각형
circle 원
pendown 꼬리를 내림(그리기 시작)
penup 꼬리를 올림(그리지 않고 이동)
speed 거북이 이동 속도/ 1이 느리고 10이 가장 빠름. (0은 10보다 빠름. 잘 안씀)
showturtle 거북이 표시
hideturtle 거북이 숨김
stamp 현재 위치 거북이 도장을 찍는다.
clear 화면 치움
reset 화면을 치우고 거북이를 중앙에 배치

 

***turtle02.py

import turtle as t #터틀그래픽-아이들 교육용
t.shape("turtle")  #커서 역할
t.speed(1)
t.forward(200)
t.penup()
t.forward(50)
t.pendown()
t.forward(100)
t.done()

 

'm' 카테고리의 다른 글

240513  (0) 2024.05.13
240509  (0) 2024.05.09
240507  (0) 2024.05.07
240503  (0) 2024.05.03
240502  (1) 2024.05.02