---
# System prepended metadata

title: 第十一堂課 2022/05/16

---

# 第十一堂課 2022/05/16
姓名：陳柔云（110251040）
## Python Functions
- A function is a block of code which only runs when it is called.
- You can pass data, known as parameters, into a function.
### Creating a function
In Python a function is defined using the def keyword:
    例:
```
def my_function():
  print("Hello from a function")
```
### Calling a function
To call a function, use the function name followed by parenthesis:
    例:
```
def my_function():
  print("Hello from a function")
  
my_function()
Answer : Hello from a function
```

### Arguments (often shortened to args in Python documentations)
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
例:
```
def my_function(fname):
  print(fname+" Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Answer :
Emil Refsnes
Tobias Refsnes
Linus Refsnes
```
```
def myFun(x):
  print(x+"您好")

myFun('小明')
Answer : 小明您好
```
```
def myFun(x,y):
  print(x+"您好: "+y)

myFun('小明','早餐吃了沒？')
Answer : 小明您好: 早餐吃了沒？
```
```
def myFun(x,y,z):
  print(x+'您好： '+y +' '+z)
def myCal(x,y):
  print(x+y)

myFun('小明','早餐吃了沒？','記得帶外套')
myCal(3,5)
myCal(y=5,x=3)
Answer :
小明您好： 早餐吃了沒？ 記得帶外套
8
8

myFun('早餐吃了沒？','小明','記得帶外套')
myCal(3,5)
myCal(y=5,x=3)
Answer ：
早餐吃了沒？您好： 小明 記得帶外套
8
8
```
## 計算1,2,...,n的總和
```
n=10
s=0
for i in range(1,n+1):
  s=s+i
print(s)
Answer ： 55
```
```
n=200
s=0
for i in range(1,n+1):
  s=s+i
print(s)
Answer : 20100
```
```
def Sum1toN(n):
  s=0
  #n=10
  for i in range(1,n+1):
    s=s+i
  return s
  
Sum1toN(10)
Answer : 55

Sum1toN(1000)
Answer : 500500

x=Sum1toN(10)
print(x)
Answer : 55
```
## 計算m,m+1,...,n的總和
```
def Sum1toN(m,n):
  s=0
  #n=10
  for i in range(1,n+1):
    s=s+i
  return s
  
x=Sum1toN(5,10)
print(x)
Answer : 55
```