
함수 : 여러 명령들을 하나의 이름을 가진 코드블록으로 묶어주는 방법
def my_function(something):
#Do this with something
#Then do this
#Finally do this
my_function(123)
매개변수 = 파라미터(parameter)전달인자 = 아규먼트(argument)# 입력값이 없는 함수
def greet():
print("Hello")
print("How do you do?")
print("Isn't the weather nice today?")
greet()
# 입력값이 있는 함수
def greet_with_name(name):
print(f"Hello {name}")
print(f"How do you do {name}?")
print(f"Isn't the weather nice today {name}?")
greet_with_name("Angela")
다수의 파라미터가 존재하는 경우 위치 인자 또는 키워드 인자를 사용
위치 인자 (positional arguments)
def my_function(a, b, c):
#Do this with a
#Then do this with b
#Finally do this with c
my_function(1, 2, 3)
키워드 인자 (keyword arguments)
def my_function(a, b, c):
#Do this with a
#Then do this with b
#Finally do this with c
my_function(a=1, b=2, c=3)
def greet_with(name, location):
print(f"Hello, {name}")
print(f"What is it like in {location}?")
greet_with(location="England", name="Angela")
Paint Area Calculator
주어진 면적을 칠하기 위해 몇 통의 페인트가 필요한지 계산하는 프로그램
- 페인트 1통은 만큼의 벽을 칠할 수 있다고 가정 (coverage per can = 5)
- 공식 : number of cans = (wall height x wall width) ÷ coverage per can
- 페인트는 무조건 한 통 단위로만 팔기 때문에 소수점이 나오면 올림해야 함
- math.ceil(x) : math 모듈의 ceil은 숫자 와 같거나 더 큰 정수들 중 최소값을 반환
# Write your code below this line 👇
from math import ceil
def paint_calc(height, width, cover):
number_of_cans = ceil((height * width) / cover)
print(f"You'll need {number_of_cans} cans of paint.")
# Write your code above this line 👆
# Define a function called paint_calc() so the code below works.
# 🚨 Don't change the code below 👇
test_h = int(input()) # Height of wall (m)
test_w = int(input()) # Width of wall (m)
coverage = 5
paint_calc(height=test_h, width=test_w, cover=coverage)
Prime Numbers
입력한 숫자가 소수인지 아닌지 확인하는 프로그램
- 소수(prime number) : 자기 자신과 1 외에 다른 숫자로는 나눌 수 없는 숫자
- 최대 입력값은 100 이하라고 가정
# Write your code below this line 👇
def prime_checker(number):
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
if is_prime: # for문 종료 후 is_prime의 값 확인
print("It's a prime number.")
else:
print("It's not a prime number.")
# Write your code above this line 👆
#Do NOT change any of the code below👇
n = int(input()) # Check this number
prime_checker(number=n)
고전적인 암호화 방식인 카이사르 암호로 메시지를 암호화/복호화 하는 프로그램
🔍 유의 사항
- 암호화는 메시지의 각 알파벳을 정해진 수(shift number) 만큼의 뒤에 있는 알파벳으로 변경
- shift number 0 : A → A (이동 없음)
- shift number 1 : A → B (1만큼 이동)
...- 아규먼트와 파라미터의 구분을 위해 서로 다른 이름 지어주기
- 첫 단계에서는 암호화만 구현하므로 direction은 무시하고 넘어가기
- 리스트에서 사용 가능한 메서드
list.index(elmnt) : 리스트에서 괄호 안의 값이 처음으로 나오는 위치의 인덱스 값 반환- IndexError: list index out of range
('z'와 같이 리스트의 끝에 가까운 인덱스 값에 shift number를 더하면 범위 밖으로 나가기 때문)
- 작성한 코드에서 해결방법
- if문으로 이동 수를 더한 인덱스 값이 25를 넘어갈 경우 26을 빼서 다시 0부터 시작하도록 만듦
- 강의 해결방법
- alphabet 리스트의 원소 전체('a' ~ 'z')를 복사하여 'z' 뒤에 붙여넣기
- index() 함수는 찾는 원소가 가장 처음 위치한 인덱스를 반환하므로 뒤에 붙여넣은 곳까지 가지 않음
- 함수가 길어지지 않기 때문에 깔끔한 방법
⌨️ 작성한 코드
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'
]
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def encrypt(plain_text, shift_amount):
#TODO-2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text.
#e.g.
#plain_text = "hello"
#shift = 5
#cipher_text = "mjqqt"
#print output: "The encoded text is mjqqt"
cipher_text = ""
for letter in plain_text:
index_before = alphabet.index(letter)
index_after = index_before + shift_amount
##🐛Bug alert: What happens if you try to encode the word 'civilization'?🐛
if index_after > 25:
index_after -= 26
cipher_text += alphabet[index_after]
print(f"The encoded text is {cipher_text}")
#TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.
encrypt(text, shift)
🔍 유의 사항
- 복호화는 암호화와 반대로 뒤로 이동했던 숫자만큼 앞으로 이동
- 음수 인덱스는 맨 뒤 원소부터 역순으로 접근하므로 alphabet 리스트에 다른 조치 필요 없음
- alphabet[-1] = 'z'
- alphabet[-2] = 'y'
...
⌨️ 작성한 코드
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',
'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'
]
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def encrypt(plain_text, shift_amount):
cipher_text = ""
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
cipher_text += alphabet[new_position]
print(f"The encoded text is {cipher_text}")
#TODO-1: Create a different function called 'decrypt' that takes the 'text' and 'shift' as inputs.
def decrypt(cipher_text, shift_amount):
#TODO-2: Inside the 'decrypt' function, shift each letter of the 'text' *backwards* in the alphabet by the shift amount and print the decrypted text.
#e.g.
#cipher_text = "mjqqt"
#shift = 5
#plain_text = "hello"
#print output: "The decoded text is hello"
plain_text = ""
for letter in cipher_text:
position = alphabet.index(letter)
new_position = position - shift_amount
plain_text += alphabet[new_position]
print(f"The decoded text is {plain_text}")
#TODO-3: Check if the user wanted to encrypt or decrypt the message by checking the 'direction' variable. Then call the correct function based on that 'drection' variable. You should be able to test the code to encrypt *AND* decrypt a message.
if direction == "encode":
encrypt(plain_text=text, shift_amount=shift)
elif direction == "decode":
decrypt(cipher_text=text, shift_amount=shift)
else:
print("You typed the wrong word. Please type 'encode' or 'decode'.")
🔍 유의 사항
- 암호화와 복호화 과정은 거의 같기 때문에 하나로 합쳐 간단하게 하기
- 복호화는 입력한 이동 수만큼 앞으로 가기 때문에, 이동 수에 을 곱하면 됨
print(f"The {cipher_direction}d text is {output_text}")에서
{cipher_direction} 뒤에 d 잊으면 안 됨 (encode or decode + d)
⌨️ 작성한 코드
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',
'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'
]
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-1: Combine the encrypt() and decrypt() functions into a single function called caesar().
def caesar(input_text, shift_amount, cipher_direction):
output_text = ""
if cipher_direction == "decode":
shift_amount *= -1
for letter in input_text:
position = alphabet.index(letter)
new_position = position + shift_amount
output_text += alphabet[new_position]
print(f"The {cipher_direction}d text is {output_text}")
#TODO-2: Call the caesar() function, passing over the 'text', 'shift' and 'direction' values.
caesar(text, shift, direction)
🔍 유의 사항
- 아스키 아트 추가
- 버그 대처하기
- 유저가 이동 수를 alphabet의 길이보다 훨씬 큰 수로 입력했을 경우
- 입력한 수를 0에서 25 사이의 수로 변환해야 함
- 나머지 연산 % 이용
- 유저가 숫자, 기호, 공백 등의 문자를 넣을 경우
- alphabet 리스트 안에 해당 문자가 있는지 확인하고 없다면 변경없이 새 문자열에 추가
- 암호화/복호화 후 프로그램을 다시 시작할 것인지 묻기
📄 hangman_art.py
아스키 아트 저장
⌨️ main.py
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',
'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(start_text, shift_amount, cipher_direction):
end_text = ""
if cipher_direction == "decode":
shift_amount *= -1
for char in start_text:
#TODO-3: What happens if the user enters a number/symbol/space?
#Can you fix the code to keep the number/symbol/space when the text is encoded/decoded?
#e.g. start_text = "meet me at 3"
#end_text = "•••• •• •• 3"
if char in alphabet:
position = alphabet.index(char)
new_position = position + shift_amount
end_text += alphabet[new_position]
else:
end_text += char
print(f"Here's the {cipher_direction}d result: {end_text}")
#TODO-1: Import and print the logo from art.py when the program starts.
import art
print(art.logo)
#TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program?
#e.g. Type 'yes' if you want to go again. Otherwise type 'no'.
#If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again?
#Hint: Try creating a while loop that continues to execute the program if the user types 'yes'.
restart = True
while restart:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet?
#Try running the program and entering a shift number of 45.
#Add some code so that the program continues to work even if the user enters a shift number greater than 26.
#Hint: Think about how you can use the modulus (%).
shift = shift % 26
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
result = input("Do you want to run again? Type 'yes' or 'no':\n").lower()
if result == "no":
restart = False
print("Goodbye")
[ 출력 결과 ]
,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba,
a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8
8b ,adPPPPP88 8PP" `"Y8ba, ,adPPPPP88 88
"8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88
`"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88
88 88
"" 88
88
,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba,
a8" "" 88 88P' "8a 88P' "8a a8P_____88 88P' "Y8
8b 88 88 d8 88 88 8PP" 88
"8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88
`"Ybbd8"' 88 88`YbbdP"' 88 88 `"Ybbd8"' 88
88
88
Type 'encode' to encrypt, type 'decode' to decrypt:
❚encode
Type your message:
❚Hello! @$ 63847
Type the shift number:
❚5
Here's the encoded result: mjqqt! @$ 63847
Do you want to run again? Type 'yes' or 'no':
❚yes
Type 'encode' to encrypt, type 'decode' to decrypt:
❚decode
Type your message:
❚mjqqt! @$ 63847
Type the shift number:
❚5
Here's the decoded result: hello! @$ 63847
Do you want to run again? Type 'yes' or 'no':
❚no
Goodbye