[๐ŸงจํŒŒ์ด์ฌ ๊ธฐ์ดˆ3] ํ•จ์ˆ˜, ์ž…์ถœ๋ ฅ, ํŒŒ์ผ ์ฝ๊ธฐ ์“ฐ๊ธฐ

์•ˆ์ง€์ˆ˜ยท2023๋…„ 1์›” 30์ผ
0

ํ•จ์ˆ˜

๐Ÿ‘‘ ์ž…๋ ฅ๊ฐ’ O, ๊ฒฐ๊ด๊ฐ’ O

def sum(a,b):
	result = a + b
    return result

๐Ÿ‘‘ ์ž…๋ ฅ๊ฐ’ X, ๊ฒฐ๊ด๊ฐ’ O

def say():
	return 'Hi'
  • ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๊ฐ’์€ ์–ธ์ œ๋‚˜ ํ•˜๋‚˜์ด๋‹ค.
    return a+b, a*b -> ํŠœํ”Œ ํ˜•ํƒœ๋กœ (7, 12) ์ด๋ ‡๊ฒŒ ๋ฐ˜ํ™˜๋จ

๐Ÿ‘‘ ์ž…๋ ฅ๊ฐ’ O, ๊ฒฐ๊ด๊ฐ’ X

def sum(a,b):
print("%d, %d์˜ ํ•ฉ์€ %d์ž…๋‹ˆ๋‹ค." %(a, b, +b))
  • ๋งค๊ฐœ ๋ณ€์ˆ˜์— ์ดˆ๊นƒ๊ฐ’์„ ๋ฏธ๋ฆฌ ์„ค์ •ํ•˜๊ธฐ(๊ทธ๋Ÿฌ๋ฉด ํ•จ์ˆ˜ ํ˜ธ์ถœ ์‹œ ์•ˆ ์ ์–ด๋„ ๋จ. but!!! ์ดˆ๊ธฐํ™”๋œ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ’์€ ๊ฐ€์žฅ ๋’ค์—!)

๐Ÿ‘‘ ์ž…๋ ฅ๊ฐ’ X, ๊ฒฐ๊ด๊ฐ’ X

def say():
	print('Hi')

๐Ÿ‘‘ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ž…๋ ฅ๊ฐ’

def sum_many(*args):
	sum = 0
    for i in args:
    	sum = sum+i
    return sum
  • ๊ผญ args ์•„๋‹ˆ์–ด๋„, for์— ์žˆ๋Š” ๊ฒƒ๊ณผ ๋งž์ถ”๋ฉด ๋จ!

๐Ÿ‘‘ ํ‚ค์›Œ๋“œ ํŒŒ๋ผ๋ฏธํ„ฐ

def fun(**kw)
	for k in kw.keys():
    if(k=="name"):
    	print("๋‹น์‹ ์˜ ์ด๋ฆ„์€ :"+k)

๐Ÿ‘‘ ํ•จ์ˆ˜ ์•ˆ์—์„œ ํ•จ์ˆ˜ ๋ฐ–์˜ ๋ณ€์ˆ˜ ๋ณ€๊ฒฝํ•˜๊ธฐ

a = 1
def vartest():
	global a
	a = a+1
>> 2
  • global ์•ˆ์“ฐ๋ฉด, ๊ฒฐ๊ณผ ๊ทธ๋ƒฅ 1์ž„

๐Ÿ‘‘ lamda

add = lamda a, b: a+b
result = add(3,4)
>> 7

์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ ํ•จ์ˆ˜(input, print)

๐Ÿ‘‘ input

number = input("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค: ")
>> ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค: 3  #์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ
print(number)
>> 3

๐Ÿ‘‘ print

  • ','๋Š” ๋„์–ด์“ฐ๊ธฐ ํ•˜์—ฌ ์ถœ๋ ฅํ•˜๊ฒŒ ํ•จ(์—†์œผ๋ฉด ๋ถ™์—ฌ์„œ ์ถœ๋ ฅ)
print("life", "is", "too")
>> life is too

ํŒŒ์ผ ์ฝ๊ธฐ ์“ฐ๊ธฐ

๐Ÿ‘‘ ํŒŒ์ผ ์ƒ์„ฑํ•˜๊ธฐ

f = open("์ƒˆํŒŒ์ผ.txt", 'w')
f.close
  • ํŒŒ์ผ ์—ด๊ธฐ ๋ชจ๋“œ
  1. r: ์“ฐ๊ธฐ๋ชจ๋“œ
  2. w: ์ฝ๊ธฐ๋ชจ๋“œ
  3. a: ์ถ”๊ฐ€๋ชจ๋“œ

๐ŸŽˆ ํŒŒ์ผ ์“ฐ๊ธฐ๋ชจ๋“œ: write() ํ•จ์ˆ˜

  • ํŒŒ์ผ์— ๋‚ด์šฉ ์žˆ์—ˆ์–ด๋„, ๋ชจ๋‘ ์‚ญ์ œ ํ›„ ๋‹ค์‹œ ์”€
f = open("C:Python/์ƒˆํŒŒ์ผ.txt", 'w', encoding = "UTF-8")
for i in range(1,11):
	data = "%d๋ฒˆ์งธ ์ค„์ž…๋‹ˆ๋‹ค.\n" %i
    f.write(data)
f.close()
  • encoding = "UTF-8": ํ•œ๊ธ€ ๊นจ์ง€๋Š” ๊ฒƒ ๋ฐฉ์ง€

๐ŸŽˆ ํŒŒ์ผ ์ฝ๊ธฐ๋ชจ๋“œ
1. readline() ํ•จ์ˆ˜: ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ

f = open("C:Python/์ƒˆํŒŒ์ผ.txt", 'w', encoding = "UTF-8")
line = f.readline()
print(line)
f.close()
  1. readlines() ํ•จ์ˆ˜: ์ „์ฒด ๋ฆฌ์ŠคํŠธ๋กœ ์ฝ์–ด์˜ค๊ธฐ
f = open("C:Python/์ƒˆํŒŒ์ผ.txt", 'w', encoding = "UTF-8")
lines = f.readlines()
for line in lines:
	print(line)
f.close()
  1. read() ํ•จ์ˆ˜: ์ „์ฒด ์ฝ์Œ

๐ŸŽˆ ํŒŒ์ผ ์ถ”๊ฐ€๋ชจ๋“œ

  • ์›๋ž˜ ํŒŒ์ผ ๋‚ด์šฉ์— ๋ง๋ถ™์ž„

๐Ÿ‘‘ with๋ฌธ๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๊ธฐ

with open("foo.txt", 'w') as f:
f.write("Life is too short")
profile
์ง€์ˆ˜์˜ ์ทจ์ค€, ๊ฐœ๋ฐœ์ผ๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€