[Python]

Python 기본 개념 정리 4

Sir교수 2022. 11. 29. 22:52
728x90

6. 입력과 출력
6.1 화면출력
ello Python!!
print("Hello Python!!")
Hello Python!!
문자열 여러개를 연결하여 출력 (자동으로 공백 발생)

print("Best", "python", "book")
Best python book
sep 활용 (공백 대신 다른 문자열)

,
print("Best", "python", "book", sep = "-")
Best-python-book
빈칸없이 문자를 연결할 때 +사용

print("abcd" + "efg")
abcdefg
콤마와 + 같이 사용 가능

print("Best", "python", "book" + ":", "This book")
Best python book: This book
변수에 저장된 내용을 출력 할 때

x = 10
print(x)
10
문자열과 숫자를 함께 출력

name = "J"
ID_num = 789
print("Name:", name + "," , "ID Number:", ID_num )
Name: J, ID Number: 789
여러줄로 출력하기 (개행문자 \n)

print("James is my friend.\nHe is Korean.")
print("James is my friend.\nHe is Korean.")
James is my friend.
He is Korean.
줄바꿈

\n
print("James is my friend.\n\nHe is Korean.")
James is my friend.

He is Korean.
줄을 바꾸지 않고 출력

print("Welcome to")
print("python!")
Welcome to
python!
두 줄로 출력된 결과를 한 줄로 입력하기 (end)

 
print("Welcome to", end = "")
print(" python!")
Welcome to python!
형식 지정 출력
나머지 연산자(%)를 이용한 형식 위치 지정
나머지 연산자를 이용한 데이터의 출력형식과 위치를 지정하는 기본구조

# %s는 문자열
name = "오리너구리"
print("%s은 나의 친구입니다." %name) # %s는 문자열
오리너구리는 나의 친구입니다.
r = 3
PI = 3.141592
print("반지름: %d, 원주율: %f" %(r, PI))  # %d는 10진수, %f는 실수
반지름: 3, 원주율: 3.141592
형식 지정 문자열에서 출력 위치 지정
string.format을 이용하는 형식지정 문자열의 기본 구조

print("{0},{1},{2}.....{n}".fomnat(data_0,data_1,data_2,......,data_n)

animal_1 = "cat"
animal_5 = "dog"
animal_4 = "fox"
animal_1 = "cat"
animal_5 = "dog"
animal_4 = "fox"

print("Animal: {0}".format(animal_5))
print("Animal: {0},{1},{2}".format(animal_4, animal_5, animal_1)) 
# {0}은 0번째 format. 뒤에 숫자로 변수 변경하여 순서 변경 가능
Animal: dog
Animal: fox,dog,cat
출력 위치 변경
print("Animal: {1},{2},{0}". format(animal_1, animal_5, animal_4))
Animal: dog,fox,cat
순차적으로 데이터 순서를 지정하려면 생략가능

5
print("Animal:{},{},{}".format(animal_1, animal_4, animal_5))
Animal:cat,fox,dog
정수나 실수도 출력가능

문자열을 변수에 대입한 후 변수를 불러서 출력 실수의 경우 17자리까지 표현되며 반올림 되어 출력된다.

1
name = 'Tomas'
2
age = 10
3
a = 0.232526234324215649655435
4
format_string = "string: {0}, integer Number: {1}, floating Number: {2}"
5
print(format_string.format(name, age, a))
string: Tomas, integer Number: 10, floating Number: 0.23252623432421565
형식 지정 문자열에서 숫자 출력 형식 지정
데이터가 숫자일 경우 {N: '출력형식'을 지정하여 다양한 형태로 출력이 가능}

a = 2532.1234567890123456789
print("{0:.2f},   {0:.5f}".format(a))
2532.12,   2532.12346
6.1 키보드 입력
data = input("문자열")

yourName = input("당신의 이름은?")
print("당신은 {}군요.".format(yourName))
당신의 이름은? 오리 너구리
당신은  오리 너구리군요.
num = input("숫자를 입력하세요:")
print("당신이 입력한 숫자는 {}입니다.".format(num))
숫자를 입력하세요:22
당신이 입력한 숫자는 22입니다.
weight = input("오리 너구리님의 몸무게는?")
print("오리 너구리 님의 몸무게는 {}kg입니다.".format(weight))
오리 너구리님의 몸무게는?50
오리 너구리 님의 몸무게는 50kg입니다.
숫자를 연산에 이용하기 위해서는 변환해야 함

a = input ("정사각형 한변의 길이는 얼마입니까?")
area = float(a) **2 
print("정사각형의 넓이는 {}입니다.".format(area))
정사각형 한변의 길이는 얼마입니까?1.2
정사각형의 넓이는 1.44입니다.
새로운 방식 f

a = input ("정사각형 한변의 길이는 얼마입니까?")
area = float(a) **2 
print(f"정사각형의 넓이는 {area}입니다.")
정사각형 한변의 길이는 얼마입니까?2.56
정사각형의 넓이는 6.5536입니다.
6.3 파일 읽고 쓰기
출력결과를 화면이 아니라 파일로 출력하거나 읽어야 할 경우

파일열기
내장 함수인 open()을 이용해 파일을 열어야 한다.

f = open('file_name', 'mode)

file_name = 열고자 하는 파일

mode = 파일의 속성

f.write(str)

f.close

r = 읽기모드로 파일열기
w = 쓰기모드로 파일열기 (같은 이름이 있으면 기존 내용은 모두 삭제됨)
x = 쓰기모드로 파일열기 (같은 이름의 파일이 있을 경우 오류 발생)
a = 추가모드로 파일열기 (같은 이름의 파일이 있는 경우 기존 내용 모두 삭제)
b = 바이너리 모드로 파일 열기
t = 텍스트 파일 모드로 파일 열기 (기본 지정하지 않으면 기본적으로 텍스트 모드로 지정됨)
파일 쓰기
f = open('file_name','w')
f.write(str)
f.close
폴더로 이동하기 명령

cd C:\myPyCode
c:\myPyCode
파일을 쓰기 모드로 열고, 문자열 입력 후 파일 닫기 코드

 yeah
f = open('myFile.txt', 'w')                  #(1)'myFile.txt' 파일 쓰기 모드로 열기
f.write('This is my first file yeah.')            #(2) 연 파일에 문자열 쓰기
f.close()                                    #(3) 파일 닫기 
파일 이름을 이용하여 내용 확인하기

f = open('myMing.txt','w')
f.write('Ming is 오리너구리')
f.close()
File
!type myFile.txt
This is my first file yeah.
파일 읽기
_text)
f = open('myFile.txt', 'r')
file_text = f.read()
f.close()

print(file_text)
This is my first file yeah.
6.4 반복문을 이용해 파일 읽고 쓰기
f = open('two_times_table.txt','w')
for num in range(1,6):
    format_string = "2 * {0} = {1}\n".format(num,num*2)
    f.write(format_string)
f.close()
imes_table.txt
!type two_times_table.txt
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
readline()
f = open('two_times_table.txt') #파일을 읽기 모드로 열기
line1 = f.readline()            #한 줄씩 문자열을 읽기
line2 = f.readline()
f.close()
print(line1, end ="")           #한 줄씩 문자열 출력
print(line2, end ="")
2 * 1 = 2

2 * 2 = 4
f = open("two_times_table.txt")
line = f.readline()
while line:
    print(line, end ="")
    line = f.readline()
f.close()
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
readlines() 한꺼번에 출력한다

f = open("two_times_table.txt")
lines = f.readlines()
f.close()

print(lines)
['2 * 1 = 2\n', '2 * 2 = 4\n', '2 * 3 = 6\n', '2 * 4 = 8\n', '2 * 5 = 10\n']
for 문을 이용하여 전체 읽기

)
f = open("two_times_table.txt") #파일을 읽기 모드로 열기
lines = f.readlines()           #파일 전체 읽기(리스트로 반환)
f.close()                       #파일 닫기
for line in lines:              #리스트를 <반복 범위>로 지정
    print(line, end="")      #리스트 항목을 출력(줄 바꿈 안함)
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
6.5 with 문을 활용해 파일 읽고 쓰기
with open('file_name', 'mode') as f:

with open('c:/myPyCode/myTextFile2.txt','w') as f:   #(1) 파일 열기
    f.write('File read/write test2: line1\n')        #(2) 파일 쓰기
    f.write('File read/write test2: line2\n')
    f.write('File read/write test2: line3\n')
with open('c:/myPyCode/myTextFile2.txt') as f: #파일 열기
    file_string = f.read()
    print(file_string)
File read/write test2: line1
File read/write test2: line2
File read/write test2: line3

  # 파일에 문자열 쓰기 
with open('c:/myPyCode/myTextFile3.txt', 'w') as f:    #파일을 쓰기 모드로 열기
    for num in range(1,6):                             #for문에서 num이 1~5까지 반복
        format_string = "3 x {0} = {1}\n".format(num,3*num) #문자열 생성
        f.write(format_string)                               # 파일에 문자열 쓰기 
with open('c:/myPyCode/myTextFile3.txt','r')as f: #파일을 읽기 모드로 열기
    for line in f:                                #파일 전체를 읽고 리스트 항목을 line에 할당
        print(line, end="")
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

728x90