def 함수이름(매개변수(생략가능)):
내용
return 변수 #함수가 일 수행 후 그 결과를 반환
# 함수 생성 매개인자 없음, 리턴값도 없음
def board_delete():
pass
# 매개인자 있음, 리턴값 없음
def board_delete(a, b):
pass
# 매개인자는 없음, 리턴값 있음
def server_connet():
flag = False
~~~
flag = True
return flag #리턴값이 있을때 필수
# 매개인자 있음, 리턴값 있음
def Cal(a,b):
hap = a + b
return = hap
x, y = 5, 4
tot = Cal(x,y)
def fun_name(pra):
code1
code2
...
return 반환되는값
함수와 블랙 박스
블랙박스
- 내부 동작 방식은 보이지 않고, 입력 -> 처리 -> 출력만 보이는 시스템
- 함수도 블랙 박스처럼, 내부 로직을 몰라도 입력하면 결과
- 함수도 블랙 박스처럼, 내부 로직을 몰라도 입력하면 결과를 반환하는 방식으로 동작
def greet(*names):
for name in names:
print('안녕하세요', name, '씨')
greet('홍길동', '양만춘', '이순신') # 인자가 3개
greet('James', 'Thomas') # 인자가 2개
>>>
안녕하세요 홍길동 씨
안녕하세요 양만춘 씨
안녕하세요 이순신 씨
안녕하세요 James 씨
안녕하세요 Thomas 씨
# 모듈 전체를 가져오는 방법
import 모듈
# 모듈 내에서 필요한 부분만 가져오는 방법
from 모듈 import 이름
#game.py
# 임의의 모듈
def Game(x):
today_game = ' '
if(x == 1 ):
today_game = '몬스터 헌터 월드'
elif(x == 0):
today_game = '포켓로그'
else:
today_game = '로스트 아크'
return today_game
def exercise(x):
today_ex = ' '
if(x == 1):
today_ex = '계단 운동'
elif(x == 0):
today_ex = '팔굽혀펴기'
else:
today_ex = '오늘은 쉬는날'
return today_ex
def Music(x):
today_mu = ' '
if(x == 1 ):
today_mu = '발라드'
elif(x == 0):
today_mu = '팝송'
else:
today_mu = 'j-pop'
return today_mu
def play():
print('game.py문서의 play함수')
print('운동 하기')
print('뮤직 play')
# game.py를 import 하기
import game
import random
# from 문서이름 import 함수이름만 명시 -> 머신러닝에서 많이 사용하는 방법
from game import exercise
rm_game = 0
rm_exercise = 0
rm_music =0
rm_count = random.randrange(0,2)
rm_exercise = random.randrange(0,2)
rm_music = random.randrange(0,2)
result_game = game.Game(rm_count)
print(result_game)
result_ex = exercise(rm_count)
print(result_ex)
실행 결과
조건
1. 중복 숫자가 없어야 함
2. set()집합 사용 X
import random
lotto = set()
num = 0
while len(lotto) < 6:
num = random.randrange(1,45)
lotto.add(num)
lotto_list = list(lotto)
lotto_list.sort()
print(lotto_list)
import random
lotto = []
for i in range(7):
i = random.sample(range(1,45))
lotto.append(i)
lotto.sort()
print(lotto)
문제점: 중복 숫자가 나올 수 있음
import random
lotto = list()
num = 0
def ran_lotto_number(lotto_list): # 랜덤 함수 번호 생성해주는 함수
while len(lotto_list) < 6:
num = random.randrange(1,45)
if num not in lotto_list:
lotto_list.append(num)
lotto_list.sort() # 로또번호 정렬
return lotto_list
def view_lotto_number(): # 로또 번호 리스트를 보여주는 함수
view_lotto = ran_lotto_number(lotto)
print(view_lotto)
view_lotto_number()