欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python学习笔记(八)

程序员文章站 2022-07-09 23:27:58
...

1.函数就是程序中可重复使用的程序段
用关键字“def”来定义,给一段程序起一个名字,用这个名字来执行一段程序,反复使用

# coding:utf-8
def say_hi():
    print("hi!")
say_hi()
#参数Function
def print_sum_two(a,b):
    c = a + b
    print(c)
print_sum_two(3, 6)
#传入字符串
def hello_some(str):
    print("Hello "+ str + "!")
hello_some("China")
#有返回值的function
def repeat_str(str,times):
    repeated_strs = str * times
    return repeated_strs
repeated_string = repeat_str("Happy Birthday", 4)
print(repeated_string)
#全局变量与局部变量
x = 60

def fao(x):
    print("x is " + str(x))
    x = 3
    print("change local x to " + str(x))
fao(x)
print("x is still " + str(x))
#global 用法
y = 60

def foo():
    global y
    print("y is " + str(y))
    y = 3
    print("change local y to " + str(y))
foo()
print("x is " + str(y))

2.默认参数、关键字参数、VarArgs参数

#默认参数
def repeat_str1(str,times=1):
    repeated_strs = str * times
    return repeated_strs
repeated_string = repeat_str1("Happy Birthday")
print(repeated_string)
#关键字参数
#f(a,b =2)#合法
#f(a =2 ,b)#不合法

#关键字参数
def func(a,b =4,c =8):
    print("a is",a,"b is",b,"c is",c)
func(13, 17)
func(125,c=26)
func(c=28,a=5)
#VarsArgs参数
def print_paras(fpara,*nums,**word):
    print("fpara:"+str(fpara))
    print("nums"+ str(nums))
    print("words"+ str(word))
print_paras("Hello",1,3,5,7,word = "python", another_word = "java")