파이썬/파이썬 기초

파이썬 기초 03 - if/for/while/함수

H-V 2021. 10. 29. 18:19

유투버 '나도코딩'님 강의 참조

 

 

01 if

  • if 조건 : 실행 명령문 순으로 조건이 True일 경우에만 명령문 실행
  • 파이썬에서는 'elif'로 조건절 처리
# weather = "sunny"
# weather = input("How is the weather today? -> ")

# if weather == "rain" or weather == "snow":
#     print("You should take an umbrella")
# elif weather == "cloudy":
#     print("You should take a jacket")
# else:
#     print("The weather is truly fine!")

temp = int(input("what temperature is it today? -> "))

if 30 <= temp:
    print("It is so hot! Stay at home")
elif 20 <= temp and temp < 30:
    print("Not bad today! Up to you")
elif 0 <= temp < 10:
    print("too cold!")
else:
    print("I do not know where the hell we are")

what temperature is it today? -> -5 
I do not know where the hell we are

 

 

 

02 for

  • for문 또한 자바랑 다르게 작성법이 엄청 간단 하다
# for waiting_no in [0,1,2,3,4]:
#     print("대기번호: {0}".format(waiting_no))

# for i in range(5):
#     print("The number is: {0}".format(i))

starbucks = ["IronMan", "Thor", "Groot"]

for customer in starbucks:
    print("{0}, here is your coffee!".format(customer))
    
대기번호: 0
대기번호: 1
대기번호: 2
대기번호: 3
대기번호: 4

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4

IronMan, here is your coffee!
Thor, here is your coffee!
Groot, here is your coffee!

 

 

03 while

  • true/false 값에 따라 반복문을 구현하고싶을때는 while문을 쓰자
  • VS Code에서 무한 루프시 빠져나올때에는 'Ctrl + c'
# customer = "Thor"
# index = 5

# while index >= 1:
#     print("{0}, here is your coffee!".format(customer))
#     print("We will throw it away if you do not come here in {0}".format(index))
#     index -= 1
#     if index == 0:
#         print("Ok your coffee is gone")

customer = "Thor"
person = "Unkown"

while person != customer :
    print("{0}, here is your coffee!".format(customer))
    person = input("Your name?: ->")
    if (person == customer):
        print("You can take this coffee")
    else:
        print("You are not Thor. Go away!")
        
Thor, here is your coffee!
We will throw it away if you do not come here in 5
Thor, here is your coffee!
We will throw it away if you do not come here in 4
Thor, here is your coffee!
We will throw it away if you do not come here in 3
Thor, here is your coffee!
We will throw it away if you do not come here in 2
Thor, here is your coffee!
We will throw it away if you do not come here in 1
Ok your coffee is gone

Thor, here is your coffee!
Your name?: ->Sehwan
You are not Thor. Go away!
Thor, here is your coffee!
Your name?: ->Thor
You can take this coffee

 

 

 

04 continue & break

  • continue - continue 이후 코드를 실행하지말고 다시 반복문 처음으로가서 실행
    absent = [2,5]
    for student in range(1, 7):
        if student in absent:
            continue
        print("Number {0} student, please read the page".format(student))
        
    Number 1 student, please read the page
    Number 3 student, please read the page
    Number 4 student, please read the page
    Number 6 student, please read the page​
  • breake - break 이후 무조건 반복문을 멈추고 반복문 탈출 
    absent = [2,5]
    no_book = [6]
    for student in range(1, 7):
        if student in absent:
            continue
        elif student in no_book:
            print("How dare you! Number {0} student, come with me to the teacher room!".format(student))
            break
        print("Number {0} student, please read the page".format(student))
    
    Number 1 student, please read the page
    Number 3 student, please read the page
    Number 4 student, please read the page
    How dare you! Number 6 student, come with me to the teacher room!​
  • 한줄 for문
    students = [1,2,3,4,5]
    students = [i+10 for i in students]
    print(students)
    
    #리스트의 값을들 하나씩 불러와서 길이 카운트
    heros = ["IronMan", "Thor", "Groot"]
    heros = [len(i) for i in heros]
    print(heros)
    
    names = ["cha","park","kim"]
    names = [i.upper() for i in names]
    print(names)
    
    [11, 12, 13, 14, 15]
    [7, 4, 5]
    ['CHA', 'PARK', 'KIM']​

 

퀴즈 1)

승객 수 구하기

조건 1) 50명의 승객과 매칭하는데 승객별 운행 시간은 5~50분 사이의 랜덤
조건 2) 당신은 소요시간 5~15분만 걸리는 승객만 태움

cnt = 0 # 총 탑승 승객
for i in range(1, 51):
    time = randint(5, 51) #randrange 동일
    if 5 <= time <= 15: #5~15분 이내
        print("[O] {0}번째 손님 (소요시간 : {1}분)".format(i, time))
        cnt += 1
    else: #매칭 실패
        print("[ ] {0}번째 손님 (소요시간 : {1}분)".format(i, time))

print("총 탑승 승객 : {0}분".format(cnt))

*내가 직접했을때는 너무 복잡하게 생각했다. 
For문을 도니 포문이 51번 돌동안 랜덤한 randint/randrange로
한번씩 돌때마다 랜덤한 값 하나씩 뽑아서 넣기만 하면 된다
더보기

[ ] 1번째 손님 (소요시간 : 23분)
[ ] 2번째 손님 (소요시간 : 30분)
[ ] 3번째 손님 (소요시간 : 34분)
[ ] 4번째 손님 (소요시간 : 41분)
[ ] 5번째 손님 (소요시간 : 46분)
[ ] 6번째 손님 (소요시간 : 39분)
[O] 7번째 손님 (소요시간 : 10분)
[ ] 8번째 손님 (소요시간 : 16분)
[ ] 9번째 손님 (소요시간 : 37분)
[ ] 10번째 손님 (소요시간 : 22분)
[ ] 11번째 손님 (소요시간 : 42분)
[ ] 12번째 손님 (소요시간 : 33분)
[ ] 13번째 손님 (소요시간 : 25분)
[ ] 14번째 손님 (소요시간 : 37분)
[O] 15번째 손님 (소요시간 : 13분)
[ ] 16번째 손님 (소요시간 : 26분)
[O] 17번째 손님 (소요시간 : 11분)
[ ] 18번째 손님 (소요시간 : 38분)
[ ] 19번째 손님 (소요시간 : 20분)
[ ] 20번째 손님 (소요시간 : 45분)
[ ] 21번째 손님 (소요시간 : 35분)
[O] 22번째 손님 (소요시간 : 15분)
[ ] 23번째 손님 (소요시간 : 42분)
[ ] 24번째 손님 (소요시간 : 50분)
[ ] 25번째 손님 (소요시간 : 37분)
[O] 26번째 손님 (소요시간 : 11분)
[ ] 27번째 손님 (소요시간 : 32분)
[ ] 28번째 손님 (소요시간 : 16분)
[ ] 29번째 손님 (소요시간 : 21분)
[O] 30번째 손님 (소요시간 : 7분)
[O] 31번째 손님 (소요시간 : 10분)
[ ] 32번째 손님 (소요시간 : 28분)
[O] 33번째 손님 (소요시간 : 8분)
[ ] 34번째 손님 (소요시간 : 29분)
[ ] 35번째 손님 (소요시간 : 22분)
[ ] 36번째 손님 (소요시간 : 22분)
[O] 37번째 손님 (소요시간 : 13분)
[ ] 38번째 손님 (소요시간 : 51분)
[ ] 39번째 손님 (소요시간 : 29분)
[ ] 40번째 손님 (소요시간 : 18분)
[O] 41번째 손님 (소요시간 : 11분)
[O] 42번째 손님 (소요시간 : 11분)
[ ] 43번째 손님 (소요시간 : 45분)
[ ] 44번째 손님 (소요시간 : 21분)
[O] 45번째 손님 (소요시간 : 12분)
[ ] 46번째 손님 (소요시간 : 36분)
[ ] 47번째 손님 (소요시간 : 32분)
[ ] 48번째 손님 (소요시간 : 47분)
[ ] 49번째 손님 (소요시간 : 23분)
[ ] 50번째 손님 (소요시간 : 50분)
총 탑승 승객 : 12분

 

 

05 함수

  • 어떤 특정한 역할을 하는 박스라고 보면 된다. 어떠한 값을 전달 받아서 그 값을 통해 특정한 기능도 수행 가능 하다
def open_account():
    print("An account was just opened")

open_account()

An account was just opened
  • 전달값 / 반환값
def open_account():
    print("An account was just opened")


def deposit(balance, money):
    print("Deposit completed. Your balance :{0}".format(balance + money))
    return balance + money

def withdraw(balance, money):
    if balance >= money:
        print("Withrdawl succeeded. Your balance : {0}".format(balance-money))
    else:
        print("Withrawal canceled. Your balance : {0}".format(balance))


def withdraw_night(balance, money):
    commission = 100
    return commission, balance - money - commission

# # balance = 100
# # deposit(balance, 2000)
# balance = 0
# balance = deposit(balance, 1000)
# # balance = withdraw(balance, 2000)
# balance = withdraw(balance, 500)

# balance = deposit(0, 1000)
# print(balance)
balance = 0
balance = deposit(balance, 1000)
commision, balance = withdraw_night(balance, 500)
print(commision, balance)

Deposit completed. Your balance :1000
100 400
  • return의 개념이 살짝 어려(?)운데 return값이 설정이 되어있지 않으면 변수를 통해서 넘기는 값은 함수에서 처리가 되지만 함수 이후에 리턴으로 아무것도 결과가 나오지 않기 때문에 변수의 값은 'none'으로 처리가 되어버린다. 즉 A라는 함수의 결과값이 필요하고 A 함수 실행 이후 그 결과값으로 추가적으로 진행이 필요하다면 반드시 return으로 함수의 결과값을 나타내줘야 한다

 

  • 기본값

어떠한 함수에 기본적으로 들어가는 값이면 기본값을 써서 표현하면 여러번 코딩 할 필요가 없다.

def profile(name, age=17, main_lang="Python"):
    print("Name:{0}\t Age:{1}\t Language:{2}" \
        .format(name,age,main_lang))

profile("Kim")

Name:Kim         Age:17  Language:Python
  • 키워드 값

키워드를 쓰면 순서에 관계없이 변수를 넣을 수 있다

def profile(name, age, main_lang):
    print(name, age, main_lang)

profile(name="Kim", main_lang="Python", age=18)
profile(age=20, name="Vic", main_lang="C++")

Kim 18 Python
Vic 20 C++
  • 가변인자 

같은 주제에서 다른 여러값을 넣을때에는 '*'로 표시를 하면 된다!

def profile(name, age, *language):
    print("Name: {0} Age:{1}".format(name,age), end=" ")
    for lang in language:
        print(lang, end=" ")
    print()

profile("Kim", 22, "Python", "Java", "C", "C++", "C#")
profile("Vic", 33, "Kotlin", "Swift")

Name: Kim Age:22 Python Java C C++ C# 
Name: Vic Age:33 Kotlin Swift