파이썬 딥러닝 ai 스쿨 기초/lecture03

lecture03 0교시 파이썬 기초 연습문제

junny1997 2021. 3. 22. 16:21

튜플

t1 = (1, 2, 3)
#괄호로 선언
print(t1)
print(len(t1))
print(t1[0])
print(t1[:2])
#튜플은 del t1[0], t1[0] = 4 등의 데이터 수정 지원 안함
t2 = (4,)
print(t2)
print(t1*3)
print(t1 + t2)

(1, 2, 3)
3
1
(1, 2)
(4,)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
(1, 2, 3, 4)

 

 

파일 입출력

#w 쓰기
f = open("./write.txt",'w',encoding='utf-8')
f.write("file write")
f.close()

f = open("./write.txt",'w',encoding='utf-8')
for i in range(1, 10):
    data = f'line {i}\n'
    f.write(data)
f.close()

#with 안에서만 open 자동 close
with open("./write.txt",'w',encoding='utf-8')as f:
    for i in range(1, 10):
        data = f'line {i}\n'
        f.write(data)

#a로 추가
f = open("./write.txt",'a',encoding='utf-8')
for i in range(10, 20)
    data = f'line {i}\n'
    f.write(data)
f.close()

#r 읽기
f = open("./write.txt",'r',encoding='utf-8')
line = f.readline()
#한줄만 읽는다
print(line)
f.close()

f = open("./write.txt",'r',encoding='utf-8')
#while로 여러줄 읽기
line = f.readline()
while line:
    print(line)
    line = f.readline()
f.close

f = open("./write.txt",'r',encoding='utf-8')
#readlines여러줄 읽기, 리스트로 들어감
lines = f.readlines()
for line in lines:
    print(line.strip())
f.close()

f = open("./write.txt",'r',encoding='utf-8')
#read로 통채로 읽고 저장
content = f.read()
print(content)
f.close()

f = open("./write.txt",'r',encoding='utf-8')
#글자수로 읽음,읽은 만큼 커서가 움직임
content = f.read(6)
print(content)
content = f.read(14)
print(content)
#커서 처음으로 돌아감
f.seek(0)
content = f.read(14)
print(content)
f.close()

 

 

연습문제 1

while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구하세요.

 

while 문을 사용해 다음과 같이 *들을 출력해보세요.

*

**

***

****

*****

 

numbers = [1, 2, 3, 4, 5]

result = []

for n in numbers:

     if n % 2 == 0:

         result.append(n+2)

위 코드를 리스트 내포를 이용해 한 줄로 구현해보세요.

 

#3.1-1
start = 1
end = 1000
sum = 0
while(start<=end):
    if start % 3 == 0:
        sum += start
    start += 1
print(sum)

#3.1-2
stair = 5
i = 1
while(i<=stair):
    print("*" * i)
    i += 1

#3.1-3
numbers = [1, 2, 3, 4, 5]
result = [n+2 for n in numbers if n % 2 == 0]
print(result)

166833

*
**
***
****
*****

[4, 6]

 

 

연습문제 2

주어진 fileIO.txt 파일을 읽어 Key는 성이고 Value는 나이인 딕셔너리 name_age에 정보들을 할당한 후 출력 하세요.

입력 파일 예시:

Kwon 31

Lee 34

Park 39

Choi 28

Cho 25

 

결과: {‘Kwon’:31, ‘Lee’:34…}

name_age = {}
f = open("./fileIO.txt",'r',encoding='utf-8')
for line in f.readlines():
    line = line.split()
    name_age[line[0]] = line[1]
print(name_age)

 

{'Kwon': '31', 'Lee': '34', 'Park': '39', 'Choi': '28', 'Cho': '25'}