[udemy] Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복을 통해 학습하고 있습니다.
Function(함수)
- 기존 함수와 달리 함수에 변수를 제공하여 변수가 코드 블록(함수 내)에서 사용될 수 있음.
- 실제 변수에 값을 전달하려면 함수를 호출할 때 괄호 안에 데이터를 추가해야함.
- 데이터가 추가된 코드가 실행되면, 컴퓨터는 함수가 선언된 위치를 찾고 123이라는 데이터를 something이라는 변수에 전달함.
- my_function이라는 함수 내에서 변수가 123과 같아지고, 코드 블록 내에서 something 변수를 사용 할 수 있음.
def my_function(something):
# Do this
# Then do this
# Finally do this
# 123이라는 데이터를 추가하는 경우
my_function(123)
def great_with_name(name):
print(f"Hello {name}")
print(f"How do you do {name}")
great_with_name("joy")
# 결과
Hello joy
How do you do joy
✓ 입력 값이 있는 함수를 사용할 때 구분해야 할 두 가지 중요한 요소가 있음.
함수를 호출하고 데이터를 전달할 때, something이라는 새로운 변수를 만들어 입력된 데이터를 변수에 할당함
※ 이를 프로그래밍 용어로 매개변수(Parameter)라고 하고, 입력된 데이터를 데이터 인자(Argument)라고 함.
인자는 함수가 호출될 때 전달되는 실제 데이터이며, 매개변수는 그 데이터의 이름이 됨.
실습1: 삶을 주(Week)로 표현하기
- 90세까지 사는 경우 우리가 남은 주 수를 알려주는 수학과 f-String을 사용한 life_in_weeks() 함수를 만들어보세요.
현재 나이를 입력으로 사용하고 다음 형식으로 우리가 남은 시간을 나타내는 메시지를 출력함.
"You have x weeks left."
여기서 x는 입력된 나이부터 90세까지 남은 주수로 계산된 실제 숫자로 대체됨.
input example: 56
output example: You have 1768 weeks left.
def life_in_weeks(age):
input_age = 90 - age
weeks = input_age * 52
print(f"You have {weeks} weeks left.")
life_in_weeks(30)
# 결과
You have 3120 weeks left.
→ 현재 나이를 받아서 90세에서 현재 나이를 뺀 다음, 1년은 52주이기 때문에 앞으로 살 나이 * 52를 하여 남은 주 수를 알려줌.
여러 개의 입력값을 허용하는 함수
❓ Qusetion
Q1. Create a function with multiple inputs.
def great_with(name, location):
Q2. Modify the function so that it prints the expected values.
def great_with(name, location):
print(f"Hello {name}")
print(f"What is it like in {location}")
great_with("joy","LA")
# 결과
Hello joy
What is it like in LA
위치 인자(Positional Argument)
- 위 great_with 함수에서 name과 location을 바꿔서 호출하면 입력한 대로 출력되는 것을 확인하라 수 있음.
- 함수 호출 시, 특정 매개 변수에 어떤 데이터를 연결할지 지정하지 않아 위치를 보고 할당하는데 이를 파이썬에서 Positional Argument라고 부름.
def great_with(name, location):
print(f"Hello {name}")
print(f"What is it like in {location}")
great_with("LA","joy")
# 결과
Hello LA
What is it like in joy
키워드 인자(Keyword Arguments)
- 함수를 호출 할 때 위와 같은 문제가 발생되지 않도록 하기 위해서는 키워드 인자라는 것을 사용할 수 있음.
- 각 매개변수 이름과 등호를 추가해서 첫 번째 매개변수 name은 joy, 두 번째 location은 LA가 되도록 할 수 있음.
def great_with(name, location):
print(f"Hello {name}")
print(f"What is it like in {location}")
great_with(location="LA", name="joy")
# 결과
Hello joy
What is it like in LA
실습2: 사랑 계산기 만들기
- 두 이름 사이의 호환성을 테스트하는 calculate_love_score() 함수를 작성
- count()와 lower() 함수를 사용
두 사람 사이의 사랑 점수를 계산하려면:
1. 두 사람의 이름을 가져와 각 단어에서 'TRUE' 단어의 등장 횟수를 확인
2. 그럼, 단어 "LOVE" 안의 각 알파벳이 몇 번 나타나는지 확인
3. 이 숫자들을 결합하여 2자리 숫자를 만들고 출력
example:
name1 = "Angela Yu" name2 = "Jack Bauer"
T 0회 발생
R 1회 발생
U 2회 발생
E는 2회 발생
Total = 5
L 1회 발생
O 0회 발생
V 0회 발생
E 2회 발생
Total = 3
Love Score = 53
- input example: calculate_love_score("Kanye West", "Kim Kardashian")
- result example: 42
def calculate_love_score(name1, name2):
count_true = name1.lower().count("t") + name1.lower().count("r") + name1.lower().count("u") + name1.lower().count("e") + name2.lower().count("t") + name2.lower().count("r") + name2.lower().count("u") + name2.lower().count("e")
count_love = name1.lower().count("l") + name1.lower().count("o") + name1.lower().count("v") + name1.lower().count("e") + name2.lower().count("l") + name2.lower().count("o") + name2.lower().count("v") + name2.lower().count("e")
true_love = str(count_true) + str(count_love)
print(true_love)
calculate_love_score("Kanye West", "Kim Kardashian")
→ name1과 name2를 받아서 소문자로 변경하고 "true", "love" 각 알파벳들이 이름에 들어있는지 카운트하여 합침.
- count_true, count_love 변수는 int 타입이라 string 타입으로 바꾸고 그 두개를 합침.
- 그리고 출력하면 됨.
카이사르 암호 - 암호화
# TODO-1: 'original_text'와 'shift_amount'를 입력으로 사용하는 encrypt() 함수 만들기
# TODO-2: encrypt()함수 내부에서 'original_text'의 각 문자를 알파벳 순으로 이동(스프트 수에 따라 암호화된 텍스트를 출력)
# TODO-3: encrypt() 함수를 호출하고 사용자에게 추가 입력을 받음.
# TODO-4: z를 앞으로 9 만큼 이동하려고 하면 어떻게 되는지, 코드를 코칠 수 있는지 확인
TODO-1 [Code]
def encrypt(original_text, shift_amount):
TODO-2 [Code]
def encrypt(original_text, shift_amount):
new_text = ""
for plain in original_text:
count = alphabet.index(plain) + shift_amount
new_text += alphabet[count]
print(f"Here is the encoded result: {new_text}")
TODO-3 [Code]
encrypt(original_text=text, shift_amount=shift)
TODO-4 [Code]
def encrypt(original_text, shift_amount):
new_text = ""
for plain in original_text:
count = alphabet.index(plain) + shift_amount
count %= len(alphabet)
new_text += alphabet[count]
print(f"Here is the encoded result: {new_text}")
카이사르 암호 - 복호화
# TODO-5: decrypt()라는 함수를 만들고 'original_text'와 'shift_amount' 두 개의 입력 값을 받음
# TODO-6: original_text의 각 문자를 알파벳에서 거꾸로 이동하여 원본 텍스트로 디코딩 후 복호화된 텍스트를 출력
# TODO-7: encrypt()와 decrypt() 함수를 caesar() 단일 함수로 결합하고 If문으로 'encode' 할지 'decode' 할지 결정하기
TODO-5 [Code]
def decrypt(original_text, shift_amount):
TODO-6 [Code]
def decrypt(original_text, shift_amount):
back_text = ""
for text2 in original_text:
back_position = alphabet.index(text2) - shift_amount
back_position %= len(alphabet)
back_text += alphabet[back_position]
print(f"Here is the decode result: {back_text}")
TODO-7 [Code]
def caesar(original_text, shift_amount, encode_or_decode):
cipher_text = ""
for letter in original_text:
if encode_or_decode == "decode":
shift_amount *= -1
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
cipher_text += alphabet[shifted_position]
print(f"Here is the {encode_or_decode}d result: {cipher_text}")
카이사르 암호 - 마지막
# TODO-8: art.py 에서 로고를 가져와 출력하기
# TODO-9: 만약 입력 값에 알파벳이 아닌 다른 것이 들어와도 출력되게 만들기
# TODO-10: 프로그램을 다시 실행할 것인지 종료할 것인지 결정하게 하기
TODO-8 [Code]
from art import logo
print(logo)
TODO-9 [Code]
def caesar(original_text, shift_amount, encode_or_decode):
output_text = ""
for letter in original_text:
if letter not in alphabet:
output_text += letter
else:
if encode_or_decode == "decode":
shift_amount *= -1
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the {encode_or_decode}d result: {output_text}")
TODO-10 [Code]
want_continue = True
while want_continue:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)
restart = input("Type 'yes' if you want to go again. Otherwise type 'no'. \n").lower()
if restart == "no":
want_continue = False
print("Good Bye!")
[전체 Code]
from art import logo
print(logo)
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def caesar(original_text, shift_amount, encode_or_decode):
output_text = ""
for letter in original_text:
if letter not in alphabet:
output_text += letter
else:
if encode_or_decode == "decode":
shift_amount *= -1
shifted_position = alphabet.index(letter) + shift_amount
shifted_position %= len(alphabet)
output_text += alphabet[shifted_position]
print(f"Here is the {encode_or_decode}d result: {output_text}")
want_continue = True
while want_continue:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)
restart = input("Type 'yes' if you want to go again. Otherwise type 'no'. \n").lower()
if restart == "no":
want_continue = False
print("Good Bye!")
p.s 주말에 이거 다시 해봐야할 거 같다...
'Language > Python' 카테고리의 다른 글
[Section9] 딕셔너리(Dictionaries) (0) | 2025.01.17 |
---|---|
[Section7] 게임 프로젝트(행맨) (0) | 2025.01.14 |
[Section6] 파이썬 함수와 카렐 (0) | 2025.01.13 |
[Section5] 파이썬 반복문 (0) | 2025.01.13 |
[Section4] 파이썬 리스트 (0) | 2025.01.12 |