출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>유효성 검사</title>
</head>

<body>
    
    <form id="myform">
    
        <h1> 회원가입</h1>
        <hr>
        <table>
            <tr>
                <td><label for="uesrid">아이디(이메일)</label></td>
                <td><input type="text" name="userid" id="userid"></td>
            </tr>
            <tr>
                <td><label for="pw">비밀번호</label></td>
                <td><input type="password" name="pw" id="pw"></td>
            </tr>
            <tr>
                <td><label for="pw-check">비밀번호 번호 확인</label></td>
                <td><input type="password" name="pw-check" id="pw-check"></td>
            </tr>
            <tr>
                <td><label for="username">이름</label></td>
                <td><input type="text" name="username" id="username"></td>
            </tr> 
            <tr>
                <td></td>
                <td><input type="submit" value="회원가입">
                    <input type="reset" value="초기화"></td>
            </tr>
        
        
        </table>
    </form>
</body>
</html>
<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>유효성 검사</title>
    
    <script>
    
        window.onload = function(){
            
            document.querySelector('#myform').onsubmit = function(){               
                var userid = document.querySelector('#userid');
                var pw = document.getElementById('pw');
                var pwcheck = document.getElementById('pw-check');
                var username = document.querySelector('#username');
                
                // 유효성 검사 1: 공백이 없어야 한다.
                if(userid.value.trim().length < 1){
                    alert ('id는 필수 항목입니다.');
                    userid.value='';
                    userid.focus(); //커서를 userid로 이동시키는 함수
                    return false;
                }
                
                if(pw.value.trim()<1){
                    alert('비밀번호는 필수항목입니다.');
                    pw.value='';
                    pw.focus();
                    return false;
                }
                
                // pw == pwcheck 이어야 한다.
                if(pwcheck.value.trim()<1 || pw.value!=pwcheck.value){
                    alert('비밀번호 확인이 일치하지 않습니다.');
                    pwcheck.value='';
                    pwcheck.focus();
                    return false;
                }
                
                 if(username.value.trim()<1){
                    alert('이름 항목은 필수항목입니다.');
                    username.value='';
                    username.focus();
                    return false;
                }
        };
            
        };
    
    </script>
</head>

<body>
    
    <form id="myform" action="http://www.naver.com">
    
        <h1> 회원가입</h1>
        <hr>
        <table>
            <tr>
                <td><label for="uesrid">아이디(이메일)</label></td>
                <td><input type="text" name="userid" id="userid"></td>
            </tr>
            <tr>
                <td><label for="pw">비밀번호</label></td>
                <td><input type="password" name="pw" id="pw"></td>
            </tr>
            <tr>
                <td><label for="pw-check">비밀번호 번호 확인</label></td>
                <td><input type="password" name="pw-check" id="pw-check"></td>
            </tr>
            <tr>
                <td><label for="username">이름</label></td>
                <td><input type="text" name="username" id="username"></td>
            </tr> 
            <tr>
                <td></td>
                <td><input type="submit" value="회원가입">
                    <input type="reset" value="초기화"></td>
            </tr>
        
        
        </table>
    </form>
</body>
</html>

 

다 입력하면 action = > naver로 가짐

 

 

클릭 이벤트 / this 키워드

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>event</title>
</head>

<style>
    h1 {
        border: 1px solid #999;
    }
</style>

<script>
    
    window.onload = function(){
        
        // 캐스팅_변수선언
        var hearder = document.getElementById('header');
        
        // 클릭하면 Click hearder :)♡가 뜨는 onclick 이벤트 연결
        header.onclick = function(){
            alert('Click header :)♡ '+this.innerHTML); 
            // this > 이벤트가 발생한 header를 가리키고 있다 
            // 여기서 this.innerHTML는 C L I C K! 이다          
            
        // 이벤트 제거 > 한번 클릭하고 나면 창이 다시뜨지 않는다.
        header.onclick = null;
            
        }
        
    };
    
</script>

<body>

    <h1 id="header"> C L I C K ! </h1>

</body></html>

 

이벤트 강제실행

 

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>event</title>
</head>

<style>
    h1 {
        border: 1px solid #999;
    }
</style>

<script>
    
    window.onload = function(){
        
    
        
        // 캐스팅
        var btn1 = document.getElementById('btn1'); //버튼id
        var btn2 = document.getElementById('btn2');
        
        var cnt1 = document.getElementById('count-a');
        var cnt2 = document.getElementById('count-b');
        
        // btn 문서객체에 클릭이벤트 적용
        btn1.onclick = function(){
            // 클릭하면 숫자증가 
            cnt1.innerHTML = Number(cnt1.innerHTML)+1;
            // a를 누르면 b 버튼 카운트도 같이 증가하고 싶다면
            //btn2.onclick();
            
        };
        
        btn2.onclick = function(){     //inner나 text나 둘다상관없음
            cnt2.innerHTML = Number(cnt2.textContent)+1;            
        };
        
        
        
    };
    
</script>

<body>
        
    <button id="btn1">Button-A</button>
    <button id="btn2">Button-B</button>
    <h1>Button-A : <span id="count-a">0</span></h1>
    <h1>Button-B : <span id="count-b">0</span></h1>
    

</body></html>

 

인라인 이벤트 모델

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>event</title>
</head>

<style>
    h1 {
        border: 1px solid #999;
    }
</style>

<script>
    
    function clickH1(){
        alert('인라인 방식으로 이벤트 처리');
    }
</script>

<body>
    
    <h1 onclick="clickH1();">인라인 방식의 이벤트 정의</h1>


</body></html>

문서 객체의 스타일 변경

- style 속성 사용
- getElementById ( ) 메서드로 문서 객체를 가져옴
- style 속성에 있는 border, color, fontFamily 속성을 지정
- CSS에 입력하는 것과 같은 형식으로 입력

 

<!DOCTYPE html>
<html lang="">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {
            
            // 태그이름으로 문서객체 생성 > 배열로 반환
            var divs = document.getElementsByTagName('div'); // div 아래두개모두선택
            divs[0].innerHTML='By tagname - 0 ';
            divs[1].innerHTML='By tagname - 1 ';
            
            // style
            divs[0].style.color = 'pink';       

        };
    </script>

</head>

<body>

    <div id="header-1">1</div>
    <div id="header-2">2</div>

</body></html>


<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Window Object</title>

    <script>
        window.onload = function() {

            document.getElementById('go_naver_btn').onclick = function() {
                
                var alink = document.querySelector('a');
                alink.style.display='block';
                alink.style.backgroundColor='blue';
                alink.style.fontSize=32;
                alink.style.color='yellow';
                alink.style.fontWeight='bold';
                alink.style.textAlign='center';

            };         


        };
    </script>

</head>

<body>


    <a href="http://www.naver.com">네이버로 이동</a>

</body></html>

 

HTML 태그를 자바스크립트로 가져오는 방법

 

<!DOCTYPE html>
<html lang="">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {

            //html 문서의 요소를 문서 객체로 만들기
            // id 속성값으로 문서 객체 생성 : 캐스팅
            // document.getElementById('아이디속성값');

            var header1 = document.getElementById('header-1');
            var header2 = document.getElementById('header-2');

            // 문서 객체의 속성 변경
            header1.innerHTML = '<i>문서객체 생성</i>';
            header2.textContent = '<i>문서객체 생성</i>';


        };
    </script>

</head>

<body>

    <div id="header-1">1</div>
    <div id="header-2">2</div>

</body></html>


 

여러 개의 문서 객체 가져오는 방법

- document 객체의 getElementById( )메서드는 한 번에 한 가지 문서 객체만 가져올 수 있음
- 아래 메서드를 이용해서 여러 개의 객체를 가져올 수 있음

 

getElementsByName(name) : 태그의 name 속성이 name과 일치하는 문서 객체를 배열로 가져온다.

getElementsByTagName(tagname) : tagName과 일치하는 문서 객체를 배열로 가져온다.

 

<!DOCTYPE html>
<html lang="">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {
            
            // 태그이름으로 문서객체 생성 > 배열로 반환
            var divs = document.getElementsByTagName('div'); // div 아래두개모두선택
            divs[0].innerHTML='By tagname - 0 ';
            divs[1].innerHTML='By tagname - 1 ';

        };
    </script>

</head>

<body>

    <div id="header-1">1</div>
    <div id="header-2">2</div>

</body></html>


 

HTML 5에서 추가된 메서드

querySelector / querySelectorAll 예제1)

<!DOCTYPE html>
<html lang="">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {
			// CSS의 선택자로 선택할수 있는 메소드
			
            
            var div1 = document.querySelector('div'); // 가장 첫번째거 가져옴.
            alert(div1.innerHTML) // 1
            
            var divs = document.querySelectorAll('div');
            alert(divs[0].innerHTML+' : querySelectorAll'); // 1 : que~


        };
    </script>

</head>

<body>

    <div id="header-1">1</div>
    <div id="header-2">2</div>

</body></html>


 

querySelector / querySelectorAll 예제2)

<!DOCTYPE html>
<html lang="">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {


            var input = document.querySelector('input[type=button]');
            alert(input.value);

            var input2 = document.querySelector('input[type=text]');
            alert(input2.value);

        };
    </script>

</head>

<body>

    <input type="button" value="네이버로 이동" id="go_naver_btn">
    <input type="text" value="텍스트">

</body></html>

 

 

querySelector / querySelectorAll 예제3)

> 유효성 검사

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Window Object</title>

    <script>

        window.onload = function() {
            document.getElementById('go_naver_btn').onclick = function() {

                var userid = document.querySelector('#userid');

                var uid = userid.value;

                if (uid.length < 1) {
                    alert('아이디는 필수 입력항목입니다.');
                } else {
                    alert('사용자가 입력한 아이디는 ' + userid.value + '입니다.');
                }

            };

        };
    </script>
    <style>

    </style>

</head>

<body>

    <input type="text" value="test" id="userid">
    <br>
    <input type="button" value="확인" id="go_naver_btn">



</body></html>

 

 

 

문서 객체 생성


정적으로 문서 객체를 생성 : 처음 HTML 페이지에 적혀 있는 태그들을 읽으며 생성
- 동적으로 문서 객체를 생성 : 자바스크립트로 원래 HTML 페이지에는 없던 문서 객체를 생성

 

createElement(tagName) > 요소 노드를 생성

createTextNode(text)      > 텍스트 노드 생성

appendchild(node))        > 객체에 노드를 연결

 

텍스트 노드를 갖는 문서 객체

*<h1></h1>이 body에 생성됨 (createElement)

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>
    
    <script>
    
    
        window.onload = function(){
            
            // 태그 요소 생성
            var header = document.createElement('h1');
            
            // 텍스트 요소 생성
            
            // 태그 요소에 텍스트 요소 추가
            
            // 새로운 문서객체를  body 요소에 추가
            document.body.appendChild(header);
        }
    </script>
    
</head>

<body>
    
</body>
</html>

 

 

 

 

*<h1></h1> 사이에 하이! 뽀선뽀선!을 넣어줌 (createtextNode)

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>
    
    <script>
    
    
        window.onload = function(){
            
            // 태그 요소 생성
            var header = document.createElement('h1');
            
            // 텍스트 요소 생성
            var textNode = document.createTextNode('하이! 뽀선뽀선!');
            // 태그 요소에 텍스트 요소 추가
            header.appendChild(textNode);
            
            // 새로운 문서객체를  body 요소에 추가
            document.body.appendChild(header);
        }
    </script>
    
</head>

<body>
    
</body>
</html>

 

 

 

텍스트가 없는 요소 : img

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {


            // 텍스트가 없는 요소 : img
            var img = document.createElement('img');
            document.body.appendChild(img);
        }
    </script>

</head>

<body>

</body>

</html>

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {


            // 텍스트가 없는 요소 : img
            var img = document.createElement('img');
            img.src = 'tae6.jpg';
            img.width = 300; //px
            img.height = 300;
            document.body.appendChild(img);
        }
    </script>

</head>

<body>

</body>

</html>

 

두개 합친 것! TEST

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {
                        
            // 태그 요소 생성
            var header = document.createElement('h1');
            
            // 텍스트 요소 생성
            var textNode = document.createTextNode('하이! 뽀선뽀선!');
            // 태그 요소에 텍스트 요소 추가
            header.appendChild(textNode);
            
            // 새로운 문서객체를  body 요소에 추가
            document.body.appendChild(header);


            // 텍스트가 없는 요소 : img
            var img = document.createElement('img');
            img.src = 'tae6.jpg';
            img.width = 300; //px
            img.height = 300;
            document.body.appendChild(img);
            
            //밑에 있는 h1에 추가한다
            document.getElementById('pposeon').appendChild(img);
        }
    </script>

</head>

<body>
    
    <h1 id="pposeon">새로운 문서객체를 추가합니다.</h1>

</body>

</html>

// 하이 뽀선뽀선은 바디에 추가된것 > document.body.appendChild(header);

 

 

 

텍스트 노드를 갖지 않는 문서 객체 / 속성 지정

 

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>문서객체 동적 생성</title>

    <script>
        window.onload = function() {
            var pposeon = document.getElementById('pposeon');
            console.log('h1#pposeon id->', pposeon.getAttribute('data-brackets-id')); //1087

            var link = document.getElementById('link_naver');

            // text 노드 생성 
            //var str = document.createTextNode('-' + link.getAttribute('href')); // 아래랑 같음
            var str = document.createTextNode('-' + link.href);
            link.appendChild(str);

            
            
          	// 속성 지정
            var img1 = document.createElement('img');
            img1.setAttribute('src', 'tae6.jpg');
            img1.setAttribute('width', 200);
            img1.setAttribute('height', 200);
            document.body.appendChild(img1);
            
            

        };
    </script>

</head>

<body>

    <h1 id="pposeon">새로운 문서객체를 추가합니다.</h1>

    <a href="http://www.naver.com" id="link_naver"> 네이버 </a>

</body></html>

 

 

innerHTML과 textContent의 차이.

            pposeon.innerHTML = '<i>안녕하세요</i>';
            alert(pposeon.innerHTML);
            alert(pposeon.textContent);
            // html 인식이 아닌 순수한 문자로 인식
            pposeon.textContent = '<i>안녕하세요</i>';

window 객체의 로드 완료
- window 객체 로드가 완료되는 때는?

-> HTML 페이지에 존재하는 모든 태그가 화면에 올라가는 순간이 로드가 완료되는 순간

 onload를 사용한 경우

1) [ 1 ] 창뜨고 

2) 변경1 뜨면서 [ 2 ] 창 뜨고

3) 변경2가 출력

// onload가 아래쪽 body를 먼저 실행시켜준다.

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>실행순서</title>

    <script>
    window.onload = function(){
        alert(2);
        var h1 = document.getElementById('h1');
        console.log('h1->', typeof(h1));
        h1.innerHTML = '변경2';
      };
    </script>

</head>

<body>

    <h1 id="h1">h1 태그가 생성 되었습니다.</h1>
    <script>
        alert(1);
        var h1 = document.getElementById('h1');
        console.log('h1!!!!!!->', typeof(h1));
        h1.innerHTML = '변경1';
    </script>

</body></html>


 

onload를 사용하지 않은 경우

1) [ 2 ] 창 뜨고

2) [ 1 ] 창 뜨고

3) 변경1

// 위에서부터 순서대로 실행된다 

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>실행순서</title>

    <script>
//    window.onload = function(){
        alert(2);
        var h1 = document.getElementById('h1');
        console.log('h1->', typeof(h1));
        h1.innerHTML = '변경2';
//      };
    </script>

</head>

<body>

    <h1 id="h1">h1 태그가 생성 되었습니다.</h1>
    <script>
        alert(1);
        var h1 = document.getElementById('h1');
        console.log('h1!!!!!!->', typeof(h1));
        h1.innerHTML = '변경1';
    </script>

</body></html>

onload가 없어서 h1을 불러오지 못해서(?) 에러남!

 

1) 윈도우 객체확인

 

        var output = '';
        for (var key in window) {
            output += '[' + key + '] : ' + window[key] + '<br><br>';

        }

        window.onload = function() {
            document.body.innerHTML = output;
        };
        //console.log(window);

 

2) 네이버 창이 정해진 사이즈로 열리고, 글씨를 클릭하면 닫힌다.

open(URL, name, features, replace)

 

        window.onload = function() {
            //윈도우생성
            window.open();
            window.open('http://naver.com', 'newWin',
                'width=600, height=300', true);
            var child = window.open('', 'child', 'width=300, height=200');

            child.document.write('<h1 onclick="self.close();">From Parent window</h1>');
        };

 

3) 여러가지 객체 확인

        window.onload = function() {
            // 스크린객체
            // f12 누르고 보면 가로세로 길이 이런거나옴
            console.log(screen);
            // 로케이션 객체 확인
            console.log(location);           
            // 네비게이터 객체 확인
            console.log(navigator);
    
        };

 

# chapter08_02
# 파이썬 외장 (External)함ㅅ
# 실제 프로그램 개발 중 자주 사용
# 종류 : sys. pickle, shutil, temfile, time, randome 등

# 예제1
import sys
print(sys.argv) #sys.argv라고 구글에 검색해보면 좋다.


# 예제2 (강제종료)
# sys.exit()

# 예제3 (파이선 패키지 위치)
print(sys.path)


#pickle : 객체 파일 읽기, 쓰기
import pickle

# 예제4(쓰기)

f = open("test.obj", 'wb')
obj = {1:'python',2:'study', 3:'basic'}
pickle.dump(obj,f)
f.close()


# 예제5(열기)

f = open('test.obj', 'rb')
data = pickle.load(f)
print(data, type(data))
f.close()


# os : 환경변수, 디렉토리(파일) 처리 관련, 운영체제 작업 관련
# mkdir, rmdir(비어있으면 삭제), rename,

# 예제6
import os
print(os.environ)
print(os.environ["USERNAME"])
print(os.environ["ATOM_HOME"])

# 예제7 (현재 경로)
print(os.getcwd())


# time : 시간 관련 처리.
import time

# 예제8
print(time.time())

# 예제9 형태변환
print(time.localtime(time.time()))

# 예제10 (간단 표현)
print(time.ctime())

# 예제11 (형식 표현)
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

# 예제12 (시간 간격 발생)
# for i in range(5) :
#     print(i)
#     time.sleep(1) #1초마다 실행하겠다는 뜻

# random : 난수 리턴
import random

# 예제13
print(random.random()) #0~1 실수

# 예제14
print(random.randint(1,45))
print(random.randrange(1,45))

# 예제15(섞기)
d=[1,2,3,4,5]
random.shuffle(d)
print(d)

# 예제16 (무작위 선택)
c = random.choice(d)
print(c)

# webbrowser : 본인 os의 웹 브라우저 실행
import webbrowser

webbrowser.open("http://naver.com")
webbrowser.open_new("http://naver.com")

docs.python.org/ko/3.9/library/functions.html

 

내장 함수 — Python 3.9.1rc1 문서

내장 함수 파이썬 인터프리터에는 항상 사용할 수 있는 많은 함수와 형이 내장되어 있습니다. 여기에서 알파벳 순으로 나열합니다. abs(x) 숫자의 절댓값을 돌려줍니다. 인자는 정수, 실수 또는 __

docs.python.org

 

# Chapter08-1
# 파이썬 내장(Built-in) 함수
# 자주 사용하는 함수 위주로 실습
# 사용하다보면 자연스럽게 숙달
# str(), int(), tuple() 형변환 이미 학습

# 절대값
# abs()

print(abs(-3))

# all, any : iterable 요소 검사(참, 거짓)
print(all([1,2,3])) # and
print(any([1,2,0])) # or

# chr : 아스키 -> 문자 , ord : 문자 -> 아스키

print(chr(67))
print(ord('C'))

# enumerate : 인덱스 + Iterable 객체 생성
for i, name in enumerate(['abc', 'bcd', 'efg']):
    print(i, name)


#  filter : 반복가능한 객체 요소를 지정한 함수 조건에 맞는 값 추출

def conv_pos(x):
    return abs(x) > 2
    
print(list(filter(conv_pos, [1, -3, 2, 0, -5, 6])))
print(list(filter(lambda x: abs(x) > 2, [1, -3, 2, 0, -5, 6])))

# id : 객체의 주소값(레퍼런스) 반환

print(id(int(5)))
print(id(4))

# len : 요소의 길이 반환
print(len('abcdefg'))
print(len([1,2,3,4,5,6,7]))

# max, min : 최대값, 최소값

print(max([1,2,3]))
print(max('python study'))
print(min([1,2,3]))
print(min('python study'))

# map : 반복가능한 객체 요소를 지정한 함수 실행 후 추출
def conv_abs(x):
    return abs(x)
    
print(list(map(conv_abs,[1,-3,2,0,-5,6])))
print(list(map(lambda x:abs(x),[1,-3,2,0,-5,6])))

# pow : 제곱값 반환
print(pow(2,10))

# range : 반복가능한 객체(Iterable) 반환
print(list(range(1,10,2))) # 1 3 5 7 9
print(list(range(0,-15,-1))) # 0 ~ -14

# round : 반올림

print(round(6.5781, 2))
print(round(5.6))

# sorted : 반복가능한 객체(Iterable) 정렬 후 반환 

print(sorted([6,7,4,3,1,2]))
a = sorted([6,7,4,3,1,2])
print(a)
print(sorted(['p','y','t','h','o','n']))


# sum : 반복가능한 객체(Iterable) 합 반환
print(sum([6,7,8,9,10]))
print(sum(range(1,101)))

# type : 자료형 확인

print(type(3))
print(type({}))
print(type(()))
print(type([]))

# zip : 반복가능한 객체(Iterable)의 요소를 묶어서 반환

print(list(zip([10,20,30],[40,50,777]))) #짝이 맞지 않으면 반환되지않음 3:2 면 2개만.
print(type(list(zip([10,20,30],[40,50,777]))[0]))

'python_basic' 카테고리의 다른 글

[파이썬] csv 파일쓰기 / 읽기  (0) 2020.11.30
[파이썬] 파일읽기 / 쓰기  (0) 2020.11.30
[파이썬] 외장함수  (0) 2020.11.30
[파이썬] 예외처리 Exception / try - except - else - finally  (0) 2020.11.30
[파이썬] 패키지 / init  (0) 2020.11.23
[파이썬] 모듈  (0) 2020.11.23
[파이썬] 클래스  (0) 2020.11.23
# chapter07-01
# 파이썬예외처리의 이해
# 예외종류
# syntax, type, name, index, value, key..error
# 문법적으로는 틀리지 않았지만, 코드실행 프로세스(단계) 발생하는 예외도 중요

# 1. 예외는 반드시 처리
# 2. 로그는 반드시 남긴다.
# 3. 예외는 던져진다.
# 4. 예외 무시.


# syntaxError / 문법 오류.
# print('error) / print('error'))


# nameError / 참조 없음
# a=10
# b=15
# pring(c)

# ZeroDivisionError
# print(100/0)

#IndexError
x=[50,70,90]
print(x[1])
# print(x[4])


# KeyError
dic={'name' :'Lee' , 'age' : 41, 'city':'busan'}
# print(dic['hobby'])

# 예외가 없는 것을 가정하고 프로그램을 작성 > 런타임 예외 발생 시 예외 처리 권장(EAFP)


# AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용 예외
import time
# print(time.time2()) time2는 없다


# ValueError

x = [10,50,90]
x.remove(50)
print(x)
# x.remove(200)

# FileNotFoundError
# f = open('text.txt') 파일 없음 에러.


# TypeError : 자료형에 맞지 않는 연산 수행할 경우
x = [1,2]
y = (1,2)
z = 'test'
# print(x+y)
print(x+list(y))


# 예외처리 기본
# try : 에러가 발생할 가능성이 있는 코드 실행
# except 에러명1 : 여러개 가능
# except 에러명2 :
# else : try 블록의 에러가 없을 경우 실행
# finally : 항상 실행.


name = ['kim', 'lee', 'park']

# 예제1

try :
    z = 'kim' #'Cho' 예외처리가 된다.
    x = name.index(z)
    print('{} Found it {} in name'.format(z,x+1))
except   ValueError :
    print('not fount it = occurred ValueError!')
else :
    print('ok! else.')

print()


# 예제2

try :
    z = 'kim' #'Cho' 예외처리가 된다.
    x = name.index(z)
    print('{} Found it {} in name'.format(z,x+1))
except : # except Exception : 와 같다.
    print('not fount it = occurred')
else :
    print('ok! else.')

print()


# 예제3

try :
    z = 'cho' #'Cho' 예외처리가 된다.
    x = name.index(z)
    print('{} Found it {} in name'.format(z,x+1))
except Exception as e :
    print(e) #'cho' is not in list
    print('not fount it = occurred')
else :
    print('ok! else.')
finally :
    print('ok! finally!')

print()


# 예제4
# 에외 발생 : raise
# raise 키워드로 예외 직접 발생

try :
    a = 'park'
    if a == 'kim' :
        print('Ok! pass')
    else :
        raise ValueError #강제로 발생시키는에러.
except ValueError :
    print('Occurred! Exception!')
else :
    print('OK! else.')

'python_basic' 카테고리의 다른 글

[파이썬] 파일읽기 / 쓰기  (0) 2020.11.30
[파이썬] 외장함수  (0) 2020.11.30
[파이썬] 내장함수  (0) 2020.11.30
[파이썬] 패키지 / init  (0) 2020.11.23
[파이썬] 모듈  (0) 2020.11.23
[파이썬] 클래스  (0) 2020.11.23
[파이썬] 사용자로부터 입력받기 / input  (0) 2020.11.23

+ Recent posts