首页 技术 正文
技术 2022年11月12日
0 收藏 458 点赞 3,142 浏览 1633 个字

1、函数定义

你可以定义一个由自己想要功能的函数,以下是简单的规则:

  函数代码块以def关键词开头,后接函数标识符名称和圆括号()。

  任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。

  函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。

  函数内容以冒号起始,并且缩进。

  Return[expression]结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

函数:程序中可重复使用的程序段。给一段程程序起一个名字,用这个名字来执行一段程序,反复使用(调用函数),用关键字 ‘def’ 来定义,identifier(参数)

# -*- coding: utf-8 -*-# 没有参数和返回的函数
def say_hi():
print(" hi!")
say_hi()
say_hi()# 有参数,无返回值
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")
hello_some("Python")# 有参数,有返回值
def repeat_str(str, times):
repeated_strs = str * times
return repeated_strs
repeated_strings = repeat_str("Happy Birthday!", 4)
print(repeated_strings)# 全局变量与局部 变量
x = 60
def foo(x):
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo(x)
print('x is still', str(x))x = 60
def foo():
global x
print("x is: " + str(x))
x = 3
print("change local x to " + str(x))
foo()
print('value of x is', str(x))

运行结果:

python基础3–函数

2、关于函数的参数,有以下三个用:默认参数,关键字参数,VarArgs参数

# -*- coding: utf-8 -*-# 默认参数: 如果没有传入参数,使用默认值
def repeat_str(s, times=1):
repeated_strs = s * times
return repeated_strsrepeated_strings = repeat_str("Happy Birthday!")
print(repeated_strings)repeated_strings_2 = repeat_str("Happy Birthday!", 4)
print(repeated_strings_2)# 不能在有默认参数后面跟随没有默认参数
# f(a, b =2)合法
# f(a = 2, b)非法# 关键字参数: 调用函数时,选择性的传入部分参数
def func(a, b=4, c=8):
print('a is', a, 'and b is', b, 'and c is', c)func(13, 17)
func(125, c=24)
func(c=40, a=80)# VarArgs参数
#当用*在前加入一个参数名时,python将默认参数传入的是一个list或tuple,即多个参数
#当用**在前加入一个参数名时,python将默认参数传入的是一个dict,即多个有关键字指明的参数
def print_paras(fpara1, fpara2, *nums, **words):
print("fpara1: " + str(fpara1))
print("fpara2: " + str(fpara2))
print("nums: " + str(nums))
print("words: " + str(words))print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")

运行结果:

python基础3–函数

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292