chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable)...

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

Upload: others

Post on 17-Jan-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

Chapter 1변수, 자료형,예약어, 연산자, 숫자형자료형

2014. 5. 22

Page 2: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

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 기관및연구기관

Page 3: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

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!"

명료하고읽기쉬운문법

명료하고읽기쉬운문법

Page 4: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

Python은대화형인터프리터언어

chanchan-ui-Mac-Pro:~ chanchan$ pythonPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "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) : 명령입력대기중임을나타낸다.

명령입력

명령입력

Page 5: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

High Level 동적데이터타입결정지원

>>> def add(a, b):... return a+b... >>> 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

문자Type

ListType

return a+b 에서a 와 b 에맞는 + method 를자동으로호출함

Page 6: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

메모리자동관리

C나 C++ 같은언어는메모리관리책임이개발자에게달려있음.

약간의수정에도항상메모리관리를점검해야함. 의도치않은에러발생확률높음.

Python에서는 Garbage Collection 기능을이용하여메모리관리를함. 필요시자동으로메모리를자동할당 사용이끝나면자동을사용해제

Page 7: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

다른언어와의확장성

>>> import rpy>>> x = [5.05, 6.75, 3.21, 2.66]>>> 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

> 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함수를이용해상관계수구하기

Python 에서 rpy모듈을사용하여R cor함수를호출

현재는작동하지않는코드입니다.타이핑하지마십시오.

Page 8: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

#!/usr/bin/pythonfrom Bio import Entrezfrom Bio import Medline

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)

for record in records:print "PubMed ID : ", record.get("PMID", "?")print "TITLE: ", record.get("TI", "?")print "ABSTRACT: ", record.get("AB", "?")

PubMed ID : 23091317TITLE: 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 : 23091316TITLE: Association between Nutrient Intake and Obesity in Type 2 Diabetic Patients from the Korean National DiabetesProgram: A Cross-Sectional Study.ABSTRACT: The aim of the study was to assess the association between usual dietary nutrient … 생략

PubMed ID : 23076296TITLE: 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.. 생략

BioPython 모듈불러오기키워드‘Type 2 Diabetes korean’ 으로PubMed문헌검색후PubMed ID 3개만가져옴

가져온 PubMed ID 를이용하여MedLine Text 를가져옴

PubMed ID, Title, Abstract 를출력

결과총 12 줄짜리프로그램

풍부한라이브러리예) BioPython을이용해 PubMed문헌 search/retrieve

현재는작동하지않는코드입니다.타이핑하지마십시오.

Page 9: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

간단한실습

>>> 2 + 46>>> ( 4 + 6 ) * 220>>> 11 / 33>>> 11 / 3.3.6666666666666665>>> 11 % 32>>> divmod(11, 3)(3, 2)>>> a, b = divmod(11, 3)>>> a3>>> b2>>> 3.4e434000.0>>> 3.4e-40.00034000000000000002>>> 2**38

정수 / 정수 = 정수정수 / 실수 = 실수실수 / 실수 = 실수

% 나머지연산자divmod(a, b) a를 b로나눴을때몫과나머지를계산해주는함수(function)

3.4e4 : 3.4 곱하기 10의 4승3.4e-4 : 3.4 곱하기 10의 -4승2**3 : 2의 3승

정수/정수형에서제대로된계산결과를얻기위해3. 이라고표시하여 3이라는숫자를실수형으로인식

Page 10: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

작성한프로그램저장

1. File Click

2. New Window Click

3. 새윈도우창에앞에서작성한계산을입력

4. File -> Save 클릭

5. first_code.py 라고타이핑후저장

주의 : 저장시저장경로는현재사용자가쓰기권한이있는디렉토리여야합니다.

Page 11: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

작성한프로그램실행

1. Run선택후 Run Module 로실행

2. 아무런결과도나오지않는다???

3. 출력하고하는부분에 print 구문을추가이는 idle 뿐아니라다른에디터프로그램을사용하여출력할시에도동일함

4. Bingo !!!

Page 12: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

>>>a = 1>>> a = 1

File "<pyshell#5>", line 1a = 1^

IndentationError: unexpected indent

Indentation(들여쓰기) : 명령입력시첫컬럼부터시작해야 한다.그렇지않으면 indentation error 가나게된다.

Python 은들여쓰기를엄격하게지키는언어이다.

한칸공란이있음

Indentation (들여쓰기) (1/2)

Page 13: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

Indentation (들여쓰기) (2/2)

import MySQLdbdb= 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.rowcountcursor.close(); db.close()

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()

Indentation 을지키지않으면Syntax error 를일으킬뿐아니라소스코드를읽기조차힘들어진다.

현재는작동하지않는코드입니다.타이핑하지마십시오.

Page 14: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

Syntax Error vs. Logical Error

Syntax Error 스펠링이나문법이틀려서나는에러 실행시출력되는에러메시지를이용하여에러검출이가능

Logical Error Syntax Error 은전혀없으나논리상오류가나는에러종류 찾아내기쉽지않은에러형태.

>>> prin "Hello Python"File "<stdin>", line 1prin "Hello Python"

^SyntaxError: invalid syntax

>>> result = ''>>> grade = 95>>> if grade >= 90:... result = 'F'...>>> print resultF

예)Syntax error 예) Logical error

Page 15: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

변수 (variable)

‘=‘ 치환연산자 (assignment operator)오른쪽항의값을왼쪽으로치환variable Value

a 1

string_test Python

알려진또는알려지지않은어떤값(value)을담는저장공간(Storage location) 과그에상응하는심볼릭이름(symbolic name)을의미

>>> a = 1>>> string_test = ‘Python’

string_test = ‘Python’

Python 이란값(value)을string_test 란변수(variable)로치환

>>> a = 1>>> a = a + 1>>> a2>>>

a 라는변수에 1이라는값을할당한다.

a 라는변수에 1이라는값을더한후결과를다시 a 라는변수에할당한다.

Page 16: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

변수선언

첫문자가 underscore(_) 또는영문자 두번째문자부터는영문자, 숫자, underscore 가올수있음. 크기에는제한이없음 [a-zA-Z_][a-zA-Z-0-9_]* 사용가능한예

a, input_str, MyVar, _private_string, … 변수명이될수없는예

5public, @email, %var, …. 변수명은대소문자를구분.

예) Email 과 email 은다른변수

>>> @email = '[email protected]'SyntaxError: invalid syntax>>> email = '[email protected]

>>> Email = '[email protected]'>>> email = '[email protected]'>>> Email'[email protected]'>>> email'[email protected]'

변수선언규칙에맞지않는다.

변수명은대소문자를구분한다.

Page 17: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

예약어는변수명으로사용할수없다. Python 에서이미쓰고있는예약어(reserved words or keywords )는변수명으로사용할수없다.

and del from not whileas elif global or with

assert else if pass yieldbreak except import print classexec in raise continue

is return def finallyfor lambda try

Python 에서사용하는예약어

>>> from = 10SyntaxError: 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 : 가져오기/들여오기 –다른사람이만든또는

본인이만든데이터/프로그램을읽어들이는행위

Page 18: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

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()

내장함수 (built-in functions) 이름을변수명으로사용하면생기는문제

http://docs.python.org/2/library/functions.html>>> 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>>>

divmod는문자형변수로바뀌었고더이상함수가아니다.

문자형변수에 함수형태의값을입력하기때문에에러가발생한다.

chanchan
텍스트
Page 19: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

변수명의좋은예와나쁜예

>>> a = 160.4>>> aa = 71.1>>> print a, aa160.4 71.1>>>

>>> height = 160.4>>> weight = 71.1>>> print height, weight160.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

잘명명한변수명은코드를다시들여다보는본인뿐아니라코드를보는다른사람들도행복하게만듭니다.

Page 20: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

코드에주석달기

주석(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. 까지의결과만나오고 # 이후의내용은무시함

Page 21: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

자료형 (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’)

Page 22: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

>>> 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'>

>>> 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'>

type함수는객체의자료형을알려준다.

int : 정수형float : 실수형str : 문자형list : 리스트형

dict : 딕셔너리형tuple : 튜플형file : 파일형

Page 23: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

수치자료형 (1/2) 수치자료형

정수형(int), 실수형(float), 롱형(long), 복소수형(complex)이있다. 정수형상수

수치표현범위 : -2,147,483,648~2,147,483,647(32bit인경우)

# 32bit OS>>> maxint = 2**31 - 1>>> maxint2147483647L>>> -maxint - 1-2147483648L

>>> import sys>>> sys.maxint2147483647

# 64bit OS>>> import sys>>> sys.maxint9223372036854775807>>> 2**63 -19223372036854775807L

32/64bit OS에따라최대표현범위가다르다.

• 롱형상수• 정수형으로표현할수없는큰수는자동으로롱형정수로표현• 롱형상수는정수수치마지막에 ‘l’, 혹은 ‘L’을붙여서표현• 유효자리 : 메모리가허용하는한무한대.

#32bit OS>>> 1234567898765432112345678987654321L

#64bit OS>>> 12345678909876543211234567890987654321

정수형의최대표현범위를넘기면자동으로 L 이붙는다.

정수형의최대표현범위를넘지않았으므로 L 이붙지않는다.

# 32bit OS>>> print 1234567898765432112345678987654321

print 문을사용하면 L 이붙지않는다

Page 24: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

수치자료형 (2/2)

실수형 소수점을포함하거나 e나 E로지수를포함 범위 : 10의 -308승~ + 308승

>>> a = 4.5>>> b = 3.5e3>>> c = -0.3e-4>>> print a, b, c4.5 3500.0 -3e-05

>>> import sys>>> sys.float_info.max1.7976931348623157e+308

• 복소수형• 실수부 + 허수부로나뉨• 허수부에는 ‘j’나 ‘J’를붙여야함

>>> c = 5 + 8j>>> d = 2 - 6j>>> c + d(7+2j)>>> c.real5.0>>> c.imag8.0>>> c.conjugate()(5-8j)

real : 실수부

imag : 허수부

conjugate(): 켤레복소수

Page 25: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

math 모듈>>> import math>>> math.sqrt(16)4.0

>>> math.exp(3)20.085536923187668

>>> math.log(10)2.3025850929940459

>>> math.log10(10)1.0>>> math.pi3.1415926535897931

>>> math.e2.7182818284590451

>>> math.fabs(-11.5)11.5

>>> round(3.54)4.0

math 모듈불러오기

Built-in 함수

math.sqrt() : 제곱근math.exp() : 지수math.log() : 자연로그 ( base 가 e )math.log10() : 자연로그 ( base가 10 )math.pi : pi 값math.e : e 값math.fabs() : 절대값

round : 반올림함수(내장형함수임)

Page 26: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

수치연산자

+(덧셈), -(뻴셈), *(곱셈)

/(나눗셈), **(지수승), %(나머지)

• 정수형을다른정수형과연산하면결과는언제나정수형• 정수형과다른실수형을연산하면결과는언제나실수형

>>> 4 + 6 # 정수 + 정수10 # 결과는정수>>> 4 + 6.0 # 정수 + 실수10.0 # 결과는실수>>> 6 / 4.0 # 정수 / 실수1.5 # 결과는실수>>> 6 / 4 # 정수 / 정수1 # 결과는정수

Page 27: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

수치연산자의우선순위

연산자 설명 결합순서

() 괄호 왼쪽→오른쪽

+, - 단항연산자(예. -5, +4) 오른쪽 →왼쪽

** 지수 오른쪽 →왼쪽

*, /, % 곱하기, 나누기, 나머지 왼쪽 →오른쪽

+, - 더하기, 빼기 왼쪽 →오른쪽

우선순위높음

우선순위낮음

>>> 3 * -2-6>>> 2 + 3 * 414>>> ( 2 + 3 ) * 420

>>> 4 / 2 * 24>>> 4 / ( 2 * 2 )1>>> 2 ** 3 ** 42417851639229258349412352L>>> ( 2 ** 3 ) ** 44096

순서가혼동된다면괄호로묶어주는것이가장안전하다!

Page 28: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

관계연산자

값을서로비교하는연산자관계연산자 의미

> 크다

< 작다

>= 크거나같다

<= 같거나작다

== 같다

!= 같지않다

>>> 8 == 9False>>> 8 != 9True>>> 3 > 6False

>>> 5 <= 6True>>> a = 2>>> b = 3>>> a > bFalse>>> 0 < a < bTrue

0 < a and a < b 와동일한표현

chanchan
텍스트
Page 29: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

논리연산자

진리값(True, False)을피연산자로취하여논리값을계산하는연산자

논리연산자 의미

not x x가거짓이면 True,아니면 False

x and y x 와 y 모두참이면 True 아니면 False

x or y x 또는 y 둘중하나라도참이면 True, 모두거짓이면 False

>>> a = 10>>> b = 20

>>> a > 10 and b < 50False>>> a >= 10 and b < 50True

>>> a > 6 or b < 0True>>> a > 20 or b < 10False>>> ( a > 20 or b < 50 ) and a > 100False

>>> not 1False>>> not 0True

내부적으로 True 는 1을False 는 0 의값을가짐

우선순위높음

우선순위낮음

x y x and yTrue True True

True False False

False True False

False False False

x y x or yTrue True True

True False True

False True True

False False False

Page 30: Chapter 1bitec.snubi.org/eductr/python_chapter1.pdf · 2014-11-15 · 변수(variable) ‘=‘치환연산자(assignment operator) variable Value 오른쪽항의값을왼쪽으로치환

Homework

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) 는아래와같이계산할수있습니다.

1. mass, height 라는변수에몸무게가 89.3kg 이고키가 172cm 인경우를입력하고 BMI 변수에계산결과를담은후출력하시오 (단위주의!!!)

제출기한 : 2014년 5월 29일(목) 자정E-mail : [email protected], 박찬희이메일제목맨앞에 [BITEC 성함] 을명시할것.

예) [BITEC 홍길동] 1강 Homework 입니다.파일형식 : ms-word 또는한글파일또는 pdf 파일파일명 : 성함.pdf, 성함.hwp, 성함.doc프로그래밍하는부분은반드시소스코드를기입해서제출해야합니다

𝐵𝑀𝐼 = 𝑚𝑎𝑠𝑠 (𝑘𝑔 )( ℎ𝑒𝑖𝑔ℎ𝑡 𝑚𝑒𝑡𝑒𝑟 )