코딩하는 털보

파이썬 기본 - 2 본문

IT Study/Python

파이썬 기본 - 2

이정인 2021. 4. 22. 20:12

파이썬 언어 기본


5.제어문

6.함수

7.입출력


제어문

# if 문
# if 조건:
color = input("color?")
if color == "red":
    print("빨강")
elif color == "blue":
    print("파랑")
else:
    print("없음")

# for 문
# for var in list:
for i in [1,2,3,4]:
    print("대기번호 "+str(i)+"번 입니다.")

for i in range(5): # 0,1,2,3,4
    print("number : "+str(i))

# while
# while 조건:
num = 0
while num < 5:
    print("번호 : "+str(num))
    num += 1

# 한줄 for문
students = [1,2,3,4,5]
students = [i+100 for i in students]
print(students)

# 예제
from random import *
count = 0
for i in range(1,51):
    time = randrange(5,51)
    if 5<=time<=15:
        count+=1
        print("[O] "+str(i)+"번째 손님 (소요 시간 : "+str(time)+"분)")
    else:
        print("[ ] "+str(i)+"번째 손님 (소요 시간 : "+str(time)+"분)")
print("총 탑승 승객 :"+str(count))

함수

# 함수 정의하기
# def 이름():
#   구현부

def show():
    print("show me the money")

show()

# parameter / return
# def function(param1, param2, ...):
#   return var

def plus(a,b):
    return a+b

print(str(plus(2,6))) #8

# return 타입은 여러 요소의 튜플이 될 수도 있다.
def fee(money):
    commission = 100
    return money, commission

print(fee(500)) # (500, 100)

# 기본 값
def profile(name, age=30, lang="java"):
    print("이름 : {0}\n나이 : {1}\n언어 : {2}".format(name, age, lang))

profile("이정인") # 이정인, 30, java
profile("박명수", 48, "python") # 박명수, 48, python

# 키워드 값
profile(name="유재석", lang="C", age=46) # 유재석, 46, C

# 가변 인자
def profile(name, age, lang1, lang2, lang3, lang4):
    print("이름 : {0}\t나이 : {1}".format(name, age), end="\t") # end로 줄바꿈 없이 탭
    print(lang1, lang2, lang3, lang4)

profile("유재석", 20, "python", "C", "C#", "C++")
profile("박명수", 21, "Java", "Kotlin", "", "")
# 인자가 더 늘어날수도 있고 더 줄어들수도 있는경우에 위와같은 불편함이 있다.

# 가변 인자 *arg
def profile(name, age, *langs):
    print("이름 : {0}\t나이 : {1}".format(name, age), end="\t") # end로 줄바꿈 없이 탭
    for lang in langs:
        print(lang, end=" ")
    print()

profile("유재석", 20, "python", "C", "C#", "C++", "javascript")
profile("박명수", 21, "Java", "Kotlin")

# 지역변수와 전역변수

gun = 10

def checkpoint(soldiers): # 군인의 수
    global gun # 전역변수를 이 함수에서 사용
    gun = gun - soldiers
    # 계산또한 실제 전역변수에 영향을 준다.
    print("함수내 남은 총 : {0}".format(gun))

print("전채 총 : {0}".format(gun)) # 10
checkpoint(2) # 8
print("남은 총 : {0}".format(gun)) # 8

# Quiz

def std_weight(height, gender):
    if gender == "남자":
        weight = (height/100)**2*22
        print("키 {0}cm 남자의 표준 체중은 {1}kg 입니다.".format(height, round(weight,2)))
    elif gender == "여자":
        weight =  (height/100)**2*21
        print("키 {0}cm 여자의 표준 체중은 {1}kg 입니다.".format(height, round(weight,2)))
    else:
        print("예외")

std_weight(175, "남자") # 키 175cm 남자의 표준 체중은 67.38kg 입니다.

입출력

# 표준 입출력

# 콤마 사이 지정
print("Spring", "Java", sep=", ") # Spring, Java

# print 개행 변경
# 실제로 print 함수의 end 값의 기본 값은 "\n" 이다.
print("Spring", "Java", end="?")
print("선택")

import sys
# 표준 출력
print("Spring", "Java", file=sys.stdout)
# 표준 에러
print("Spring", "Java", file=sys.stderr)

scores = {"수학":0, "영어":50, "코딩":100}

for subject, score in scores.items():
    # ljust : 왼쪽 정렬 및 공간 , rjust : 오른쪽 정렬 및 공간
    print(subject.ljust(5), str(score).rjust(4), sep=":")


for num in range(1,21):
    # 3공간 중 빈 공간은 0으로 채우기
    print("대기번호 : {0}".format(str(num).zfill(3)))
# 대기번호 : 001
# 대기번호 : 002
# 대기번호 : 003
# 대기번호 : 004
# ...

# 입력, 입력은 항상 문자열로 받는다.
# answer = input("아무 값이나 입력하세요\n")
# print(answer)

# 다양한 출력 포맷
# 빈 자리는 빈 공간, 오른쪽 정렬, 공간 확보
print("{0: >10}".format(500))

# 양수일때 +, 음수일때 - (부호 찍기)
print("{0: >+10}".format(500))
print("{0: >+10}".format(-500))

# 왼쪽 정렬, 빈 자리는 밑줄로
print("{0:_<10}".format(500))

# 큰 수 세자리마다 콤마 찍기
print("{0:,}".format(10000000000))

# 큰 수 세자리마다 콤마 찍기, 부호
print("{0:+,}".format(10000000000))

# 큰 수 세자리마다 콤마 찍기, 부호, 공간 확보, 빈자리는 ^
print("{0:^<+30,}".format(10000000000))

# 소수점 출력
print("{0:f}".format(5/3))
# 소수점 세번째에서 반올림
print("{0:.2f}".format(5/3))

# 파일 입출력
# open(파일명, 동작, 인코딩정보)
# "w" = 덮어쓰기
score_file = open("score.txt", "w", encoding="utf8")
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close()

# "a" = 이어쓰기
score_file = open("score.txt", "a", encoding="utf8")
# write 함수는 기본적으로 줄바꿈이 없다.
score_file.write("코딩 : 100\n")
score_file.write("일어 : 80\n")
score_file.close()

# "r" = 읽기
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.read())
score_file.close()

# 한줄씩만 읽기
score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline(), end="")
print(score_file.readline(), end="")
score_file.close()

# 모든 줄을 한줄 씩 읽기
score_file = open("score.txt", "r", encoding="utf8")
while True:
    line = score_file.readline()
    if not line:
        break
    else:
        print(line, end="")
score_file.close()

# 리스트로 뽑기
score_file = open("score.txt", "r", encoding="utf8")
for line in score_file.readlines():
    print(line, end="")
score_file.close()


# pickle
# 프로그램상에서의 데이터를 파일형태로 저장
import pickle

# "wb" = 쓰기 및 바이너리
# pickle은 바이너리 타입으로 해야하며 인코딩이 필요없다.
profile_file = open("profile.pickle", "wb")
profile = {"이름":"박명수", "나이":30, "취미":["골프, 축구, 코딩"]}
# profile 정보를 파일에 저장
pickle.dump(profile, profile_file)
profile_file.close()

profile = {}

# "rb" = 읽기 및 바이너리
profile_file = open("profile.pickle", "rb")
# 파일에 있는 정보를 불러오기
profile = pickle.load(profile_file)
print(profile)
profile_file.close()

# with
# 파일 열기, 처리, 닫기 과정을 편하고 간결하게!
with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))
# with문을 빠져나갈때 자동으로 close

with open("study.txt", "w", encoding="utf8") as study_file:
    study_file.write("파이썬 공부중!")

with open("study.txt", "r", encoding="utf8") as study_file:
    print(study_file.read())


# Quiz
for num in range(1, 51):
    file_name = "{0}주차.txt".format(num)
    with open(file_name, "w", encoding="utf8") as file:
        file.write("- {0} 주차 주간보고 -\n".format(num))
        file.write("부서 :\n")
        file.write("이름 :\n")
        file.write("업무 요약 :\n")
Comments