学习笔记第八天(Python篇)

参数这块有一点难度啊emmmmmm

查找函数文档

help(print)
Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

In [53]:

for col in range(1, row+1):
#print函数默认任务打印完毕后换行
print( row * col, end="")
print("…")
1

99乘法表

2

version 1.0

3

4
for row in range(1,10):
5
#打印一行
6
for col in range(1, row+1):
7
#print函数默认任务打印完毕后换行
8
print( row * col, end="")
9
print("…")
1…
24…
369…
481216…
510152025…
61218243036…
7142128354249…
816243240485664…
91827364554637281…
In [29]:

1

99乘法表

2

定义一个函数打印99乘法表

3
def printline(row):
4
for col in range(1, row+1):
5
#print函数默认任务打印完毕后换行
6
print( row * col, end=" “)
7
print(”")
8

99乘法表

9

version 2.0

10
for row in range(1,10):
11
printline(row)
12

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
参数详解
{参考资料}(https://www.cnblogs.con/bingabcd/p/6671368.html)
python参考资料:headfirst python
参数分类

普通参数
默认参数
关键字参数
收集参数
普通参数

参见上例
定义时候直接定义变量名字
调用的时候直接把变量或者值放入指定位置
def 函数名 (参数1, 参数2, …):
函数体

    # 调用
    函数名(value1, value2, .......)

    #调用的时候,具体值参考的是位置,按位置赋值

默认参数
形参带有默认值
调用的时候,若没有相对应的形参赋值,则使用默认值
def func_name(p1=v1,p2=v2…):
func_blcok

        #调用1
        func_blcok()

        #调用2
        value1 = 100
        value2 = 200
        func_name(value1,value2)

In [42]:

1

默认参数示例

2

报名函数,需要晓得学生性别

3

学习Python的基本上都是男生,所以,报名的时候若没有特别指定,我们任务是男生

4

5
def reg(name, age, gender=“male”):
6
if gender == “male”:
7
print("{0} is {1}, and he is a good student".format(name, age))
8
else:
9
print("{0} is {1}, and she is a good student".format(name, age))
10

In [47]:

xinyu
1

函数的调用案例1

2

3
reg(“mingyue”, 21)
4
reg(“xinyu”, 23, “female”)
mingyue is 21, and he is a good student
xinyu is 23, and she is a good student
关键字参数
语法

def func(p1=v1, p2=v2…):
funnc_body

调用参数:
func(p1=value1, p2=value2…)
这种方法比较麻烦,但是也有他的好处:

不容易混浠,一般实参和形参只是按照位置一一对应即可,容易出错
使用关键字参数,可以不考虑参数位置
In [51]:

1
#关键字参数案例
2

3
def stu(name, age, addr):
4
print(“I am a studen”)
5
print(“我叫{0},我今年{1}岁了,我住{2}”.format(name, age, addr))
6

7
n = “xinyu”
8
a = 20
9
addr = “我家”
10

11
stu(n, a, addr)
12

13
#普通参数,只按照位置传递,容易出错
14

15

16
def stu_key(name=“NO name”, age=0, addr=“NO addr”):
17
print(“I am a studen”)
18
print(“我叫{0},我今年{1}岁了,我住{2}”.format(name, age, addr))
19

20
n = “xinyu”
21
a = 20
22
addr = “我家”
23

24
stu_key(age=a, name=n, addr=addr)
25

I am a studen
我叫xinyu,我今年20岁了,我住我家
I am a studen
我叫xinyu,我今年20岁了,我住我家

猜你喜欢

转载自blog.csdn.net/qq_44697637/article/details/88919439