(Python 2-2๊ฐ•) Function and Console I/O

210802

ํ•จ์ˆ˜

์–ด๋–ค ์ผ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์ฝ”๋„์˜ ๋ฉ์–ด๋ฆฌ

  • ๋ฐ˜๋ณต์ ์ธ ์ˆ˜ํ–‰์„ ํ•  ๋•Œ 1ํšŒ๋งŒ ์ž‘์„ฑํ•˜๊ณ  ๋ฐ˜๋ณต ํ˜ธ์ธจ ํ•  ์ˆ˜ ์žˆ๋‹ค

  • ์ฝ”๋“œ๋ฅผ ๋…ผ๋ฆฌ์ ์ธ ๋‹จ์œ„๋กœ ๋ถ„๋ฆฌํ•œ๋‹ค

  • ์บก์Аํ™” : ์ธํ„ฐํŽ˜์ด์Šค๋งŒ ์•Œ๋ฉด ํƒ€์ธ์˜ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

๋ฌธ๋ฒ•

def ํ•จ์ˆ˜์ด๋ฆ„ (parameter1, ...):
    ์ˆ˜ํ–‰๋ฌธ #1
    ์ˆ˜ํ–‰๋ฌธ #2
    return ๋ฐ˜ํ™˜๊ฐ’

์˜ˆ์‹œ

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

Parameter vs Argument

  • Parameter : ํ•จ์ˆ˜์˜ ์ž…๋ ฅ ๊ฐ’ ์ธํ„ฐํŽ˜์ด์Šค

    • def f(x): ์—์„œ์˜ x

  • Argument : ์‹ค์ œ Parameter์— ๋Œ€์ž…๋œ ๊ฐ’

    • f(2) ์—์„œ์˜ 2

์ฝ˜์†”์ฐฝ ์ž…์ถœ๋ ฅ

  • Input() : ์ฝ˜์†”์ฐฝ์—์„œ ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ ๋ฐ›๋Š” ํ•จ์ˆ˜

  • print() : ์ฝ˜์†”์ฐฝ์—์„œ ์ถœ๋ ฅ์„ ๋‹ด๋‹น

๊ธฐ๋ณธ์ ์ธ ์ถœ๋ ฅ ์™ธ์— 3๊ฐ€์ง€ ์ถœ๋ ฅ ํ˜•์‹์„ ์ง€์ • ๊ฐ€๋Šฅํ•˜๋‹ค

print(1,2,3)

print("a" + " " + "b" + " " + "c")

print("%d %d %d" % (1,2,3))

print("{} {} {}".format("a","b","c"))

print(f"value is {value})

old-school formatting

  • ์ผ๋ฐ˜์ ์œผ๋กœ %-format๊ณผ str.format() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•จ

print('%s %s' % ('one', 'two'))

print('{} {}'.format('one', 'two'))

print('%d %d' % (1, 2))

print('{} {}'.format(1, 2))

% - format

print("I eat %d apples." % 3)

print("I eat %s apples." % "five")

number = 3; day="three"
print("I ate %d apples. I was sick for %s days." % (number, day))

print("Product: %s, Price per unit: %f." % ("Apple", 5.243))
  • %s ๋ฌธ์ž์—ด (String)

  • %c ๋ฌธ์ž 1๊ฐœ(character)

  • %d ์ •์ˆ˜ (Integer)

  • %f ๋ถ€๋™์†Œ์ˆ˜ (floating-point)

  • %o 8์ง„์ˆ˜

  • %x 16์ง„์ˆ˜

  • %% Literal % (๋ฌธ์ž % ์ž์ฒด)

str.format

age = 36; name='Sungchul Choi'
print("Iโ€™m {0} years old.".format(age))
print("My name is {0} and {1} years old.".format(name,age))
print("Product: {0}, Price per unit: {1:.3f}.".format("Apple", 5.243))

naming

print("Product: %(name)10s, Price per unit: %(price)10.5f." %
{"name":"Apple", "price":5.243})

print("Product: {name:>10s}, Price per unit:
{price:10.5f}.".format(name="Apple", price=5.243))

f-string

name = "Sungchul"
age = 39
print(f"Hello, {name}. You are {age}.")
print(f'{name:20}')
print(f'{name:>20}')
print(f'{name:*<20}')
print(f'{name:*>20}')
print(f'{name:*^20}')

Hello, Sungchul. You are 39.
Sungchul
Sungchul
Sungchul************
************Sungchul
******Sungchul******

Last updated

Was this helpful?