728x90

출력문 - print() 내장함수

자바와 다르게 print() 이 문자로 출력을 합니다. 

print() 함수는 괄호의 내용을 출력한다. 

출력하고자 하는 ㄱ밧이 여러개이 ㄴ경우에는 콤마로 구분할 수 있으며,

출력할때 각각의 값 사이에 공백 한개가 추가된다. 

문자열을 출력하려면 홑따옴표 또는 쌍따옴표를 이용한다. 

 

변수에 저장된 값 출력하기 

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

 

 

 

728x90

'Language > python' 카테고리의 다른 글

numpy -인덱싱 / 슬라이싱  (0) 2022.06.21
numpy - ndarray 데이터 형태 바꿔보기  (0) 2022.06.21
numpy- 기초  (0) 2022.06.21
파이썬 기초 -2  (0) 2022.06.15
파이썬 기초 -1  (0) 2022.06.14
복사했습니다!