>>> a = 100 ; b = 200
>>> c = a + b
>>> print(a,b,c) # 콤마에 공백이 추가된다.
100 200 300
>>> print(a+b) # 수치 연산자는 계산 결과를 보여준다.
300
>>> print(a+50)
150
문자열 출력하기
>>> print('hello world!')
hello world!
>>> print('hello', 'world!') # 콤마에 공백이 추가된다.
hello world!
>>> print('hello' + 'world!')
helloworld!
>>> movie = 'toy story'
>>> print(movie)
toy story
>>> movie
'toy story
>>> x = '5'
>>> y = 5
>>> print(x)
5
>>> print(y)
5
>>> x
'5'
>>> y
5
+연산자 출력
>>> print('hello' + 100) # 에러
>>> print('hello' + str(100))
hello100
>>> x = '10'
>>> n = 100
>>> n + x # 에러
>>> n + int(x)
110
% 이용한 서식 출력
출력문 - % 이용한 서식 출력 ( 문자열, 정수)
문자열 : %s
정수 : %d
실수: %f
print( ' 위게 3개의 값을 여기에 대입하면됩니다. ' %(,))
>>> name = 'Alice' ; score = 95
>>> print('%s got %d score' % (name, score))
Alice got 95 score
>>> print('%10s got %5d score' % (name, score))
Alice got 90 score
문자열 : %s
정수 : %d
실수 : %f
print(' ' % ( , ) )
(10칸 잡아서 Alice 출력, 5칸 잡아서 90 출력)
% 이용한 서식출력(실수)
입력문 - input() 함수
키보드로부터 입력을 받는다.
필요하다면 입력 받은 데이터의 자료형을 적절히 변환해야한다.
>>> x = input('Enter x : ')
Enter x : 10 ← 10이 변수 x 에 저장된다.
>>> print(x)
10
>>> x
'10'
>>> type(x) # 입력받은 데이터는 항상 문자열로 처리한다.
<class 'str'>
>>> x = input('정수를 입력하시오 : ')
정수를 입력하시오 : 15
>>> x + 10
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
x + 10
TypeError: Can't convert 'int' object to str implicitly
>>> int(x) + 10
25
일반적으로 다음과 같이 이용한다.
>>> x = int(input('Enter one integer : '))
Enter one integer : 100
>>> type(x)
<class 'int'>
>>> y = float(input('Enter one float number : '))
Enter one float number : 3.14
>>> type(y)
<class 'float'>
파이썬 기초를 아주 많이 쉽게 간추려서 올려 드리고있습니다. 완전 기초 입문자를 위한 자료입니다.
문자열 자료형
파이썬에서 문자열 객체는 따옴표를 이용하여 생성합니다.
홑따옴표(' … ') 쌍따옴표(" … ") 홑따옴표 세 개(''' … ''') 쌍따옴표 세 개(""" … """)
>>> s ='Python is great!'
>>> s ="Python is great!"
>>> s = '''Python is great!'''
>>> s = """Python is great!"""
>>> print(s)
Python is great!
또한 역슬래쉬(\)를 이용하여 긴 문자열 생성을 할 수 있습니다.
>>> sentence = 'Python is the \
most popular programming \
language in these days.'
>>> print(sentence)
Python is the most popular programming language in these
days.
문자열 안에 홑따옴표 혹은 쌍따옴표를 쓰고싶을때의 방법도 알려드리겠습니다.
say
'hello' to mom.
4
>>> a = 'say 'hello' to mom
'
SyntaxError: invalid syntax
>>> b = "say 'hello' to mom
"
>>> c = '''say 'hello' to mom
'''
>>> d = """say 'hello' to mom
"""
>>> print(d)
say 'hello' to mom
>>> s = 'say "hello" to mom
'
>>> s = '''say "hello" to mom
'''
>>> s = """say "hello" to mom
"""
>>> print(s)
say "hello" to mom
s = """say "hello" to '
mom
'"""
>>> print(s)
say "hello" to 'mom'
긴 문장을 쓰고싶을때 !
# letter to Alice
print('''Dear Alice,
How are you?
I am busy to study programming this vacation.
Say hello to your parents.
Sincerely,
Bob''')
문자열 객체의 특징
- immutable하다.
- 순서가 있는 자료형으로 인덱싱을 이용할수 있다.
인덱스에 있는 값들을 불러올수 있는 자료형입니다.
문자열 연결하기 (+)
문자열 반복하기는 (*) 를 사용합니다
예를들어서 a =hello, a*3 를 쓰면 문자열을 3회 반복하여 출력이 됩니다. 'hellohellohello'
객체를 저장한 공간을 변수(Variable)라고 하고 변수명(variable name)으로 객체에 접근할수 있다.
객체생성하는법
Ex) a = 100
변수명 만들기
변수명은 영어 소문자, 대문자, 숫자,_(underscore)로만 구성한다.
변수명은 숫자로 시작할 수없다.
대소문자를 구분한다. 즉, data 와 Data는 다른변수이다.
변수명은 한글도 가능하다.
키워드(keyword)를 변수명으로 사용하면 안된다.
>>>number = 5
>>>score = 90
>>>python_score = 95
>>>_score =100
>>>math-score =90 #syntax 에러. 특수 기호는 _만 가능하다.
>>> math1 = 80
>>> 1math = 80 # syntax 에러. 숫자로 시작할 수 없다
>>> 학생수 = 50 # 한글 변수명도 가능함
객체 삭제하기
del 을 이용하면 객체를 삭제할수 있다.
>>> data = 100
>>> print(data)
100
>>> del data
>>> print(data)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
print(data)
NameError: name 'data' is not defined
부울형 (bool) - 파이썬의 부울형은 참/거짓을 나타내는 True/False 의 두값만을 갖는다.
>>> a = True
>>> b = False
>>> type(a)
<class 'bool'>
>>> type(b)
<class 'bool'>
>>> x = 1
>>> y = x > 0
>>> print(y)
True
>>> type(y)
<class 'bool'>
문자열 (str) - 따옴표를 이용하여 표현한다.
>>> name = 'Alice' # 홑따옴표
>>> print(name)
Alice
>>> type(name)
<class 'str'>
>>> id(name)
59750720
>>> city =
"Seoul, Korea" # 쌍따옴표
>>> print(city)
Seoul, Korea
>>> language = '''python''' # 홑따옴표 세 개
>>> print(language)
Python
>>> w = """Python is widely used""" # 쌍따옴표 세 개
>>> print(w)
Python is widely used
리스트(list) -대괄호[] 로 표현한다. 여러개의 자료들을 모아서 저장해야 하는 경우에 사용한다.
주석은 #으로 표현되고 길게 적고싶으면 ''' ''' 아니면 """ """ 을 사용하면 된다.
단축키는 ctrl +shift + / 을 누르면된다.
#이렇게 적으면 코드로 읽지 않는다.
""" 프로젝트 1.
작성자 : 홍길동
완성일 : 2016. 07. 31
프로젝트 버전 : 0.01
이 프로젝트는 파이썬 버전 3을 이용하였음 """
print('start of the program')
# 주요 코드 시작 부분
print('......')
"""
……
""" – 쌍따옴표 3개로 작성한 부분을 docstring 이라고 한다.
docstring은 함수, 클래스, 모듈 등을 작성할 때 유용하다