글
[파이썬 기초] 입력과 출력
프로그램을 만들다 보면 입력을 해야하는 경우가 있고, 출력을 해야하는 경우가 있다. 그래서 입력은 input()함수를 사용하고, 출력은 print() 문을 사용한다.
[사용자로부터 입력받기]
1 2 3 4 5 6 7 8 9 10 11 |
def reverse(text): return text[::-1]
def is_palindrome(text): return text == reverse(text)
something = input("Enter text: ") if is_palindrome(something): print("Yes, it is a palindrome") else: print("No, it is not a palindrome") |
출력화면
- 문자열을 뒤집기 위해서는 슬라이스를 사용한다. 열거형의 슬라이스 기능을 이용하여 seq[a:b] 와 같은 코드를 통해 a부터 b까지 문자열을 얻어올 수 있다. 슬라이스 숫자에 세 번쨰 인수를 넘겨주어 슬라이스 스텝을 지정해줄 수 있다.
- input() 함수는 인수로 넘겨받은 문자열을 받아들인다. 사용자가 무언가를 입력하고 엔터 키를 누를 때까지 기다려준다.
[파일 입출력 예제]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# 파일 입/출력 poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! '''
# Open for 'w'riting f = open('poem.txt', 'w') # Write text to file f.write(poem) # Close the file f.close()
# If no mode is specified, # 'r'ead mode is assumed by default f = open('poem.txt') while True: # (무한반복) line = f.readline() # 파일의 내용을 읽어들인다. # Zero length indicates EOF if len(line) == 0: break # The 'line' already has a newline # at the end of each line print(line) # close the file f.close() |
- 결과화면
- 소스코드 안에 입력한 내용이 같은 폴더 안에 'poem.txt'가 새로 생성이 되고, 안의 내용도 추가한 내용대로 추가되어있다.
[Pickle]
: 이것은 어떤 파이썬 객체이든지 파일로 저장해 두었다가 나중에 불러와서 사용할 수 있게 하는 모듈이다. 이것은 객체를 영구히 저장해 둔다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import pickle
# The name of the file where we will store the object shoplistfile = 'shoplist.data' # The list of things to buy shoplist = ['apple', 'mango', 'carrot']
# Write to the file f = open(shoplistfile, 'wb') # Dump the object to a file pickle.dump(shoplist, f) f.close()
# Destroy the shoplist variable del shoplist
# Read back from the storage f = open(shoplistfile, 'rb') # Load the oebject from the file storedlist = pickle.load(f) print(storedlist)
|
- 결과화면
https://www.programcreek.com/python/example/191/pickle.dump
- 파일에 객체를 저장하기 위해서 먼저 Open 문을 이용하여 쓰기/바이너리 모드로 파일을 열어준 후 pickle 모듈의 dump 함수를 호출하여 준다. 이 과정을 피클링(pickling)이라고 한다.
- pickle 모듈의 load 함수를 이용하여 파일에 저장된 객체를 불러온다. 이 과정을 언피클링(unpickling)이라고 한다.
'기초 > Python' 카테고리의 다른 글
[파이썬 GUI 프로그래밍] 상단바 (0) | 2018.09.11 |
---|---|
[파이썬 GUI 프로그래밍] 처음 시작 (0) | 2018.09.10 |
[파이썬 기초] 객체지향, 클래스 (0) | 2018.08.10 |
[기초] 지역변수, Global문, DocString (0) | 2018.08.08 |
[기초] 함수 (0) | 2018.08.07 |