def add(a,b):
return a+b
print(add(1,2))
print(add('abc', 'def'))
print(add([1, 2, 3], [4, 5, 6]))
a=[12, 'abcde', [3,4,5]]
a.append('add')
print(a)
a = 10
b = 20
c = 30
a + b + c
n = 5
n = n + 1
n = n + 1
n
a = 5
b = a + x # 에러!
a = 5
x = 2.5
b = a + x
b
side1 = 5 # 한쪽 변 초기화.
side2 = 12 # 다른쪽 변 초기화.
hyp = (side1 * side1 + side2 * side2) ** 0.5
print(hyp) # 빗변 계산 결과 출력.
파이썬 식별자는 변수, 함수, 모듈, 클래스 또는 객체를 식별하는데 사용되는 이름이다.
식별자의 조건
i = 10
thou = 20
a_jug_of_wine = 30
loaf_of_bread = 40
inspiration = i + thou + a_jug_of_wine + loaf_of_bread
print(inspiration, 'percent good')
import keyword
print(keyword.kwlist)
print()
print(len(keyword.kwlist))
x = 1
x = 2
n = 10 # n은 10의 이름이다.
n = n + 1 # n은 11의 이름이다.
n = n + 1 # n은 12의 이름이다.
n = 0 # n은 반드시 수정되기 전에 존재해야 한다.
n += 1 # n = n + 1과 동일함
n += 10 # n = n + 10과 동일함
n *= 2 # n = n * 2과 동일함
n -= 1 # n = n - 1과 동일함
n /= 3 # n = n / 3과 동일함
hypot = (a * a + b * b) ** 0.5
print(hypot)
x = 5 # x는 정수다
print(type(x), x)
x = 7.3 # x 는 실수다
print(type(x), x)
x = 5.0
print(type(x), x)
google = 10 ** 100 # 10의 100 제곱수 계산
print(type(google), google)
x = 4 / 2 # 결과는 2.0
print(type(x), x)
x = 7 / 4 # 결과는 1.75
print(type(x), x)
x = 4 // 2 # 결과는 2
print(type(x), x)
7 // 4 # 결과는 1
divmod(7, 4)
23 // 5 # 결과는 4
divmod(23, 5)
8.0 // 2.5 # 결과는 3.0
divmod(8.0, 2.5)
23 % 5 # 결과는 3
divmod(23, 5)
7 / 2 # 결과는 3 (파이썬 2.0)
7 / 2.0 # 결과는 3.5
7 / float(2) # 결과는 3.5
quot, rem = divmod(23, 10)
quot
rem
n = int(input('정수 숫자를 입력하라: '))
x = float(input('부동소수점 숫자를 입력하라 : '))
side1 = float(input('한 변의 길이를 입력하라: '))
side2 = float(input('다른 한 변의 길이를 입력하라: '))
hyp = ((side1 * side1) + (side2 * side2)) ** 0.5
print('빗변의 길이는 다음과 같다:', hyp)
def main():
side1 = float(input('한 변의 길이를 입력하라: '))
side2 = float(input('다른 한 변의 길이를 입력하라: '))
hyp = (side1 * side1 + side2 * side2) ** 0.5
print('빗변의 길이는 다음과 같다: ', hyp)
def main():
side1 = float(input('한 변의 길이를 입력하라: '))
side2 = float(input('다른 한 변의 길이를 입력하라: '))
hyp = (side1 * side1 + side2 * side2) ** 0.5
print('빗변의 길이는 다음과 같다: ', hyp)
def main():
age = int(input('나이를 입력하라: '))
name = input('이름을 입력하라: ')
if age < 30:
print('안녕하세요', name)
print('30세이하군요.')
print('정말 어리네요.')
main()
def main():
age = int(input('나이를 입력하라: '))
name = input('이름을 입력하라: ')
if age < 30:
print('안녕하세요', name)
print('30세이하군요.')
print('정말 어리네요.')
main()
def main():
side1 = float(input('한 변의 길이를 입력하라: '))
side2 = float(input('다른 한 변의 길이를 입력하라: '))
hyp = (side1 * side1 + side2 * side2) ** 0.5
print('빗변의 길이는 다음과 같다: ', hyp)
main()
main()
def add(a, b):
return a + b
print(add(3, 4))
print(add([1,2,3], [4,5,6]))
c = add(10, 30)
print(c)
f = add
print(f(4, 5))
print(f)
print(f is add)
def simple():
pass
print(simple())
def add(a, b):
return a + b
def myabs(x):
if x < 0:
x = -x
return x
def addabs(a, b):
c = add(a, b)
return myabs(c)
print(addabs(-5, -7))
def minus(a, b):
return a - b
print(minus(a=12, b=20))
print(minus(b=20, a=12))
def incr(x, y=1):
return x + y
print(incr(5))
print(incr(5, 10))
def calc(x, y):
return x + y, x - y, x * y, x / y
print(calc(10, 2))
def add(a, b):
return a + b
c = add(1, 3.4)
d = add('dynamic', 'typing')
e = add(['list'], ['and', 'list'])
print(c)
print(d)
print(e)
def sum(N):
if N == 1: # 종결 조건
return 1 # 종결 조건이 만족할 때의 반환 값
return N + sum(N-1) # 재귀 호출
print(sum(10))
def add(a, b):
return a + b
print(add)
c = add(10, 30)
print(c)
f = add
print(f(4, 5))
print(f)
print(f is add)
def simpleFunction():
pass
simpleFunction()
def addmember(members, newmember):
if newmember not in members: # 기존 멤버가 아니면
members.append(newmember) # 추가
members = ['hwang', 'lee', 'park', 'youn'] # 리스트에 초기 멤버 설정
addmember(members, 'jo') # 새로운 멤버 추가
addmember(members, 'hwang') # (이미 존재하는) 새로운 멤버 추가
print(members)
def f1(b):
b = 100
a = 200
f1(a)
print(a)
def f2(b):
b = "abc"
a = "def"
f2(a)
print(a)
def f3(b):
b = (1,2,3)
a = (4,5,6)
f3(a)
print(a)
def f4(b):
b[1] = 10
a = [4,5,6]
f4(a)
print(a)
def f5(b):
b['a'] = 10
a = {"a":1, "b":2}
f5(a)
print(a)
a = 5
b = 3
if a > b:
print('a는 b보다 크다')
c = 10
a = 3
b = 5
if a > b:
print('a는 b보다 크다')
c = 10
else:
print('a는 b보다 크지 않다')
c = -10
age = int(input('나이를 입력하라: '))
if age < 13:
print('당신은 사춘기를 겪지 않았다.')
elif age < 20:
print('당신은 십대 청소년이다.')
elif age <= 30:
print('당신은 여전히 젊다.')
else:
print('당신은 나이 든 사람이다.')
n = 10 # 어떤 양수 숫자로도 설정할 수 있다.
i = 1
while i <= n:
print(i, end=' ')
i += 1
def print_nums(n):
i = 1
while i <= n:
print(i, end=' ')
i += 1
print_nums(3)
print_nums(7)
print_nums(8)
n = 10 # n을 양수로 설정한다.
i = 1
while True: # 항상 실행하라!
print(i)
if i >= n:
break
i += 1
i = i + 1 # 현재 값에 1을 더하고 다시 대입하라
def pr_fibo(n):
a, b = 1, 0
while a < n:
print(a, sep=' ')
a, b = a + b, a
n = int(input('Input n: '))
pr_fibo(n)
a = 1
b = 0
temp = a
a = a + b
b = temp
from random import randint
n = randint(1, 50)
while True:
ans = int(input('어떤 숫자일까?: '))
if ans > n:
print('너무 높다! 다시 맞춰보자. ')
elif ans < n:
print('너무 낮다! 다시 맞춰보자.')
else:
print('축하한다! 숫자를 맞췄다!')
break
if not (age > 12 and age < 20):
print('당신은 십대가 아니다.')
if not (12 < age < 20):
print('당신은 십대가 아니다.')
print(6 == 9)
print(6 != 9)
print(1 > 3)
print(4 <= 5)
a = 5
b = 10
print(a < b)
a = 5
b = 10
print(0 < a < b)
a = 5
b = 10
print(0 < a and a < b)
a = 20
b = 30
print(a > 10 and b < 50)
print(a > 10 or b < 50)
print(True + 1)
print(False + 1)
print(False * 75)
print(True * 75)
print(bool(0)) # 정수 0은 거짓
print(bool(1))
print(bool(100))
print(bool(-100))
print()
print(bool(0.0)) # 실수 0.0은 거짓
print(bool(0.1))
print(bool(0.00000000000000000000000000000000000000000001))
print(bool('abc'))
print(bool('')) # 빈 문자열은 거짓
print()
print(bool([])) # 공 리스트는 거짓
print(bool([1,2,3]))
print()
print(bool(())) # 공 튜플은 거짓
print(bool((1,2,3)))
print()
print(bool({})) # 공 사전은 거짓
print(bool({1:2}))
print()
print(bool(None)) # None 객체는 거짓
print(1 and 2)
print(1 and 0)
print()
print(0 or 2)
print(1 or 0)
print()
print([] or 1) # [] 거짓
print([] or ()) # [], () 거짓
print([] and 1) # [] 거짓이므로 1은 참조할 필요 없음
print([[]] or 1) # [[]] 참으로 간주
print([{}] or 1) # [{}] 참으로 간주
print('' or 1) # 빈 문자열('')은 거짓
print(not(True))
print(not(1 and 2))
print(not('' or 1))
def double_it(n):
n = n * 2
x = 10
double_it(x)
print(x) # x는 여전히 10이다!
def set_values():
return 10, 20, 30
a, b, c = set_values()
def calc_hyp(a, b):
hyp = (a * a + b * b) ** 0.5
return hyp
def print_nums(n, rep=1):
i = 1
while i <= rep:
print(n)
i += 1
print_nums(5)
def a_func(a, b, c):
return (a + b) * c
print(a_func(4, c = 3, b = 2))
help(str)
s1 = '이것은 문자열이다.'
s2 = "이것 또한 문자열이다."
s3 = '''이것은 특별한
여러 줄의 문자열이다.'''
s3 = """이것은 특별한
여러 줄의 문자열이다."""
s1 = '”죽느냐 사느냐” 셰익스피어가 적었습니다.'
s2 = "나에게 가장 중요한 것은 ‘행복’이다."
print(s1)
print(s2)
'''당신은 “앨리스의 레스토랑”에서 그것을 얻을 수 없어.'''
s2 = '나에게 가장 중요한 것은 \‘행복\’이다.'
s = 'Hello'
s[0]
s1 = 'Abe'
s2 = 'Lincoln'
s1 = s1 + ' ' + s2
my_str = 'a'
my_str += 'b'
my_str += 'c'
[29, 31, 31]
['지희', '안나', '신후', '우진']
['우진', 9, '은희', 64 ]
a_list = []
while True:
s = input('이름을 입력하세요 : ')
if not s:
break
a_list.append(s)
a_list.sort()
print(a_list)
a = [1,2,3]
b = [10, a, 20]
c = ['x', a, 'y']
print(a)
print(b)
print(c)
for name in a_list:
print(name)
my_lst = [10, 15, 25]
for thing in my_lst:
thing *= 2
my_lst
my_lst = [10, 15, 25]
for i in [0, 1, 2]:
my_lst[i] *= 2
my_lst
my_lst = [100, 102, 50, 25, 72]
for i in range(5):
my_lst[i] *= 2
my_lst
my_lst = [100, 102, 50, 25, 72]
for i in range(len(my_lst)):
my_lst[i] *= 2
my_lst
n = int(input('양의 정수를 입력하라 : '))
prod = 1
for i in range(1, n + 1):
prod *= i
print(prod)
def my_func():
return [10, 20, 5]
my_lst = my_func()
my_lst
def a_func():
return 10, 20, 5
a, b, c = a_func()
def a_func():
return (10, 20, 5)
a, b, c = a_func()
grade_dict = { '단아':3.9, '민채':3.9, '예준':2.5 }
grade_dict['건아'] = 4.0
print(grade_dict['건아']) # 값 4.0을 출력한다
grade_dict = { }
s = (input('문자열을 입력하라 : ')).split()
wrd_counter = {}
for wrd in s:
wrd_counter[wrd] = wrd_counter.get(wrd, 0) + 1
wrd_counter
b_set1 = { '원준', '우진', '민준', '신후' }
b_set2 = { '원준', '민준', '신후', '우진' }
set1 = {1, 2, 3, 4, 5}
set2 = {5, 4, 3, 2, 1}
b_set1.remove('원준')
b_set1.add('강우')
b_set1
setA = {1, 2, 3, 4}
setB = {3, 4, 5}
setUnion = setA | setB # {1, 2, 3, 4, 5}
setIntersect = setA & setB # {3, 4}
setXOR = setA ^ setB # {1, 2, 5}
setSub = setA - setB # {1, 2}
count = 10 # 전역 변수 선언
def funcA():
count = 20 # 지역 변수 선언
print(count) # 지역 변수 20 출력
def funcB():
print(count) # 전역 변수 10 출력
def funcB():
count = 100 # 지역 변수로 변경됨.
# 전역 변수 count에 영향 없음
print(count) # 지역 변수 100 출력
funcB()
count = 10 # 전역 변수 생성
def my_func():
global count
count += 1
my_func() # my_func 함수 호출
print(count) # 11 출력
def my_func():
global foo
foo = 5 # 전역 변수 foo가
# 존재하지 않으면 생성한다.
print(foo)
my_func()
def incr(a, step=1):
return a + step
b = 1
b = incr(b) # 1 증가
print(b)
b = incr(b, 10) # 10 증가
print(b)
2 12
def incr(step=1, a):
return a + step
File "<ipython-input-2-a94c69ee2f0d>", line 1 def incr(step=1, a): ^ SyntaxError: non-default argument follows default argument
def incr(a, step=1, step2=10):
return a + step + step2
print(incr(10))
21
def area(height, width):
return height * width
#순서가 아닌 이름으로 값이 전달
a = area(height='height string ', width=3)
print(a)
b = area(width=20, height=10)
print(b)
height string height string height string 200
print(area(20, width=5))
100
area(width=5, 20)
# 기존: SyntaxError: non-keyword arg after keyword arg
File "<ipython-input-7-cb541d8d855b>", line 1 area(width=5, 20) ^ SyntaxError: positional argument follows keyword argument
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100))
212
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100, 200))
# 기존: SyntaxError: non-keyword arg after keyword arg
File "<ipython-input-9-7fc19c2524c1>", line 4 print(incr(10, 2, step2=100, 200)) ^ SyntaxError: positional argument follows keyword argument
def incr(a, step=1, step2=10, step3=100):
return a + step + step2 + step3
print(incr(10, 2, step2=100, step3=200))
312
*args
형식의 인수로 가변 인수를 선언할 수 있음*args
in function definitions in python is used to pass a variable number of arguments to a function.def myFun(*args):
print(type(args), args)
print()
for arg in args:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
<class 'tuple'> ('Hello', 'Welcome', 'to', 'GeeksforGeeks') Hello Welcome to GeeksforGeeks
def varg(a, *args):
print(a, args)
varg(1)
varg(2, 3)
varg(2, 3, 4, 5, 6)
1 () 2 (3,) 2 (3, 4, 5, 6)
def printf(format, *args):
print(format % args)
printf("I've spent %d days and %d night to do this", 6, 5)
I've spent 6 days and 5 night to do this
def myFun(**kwargs):
print(type(kwargs), kwargs)
print()
for key, value in kwargs.items():
print("{0}: {1}".format(key, value))
myFun(first ='Geeks', mid ='for', last='Geeks')
<class 'dict'> {'first': 'Geeks', 'mid': 'for', 'last': 'Geeks'} first: Geeks mid: for last: Geeks
def myFun(arg1, **kwargs):
for key, value in kwargs.items():
print ("{0} - {1}: {2}".format(arg1, key, value))
myFun("Hi", first ='Geeks', mid ='for', last='Geeks')
Hi - first: Geeks Hi - mid: for Hi - last: Geeks
*튜플변수
"를 이용하여 함수 호출이 가능def h(a, b, c):
print(a, b, c)
args = (1, 2, 3)
h(*args)
1 2 3
**사전변수
"를 이용하여 함수 호출이 가능def h(a, b, c):
print(a, b, c)
dargs = {'aa':1, 'bb':2, 'cc':3}
h(*dargs)
dargs = {'a':1, 'b':2, 'c':3}
h(**dargs)
aa bb cc 1 2 3
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"}
myFun(**kwargs)
arg1: Geeks arg2: for arg3: Geeks arg1: Geeks arg2: for arg3: Geeks
def function(**arg):
for i in arg:
print (i, arg[i])
function(a=1, b=2, c=3, d=4)
a 1 b 2 c 3 d 4