###Pythonで関数を使ってみる
######引数のデフォルトを指定する
def hello(name="A", age=10):
result = "Hello I'm " + name + ", I'm " + str(age)
print(result)
>>> hello()
Hello I'm A, I'm 10
>>> hello("Bob", 20)
Hello I'm Bob, I'm 20
######文字列の引数を逆にする
>>> def reverse(s):
cnt = len(s)
result=""
if cnt < 1:
result = s
else:
i = cnt-1
while i > -1:
result = result + s[i]
i = i - 1
print(result)
>>> reverse("abcde")
edcba
>>> reverse("a")
a
#####3で割り切れるか、5で割り切れるか、両方で割り切れるか
>>> def fb(n):
mod3 = n % 3
mod5 = n % 5
result = ""
if mod3 == 0:
result += "Fizz"
if mod5 == 0:
result += "Buzz"
return result
>>> i = 1
>>> while i <= 20:
print(i, fb(i))
i = i + 1
1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
11
12 Fizz
13
14
15 FizzBuzz
16
17
18 Fizz
19
20 Buzz