PowerPoint 프레젠테이션

Similar documents
슬라이드 1

PowerPoint 프레젠테이션

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

Microsoft PowerPoint - C++ 5 .pptx

OCW_C언어 기초

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

Microsoft PowerPoint - [2009] 02.pptx

JAVA PROGRAMMING 실습 02. 표준 입출력

C# Programming Guide - Types

17장 클래스와 메소드

C프로-3장c03逞풚

02 C h a p t e r Java

8장 문자열

쉽게 풀어쓴 C 프로그래밍

C++ Programming

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

PowerPoint Presentation

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - chap04-연산자.pptx

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

PowerPoint 프레젠테이션


Microsoft PowerPoint - Java7.pptx

PowerPoint Presentation

chap10.PDF

1

PowerPoint Template

컴파일러

Microsoft PowerPoint - additional01.ppt [호환 모드]

Microsoft PowerPoint - chap06-2pointer.ppt

Multi-pass Sieve를 이용한 한국어 상호참조해결 반-자동 태깅 도구

Design Issues

PowerPoint 프레젠테이션

C 언어 프로그래밊 과제 풀이

Modern Javascript

Multi-pass Sieve를 이용한 한국어 상호참조해결 반-자동 태깅 도구

SIGPLwinterschool2012

PowerPoint 프레젠테이션

Microsoft PowerPoint - C프로그래밍-chap03.ppt [호환 모드]

C++ Programming

02장.배열과 클래스

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202839C1D6C2F7207E203135C1D6C2F >

쉽게

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

10 강. 쉘스크립트 l 쉘스크립트 Ÿ 쉘은명령어들을연속적으로실행하는인터프리터환경을제공 Ÿ 쉘스크립트는제어문과변수선언등이가능하며프로그래밍언어와유사 Ÿ 프로그래밍언어와스크립트언어 -프로그래밍언어를사용하는경우소스코드를컴파일하여실행가능한파일로만들어야함 -일반적으로실행파일은다

금오공대 컴퓨터공학전공 강의자료

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

슬라이드 1

OCaml

쉽게 풀어쓴 C 프로그래밍

다른 JSP 페이지호출 forward() 메서드 - 하나의 JSP 페이지실행이끝나고다른 JSP 페이지를호출할때사용한다. 예 ) <% RequestDispatcher dispatcher = request.getrequestdispatcher(" 실행할페이지.jsp");

Tcl의 문법

프로그래밍개론및실습 2015 년 2 학기프로그래밍개론및실습과목으로본내용은강의교재인생능출판사, 두근두근 C 언어수업, 천인국지음을발췌수정하였음

01-OOPConcepts(2).PDF

JVM 메모리구조

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

유니티 변수-함수.key

APCPCWM_ :WP_GLOBAL_PFWP_GLOBAL_PF APCPCWM_ :WP_GLOBAL_PFWP_GLOBAL_PF 예제로보는 네트워크엔지니어를위한 Python 101

초보자를 위한 C++

Java ...

PowerPoint Presentation

Microsoft PowerPoint - Chapter_04.pptx

Microsoft PowerPoint - chap-03.pptx

슬라이드 1

목차 BUG 문법에맞지않는질의문수행시, 에러메시지에질의문의일부만보여주는문제를수정합니다... 3 BUG ROUND, TRUNC 함수에서 DATE 포맷 IW 를추가지원합니다... 5 BUG ROLLUP/CUBE 절을포함하는질의는 SUBQUE

untitled

adfasdfasfdasfasfadf

Microsoft PowerPoint - chap03-변수와데이터형.pptx

11장 포인터

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

DE1-SoC Board

PowerPoint 프레젠테이션

Microsoft PowerPoint - ch07 - 포인터 pm0415

PowerPoint 프레젠테이션

1. auto_ptr 다음프로그램의문제점은무엇인가? void func(void) int *p = new int; cout << " 양수입력 : "; cin >> *p; if (*p <= 0) cout << " 양수를입력해야합니다 " << endl; return; 동적할

설계란 무엇인가?

PowerPoint Presentation

Microsoft PowerPoint - chap-05.pptx

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate

PowerPoint Presentation

歯9장.PDF

Microsoft PowerPoint - chap05-제어문.pptx

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

Microsoft PowerPoint - e pptx

Microsoft PowerPoint - 04-UDP Programming.ppt

DocsPin_Korean.pages

ePapyrus PDF Document

TEST BANK & SOLUTION

예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = B = >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = >> tf = (A==B) % A

3장 함수

슬라이드 1

PowerPoint 프레젠테이션

slide2

Microsoft PowerPoint 세션.ppt

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100

EndNote X2 초급 분당차병원도서실사서최근영 ( )

Javascript.pages

13주-14주proc.PDF

Transcription:

Chapter 1 변수, 자료형, 예약어, 연산자, 숫자형자료형 2014. 5. 22

Python 이란? Guido Van Rossum http://www.python.org/~guido/ http://www.python.org/doc/essays/foreword/ 연구실문이닫혀있는 1989 년크리스마스기간에 무료한시간을보내기위하여새로운스크립트언어를만들게됨 ABC 라는언어에기반해서작성됨 특징 명료하고읽기쉬운문법 대화형인터프리터언어 Object Oriented Programming(OOP) Language high level 동적데이터타입결정지원 메모리자동관리 다른언어 (C, C++, JAVA,.NET, R, ) 와의확장성 다양한라이브러리제공 무료 성공사례 Google Groups/Maps, Gmail, YouTube, NASA, Yahoo!, Naver, Daum, 다수의 IT 기관및연구기관

명료하고읽기쉬운문법 명료하고읽기쉬운문법 C++ ( hello.cpp ) #include <iostream> using namespace std; int main() { } cout << "Hello World!" << endl; return 0; JAVA ( Hello.java ) public class Hello { public static void main( String[] args ) { System.out.println("Hello world!"); } } Python ( hello.py ) print "Hello world!"

Python 은대화형인터프리터언어 실행결과 실행결과 chanchan-ui-mac-pro:~ chanchan$ python Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello World 명령입력 Hello World >>> for i in range(1,10):... print 2*i, 명령입력... 2 4 6 8 10 12 14 16 18 >>> >>> 프롬프트 (prompt) : 명령입력대기중임을나타낸다.

High Level 동적데이터타입결정지원 >>> def add(a, b):... return a+b 숫자... Type >>> print add(1, 2) 3 >>> print add(bit', EC') BITEC >>> print add([1,2,3], [4,5,6]) [1, 2, 3, 4, 5, 6] 문자 Type List Type return a+b 에서 a 와 b 에맞는 + method 를자동으로호출함

메모리자동관리 C 나 C++ 같은언어는메모리관리책임이개발자에게달려있음. 약간의수정에도항상메모리관리를점검해야함. 의도치않은에러발생확률높음. Python 에서는 Garbage Collection 기능을이용하여메모리관리를함. 필요시자동으로메모리를자동할당 사용이끝나면자동을사용해제

다른언어와의확장성 > x <- c(5.05, 6.75, 3.21, 2.66) > y <- c(1.65, 26.5, -5.93, 7.96) > z <- c(1.65, 2.64, 2.64, 6.95) > cor(x, y, method="spearman") [1] 0.4 > cor(x, z, method="spearman") [1] -0.6324555 현재는작동하지않는코드입니다. 타이핑하지마십시오. R cor 함수를이용해상관계수구하기 >>> import rpy Python 에서 rpy 모듈을사용하여 >>> x = [5.05, 6.75, 3.21, 2.66] R cor 함수를호출 >>> y = [1.65, 26.5, -5.93, 7.96] >>> z = [1.65, 2.64, 2.64, 6.95] >>> print rpy.r.cor(x, y, method="spearman") 0.4 >>> print rpy.r.cor(x, z, method="spearman") -0.632455532034

풍부한라이브러리예 ) BioPython 을이용해 PubMed 문헌 search/retrieve #!/usr/bin/python from Bio import Entrez from Bio import Medline BioPython 모듈불러오기 handle = Entrez.esearch( db="pubmed", term="type 2 Diabetes korean ", retmax=3 ) record = Entrez.read( handle ) idlist = record["idlist"] handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text") records = Medline.parse(handle) 키워드 Type 2 Diabetes korean 으로 PubMed 문헌검색후 PubMed ID 3 개만가져옴 가져온 PubMed ID 를이용하여 MedLine Text 를가져옴 for record in records: print "PubMed ID : ", record.get("pmid", "?") print "TITLE: ", record.get("ti", "?") print "ABSTRACT: ", record.get("ab", "?") PubMed ID, Title, Abstract 를출력 결과 총 12 줄짜리프로그램 PubMed ID : 23091317 TITLE: Association between Total Bilirubin and Hemoglobin A1c in Korean Type 2 Diabetic Patients. ABSTRACT: Recent studies have shown that bilirubin is negatively associated 생략 현재는작동하지않는코드입니다. PubMed ID : 23091316 TITLE: Association between Nutrient Intake and Obesity in Type 2 Diabetic 타이핑 Patients 하지 from the 마십시오 Korean National. Diabetes Program: A Cross-Sectional Study. ABSTRACT: The aim of the study was to assess the association between usual dietary nutrient 생략 PubMed ID : 23076296 TITLE: The prevalence and risk factors of vertebral fractures in Korean patients with type 2 diabetes. ABSTRACT: Although type 2 diabetes mellitus (T2DM) has been associated with an increase in fracture risk, there is no data regarding the prevalence of vertebral fractures or its risk factors for patients with T2DM in.. 생략

간단한실습 >>> 2 + 4 6 >>> ( 4 + 6 ) * 2 20 >>> 11 / 3 3 >>> 11 / 3. 3.6666666666666665 >>> 11 % 3 2 >>> divmod(11, 3) (3, 2) >>> a, b = divmod(11, 3) >>> a 3 >>> b 2 >>> 3.4e4 34000.0 >>> 3.4e-4 0.00034000000000000002 >>> 2**3 8 정수 / 정수 = 정수정수 / 실수 = 실수실수 / 실수 = 실수 정수 / 정수형에서제대로된계산결과를얻기위해 3. 이라고표시하여 3 이라는숫자를실수형으로인식 % 나머지연산자 divmod(a, b) a 를 b 로나눴을때몫과나머지를계산해주는함수 (function) 3.4e4 : 3.4 곱하기 10 의 4 승 3.4e-4 : 3.4 곱하기 10 의 -4 승 2**3 : 2 의 3 승

작성한프로그램저장 1. File Click 2. New Window Click 3. 새윈도우창에앞에서작성한계산을입력 5. first_code.py 라고타이핑후저장 4. File -> Save 클릭 주의 : 저장시저장경로는현재사용자가쓰기권한이있는디렉토리여야합니다.

작성한프로그램실행 1. Run 선택후 Run Module 로실행 2. 아무런결과도나오지않는다??? 3. 출력하고하는부분에 print 구문을추가이는 idle 뿐아니라다른에디터프로그램을사용하여출력할시에도동일함 4. Bingo!!!

Indentation ( 들여쓰기 ) (1/2) >>>a = 1 >>> a = 1 한칸공란이있음 File "<pyshell#5>", line 1 a = 1 ^ IndentationError: unexpected indent Indentation( 들여쓰기 ) : 명령입력시첫컬럼부터시작해야한다. 그렇지않으면 indentation error 가나게된다. Python 은들여쓰기를엄격하게지키는언어이다.

Indentation ( 들여쓰기 ) (2/2) import MySQLdb db= MySQLdb.connect(host="localhost", user="python-test", passwd="python",db="python-test") cursor = db.cursor();stmt = "SELECT * from books" cursor.execute(stmt);rows = cursor.fetchall () for row in rows: print "Row: ;; for col in row : print "Column: %s" % (col); print "End of Row" print "Number of rows returned: %d" % cursor.rowcount cursor.close(); db.close() import MySQLdb Indentation 을지키지않으면 Syntax error 를일으킬뿐아니라소스코드를읽기조차힘들어진다. db= MySQLdb.connect(host="localhost", user="python-test", passwd="python", db="python-test") cursor = db.cursor() stmt = "SELECT * from books" cursor.execute(stmt) rows = cursor.fetchall () for row in rows: print "Row: " for col in row : print "Column: %s" % (col) print "End of Row" print "Number of rows returned: %d" % cursor.rowcount 현재는작동하지않는코드입니다. 타이핑하지마십시오. cursor.close() db.close()

Syntax Error vs. Logical Error Syntax Error 스펠링이나문법이틀려서나는에러 실행시출력되는에러메시지를이용하여에러검출이가능 Logical Error Syntax Error 은전혀없으나논리상오류가나는에러종류 찾아내기쉽지않은에러형태. >>> prin "Hello Python" File "<stdin>", line 1 prin "Hello Python" ^ SyntaxError: invalid syntax 예 )Syntax error >>> result = '' >>> grade = 95 >>> if grade >= 90:... result = 'F'... >>> print result F 예 ) Logical error

변수 (variable) 알려진또는알려지지않은어떤값 (value) 을담는저장공간 (Storage location) 과 그에상응하는심볼릭이름 (symbolic name) 을의미 >>> a = 1 >>> string_test = Python variable Value = 치환연산자 (assignment operator) 오른쪽항의값을왼쪽으로치환 a 1 string_test = Python string_test Python Python 이란값 (value) 을 string_test 란변수 (variable) 로치환 >>> a = 1 >>> a = a + 1 >>> a 2 >>> a 라는변수에 1 이라는값을할당한다. a 라는변수에 1 이라는값을더한후결과를 다시 a 라는변수에할당한다.

변수선언 첫문자가 underscore(_) 또는영문자 두번째문자부터는영문자, 숫자, underscore 가올수있음. 크기에는제한이없음 [a-za-z_][a-za-z-0-9_]* 사용가능한예 a, input_str, MyVar, _private_string, 변수명이될수없는예 5public, @email, %var,. 변수명은대소문자를구분. 예 ) Email 과 email 은다른변수 >>> @email = 'chanchan@snu.ac.kr' SyntaxError: invalid syntax >>> email = 'chanchan@snu.ac.kr >>> Email = 'test@test.com' >>> email = 'chanchan@snu.ac.kr' >>> Email 'test@test.com' >>> email 'chanchan@snu.ac.kr' 변수선언규칙에맞지않는다. 변수명은대소문자를구분한다.

예약어는변수명으로사용할수없다. Python 에서이미쓰고있는예약어 (reserved words or keywords ) 는변수명으로사용할수없다. Python 에서사용하는예약어 and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue is return def finally for lambda try >>> from = 10 SyntaxError: invalid syntax # 예약어확인하기 >>> import keyword >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] >>> import : 가져오기 / 들여오기 다른사람이만든또는본인이만든데이터 / 프로그램을읽어들이는행위

내장함수 (built-in functions) 이름을변수명으로사용하면생기는문제 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() import () complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern() >>> divmod <built-in function divmod> >>> divmod(10,3) (3, 1) >>> divmod = 'Division and Modulus' >>> divmod(10, 3) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> divmod(10, 3) TypeError: 'str' object is not callable >>> http://docs.python.org/2/library/functions.html divmod 는문자형변수로바뀌었고더이상함수가아니다. 문자형변수에함수형태의값을입력하기때문에에러가발생한다.

변수명의좋은예와나쁜예 >>> a = 160.4 >>> aa = 71.1 >>> print a, aa 160.4 71.1 >>> >>> height = 160.4 >>> weight = 71.1 >>> print height, weight 160.4 71.1 >>> x = 90 >>> xx = 77 >>> xxx = 93 >>> y = x + xx + xxx >>> y / 3. 86.66666666666667 >>> english = 90 >>> mathematics = 77 >>> computer = 93 >>> total = english + mathematics + computer >>> total / 3. 86.66666666666667 잘명명한변수명은코드를다시들여다보는본인뿐아니라코드를보는다른사람들도행복하게만듭니다.

코드에주석달기 주석 (comment) 은 # 문자를이용하여달수있음. 주석처리된부분은프로그램실행시영향을미치지않음. >>> # The score of english >>> english = 90 >>> # The score of math. >>> mathematics = 77 >>> # The score of computer >>> computer = 93 >>> # The total score of english, math and computer >>> total = english + mathematics + computer >>> # Average score >>> total / 3. 86.66666666666667 >>> total / 3. # Average Score total/3. 86.66666666666667 Total / 3. 까지의결과만나오고 # 이후의내용은무시함

자료형 (Data Type) 프로그램에서표현또는저장하는데이터의유형. 컴퓨터로표현할수있는자료의종류 Python 에서는다른언어에서제공하지않는고수준의자료형이존재 자료형설명예 수치형 (Numbers) 정수, long 형정수, 실수, 복소수등을표현 123, 12345L, 1.43, 5+4j 문자열 (Strings) 문자들의모임 BITEC, Python, BITEC Python 리스트 (Lists) 순서를가지는 python 객체의집합 [ BITEC, Python ] 사전 (Dictionary) 순서를가지지않는객체의집합. 키 (key) 와값 (value) 으로구성됨 { BITEC : 1, Python :2 } 튜플 (Tuples) 순서를가지는 python 객체의집합. 순서변경이안됨 ( BITEC, Python ) 파일 (Files) 파일에자료를입출력하기위한객체 fp = open( BITEC.txt )

>>> variable = 1 >>> type(variable) <type 'int'> >>> variable = 3.141592 >>> type(variable) <type 'float'> >>> variable = "BITEC" >>> type(variable) <type 'str'> >>> variable = ['BITEC', 'Python'] >>> type(variable) <type 'list'> dict : 딕셔너리형 tuple : 튜플형 file : 파일형 type 함수는객체의자료형을알려준다. int : 정수형 float : 실수형 str : 문자형 list : 리스트형 >>> variable = { 'BITEC':1, 'Python':2 } >>> type(variable) <type 'dict'> >>> variable = ('BITEC', 'Python') >>> type(variable) <type 'tuple'> >>> fp = open("c:\bitec_python\ch1\hello.py") >>> type(fp) <type 'file'>

수치자료형 (1/2) 수치자료형 정수형 (int), 실수형 (float), 롱형 (long), 복소수형 (complex) 이있다. 정수형상수 수치표현범위 : -2,147,483,648~2,147,483,647(32bit인경우 ) # 32bit OS >>> maxint = 2**31-1 >>> maxint 2147483647L >>> -maxint - 1-2147483648L >>> import sys >>> sys.maxint 2147483647 # 64bit OS >>> import sys >>> sys.maxint 9223372036854775807 >>> 2**63-1 9223372036854775807L 32/64bit OS 에따라최대표현범위가다르다. 롱형상수 정수형으로표현할수없는큰수는자동으로롱형정수로표현 롱형상수는정수수치마지막에 l, 혹은 L 을붙여서표현 유효자리 : 메모리가허용하는한무한대. #32bit OS >>> 12345678987654321 12345678987654321L # 32bit OS >>> print 12345678987654321 12345678987654321 #64bit OS >>> 1234567890987654321 1234567890987654321 정수형의최대표현범위를넘기면자동으로 L 이붙는다. print 문을사용하면 L 이붙지않는다 정수형의최대표현범위를넘지않았으므로 L 이붙지않는다.

수치자료형 (2/2) 실수형 소수점을포함하거나 e 나 E 로지수를포함 범위 : 10 의 -308 승 ~ + 308 승 >>> a = 4.5 >>> b = 3.5e3 >>> c = -0.3e-4 >>> print a, b, c 4.5 3500.0-3e-05 복소수형 실수부 + 허수부로나뉨 허수부에는 j 나 J 를붙여야함 >>> import sys >>> sys.float_info.max 1.7976931348623157e+308 real : 실수부 conjugate(): 켤레복소수 >>> c = 5 + 8j >>> d = 2-6j >>> c + d (7+2j) >>> c.real 5.0 >>> c.imag 8.0 >>> c.conjugate() (5-8j) imag : 허수부

math 모듈 >>> import math >>> math.sqrt(16) 4.0 >>> math.exp(3) 20.085536923187668 >>> math.log(10) 2.3025850929940459 >>> math.log10(10) 1.0 >>> math.pi 3.1415926535897931 >>> math.e 2.7182818284590451 math 모듈불러오기 math.sqrt() : 제곱근 math.exp() : 지수 math.log() : 자연로그 ( base 가 e ) math.log10() : 자연로그 ( base 가 10 ) math.pi : pi 값 math.e : e 값 math.fabs() : 절대값 round : 반올림함수 ( 내장형함수임 ) >>> math.fabs(-11.5) 11.5 >>> round(3.54) 4.0 Built-in 함수

수치연산자 +( 덧셈 ), -( 뻴셈 ), *( 곱셈 ) /( 나눗셈 ), **( 지수승 ), %( 나머지 ) 정수형을다른정수형과연산하면결과는언제나정수형 정수형과다른실수형을연산하면결과는언제나실수형 >>> 4 + 6 # 정수 + 정수 10 # 결과는정수 >>> 4 + 6.0 # 정수 + 실수 10.0 # 결과는실수 >>> 6 / 4.0 # 정수 / 실수 1.5 # 결과는실수 >>> 6 / 4 # 정수 / 정수 1 # 결과는정수

수치연산자의우선순위 우선순위높음 우선순위낮음 연산자 설명 결합순서 () 괄호 왼쪽 오른쪽 +, - 단항연산자 ( 예. -5, +4) 오른쪽 왼쪽 ** 지수 오른쪽 왼쪽 *, /, % 곱하기, 나누기, 나머지 왼쪽 오른쪽 +, - 더하기, 빼기 왼쪽 오른쪽 >>> 3 * -2-6 >>> 2 + 3 * 4 14 >>> ( 2 + 3 ) * 4 20 >>> 4 / 2 * 2 4 >>> 4 / ( 2 * 2 ) 1 >>> 2 ** 3 ** 4 2417851639229258349412352L >>> ( 2 ** 3 ) ** 4 4096 순서가혼동된다면괄호로묶어주는것이가장안전하다!

관계연산자 값을서로비교하는연산자 관계연산자 의미 > 크다 < 작다 >= 크거나같다 <= 같거나작다 == 같다!= 같지않다 >>> 8 == 9 False >>> 8!= 9 True >>> 3 > 6 False >>> 5 <= 6 True >>> a = 2 >>> b = 3 >>> a > b False >>> 0 < a < b True 0 < a and a < b 와동일한표현

논리연산자 진리값 (True, False) 을피연산자로취하여논리값을계산하는연산자 우선순위높음 우선순위낮음 논리연산자 not x x and y x or y 의미 x 가거짓이면 True, 아니면 False x 와 y 모두참이면 True 아니면 False x 또는 y 둘중하나라도참이면 True, 모두거짓이면 False >>> a = 10 >>> b = 20 >>> a > 10 and b < 50 False >>> a >= 10 and b < 50 True >>> a > 6 or b < 0 True >>> a > 20 or b < 10 False >>> ( a > 20 or b < 50 ) and a > 100 False >>> not 1 False >>> not 0 True 내부적으로 True 는 1 을 False 는 0 의값을가짐 x y x and y True True True True False False False True False False False False x y x or y True True True True False True False True True False False False

Homework 제출기한 : 2014 년 5 월 29 일 ( 목 ) 자정 E-mail : chanchan@snu.ac.kr, 박찬희이메일제목맨앞에 [BITEC 성함 ] 을명시할것. 예 ) [BITEC 홍길동 ] 1 강 Homework 입니다. 파일형식 : ms-word 또는한글파일또는 pdf 파일파일명 : 성함.pdf, 성함.hwp, 성함.doc 프로그래밍하는부분은반드시소스코드를기입해서제출해야합니다 1. 아래문자중변수명으로사용할수없는것들을찾아이유를기술하시오 1. patient, _secret_text, %_percent, 1st_author, ranges, range, pass 2. ( 6 < 10 ) and ( 7!= 5 ) or ( 10 == 9 ) 의결과가무엇이고왜그렇게나왔는지설명하시오 3. BMI(Body Mass Index) 는아래와같이계산할수있습니다. BMI = mass (kg ) ( height meter ) 1. mass, height 라는변수에몸무게가 89.3kg 이고키가 172cm 인경우를입력하고 BMI 변수에계산결과를담은후출력하시오 ( 단위주의!!!)