优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python基础-函数(python基础教程函数)

nanyue 2024-08-09 07:02:55 技术文章 6 ℃

函数

  • 函数是代码的一种组织形式
  • 函数应该能完成一项特定的工作, 而且一般一个函数值完成一项工作
  • 有些语言, 分函数和过程两个概念, 通俗解释是, 有返回结果的叫函数, 无返回结果的叫过程, Python不加以区分
  • 函数的使用
  • 函数使用需要先定义
  • 使用函数,俗称调用
# 定义一个函数
# 只是定义的话不会执行
# 1. def关键字, 后跟一个空格
# 2. 函数名, 自己定义,起名需要遵循变量命名, 大驼峰命名只给类用
# 3. 后面括号和冒号不能省, 括号内可以有参数
# 4. 函数内所有代码缩进
def func():
 print('我是一个函数')
print("函数结束了")
我是一个函数
函数结束了
# 函数的调用
func()
我是一个函数
  • 参数
  • str
  • list, tupe, set, map

函数的参数和返回值

  • 参数: 负责给函数传递一些必要的数据或者信息
  • 形参(形式参数):在函数定义的时候用到的参数,没有具体值,只是一个占位符
  • 实参(实际参数):在调用函数的时候输入的值
  • 返回值:调用函数的时候的一个执行结果
  • 使用return返回结果
  • 如果没有值需要返回,推荐使用return None表示函数结束
  • 函数一旦执行return,则函数立即结束
  • 如果函数没有return关键字,则函数默认返回None
# 形参和实参案例
# 参数person只是一个符号
# 调用的时候用另一个
def hello(person):
 print("{0},你好吗?".format(person))
 print("{},你在哪?".format(person))
 return None
hello("小明")
小明,你好吗?
小明,你在哪?
# help 帮助函数
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.
help(print()) # 等价于help(None)
Help on NoneType object:
class NoneType(object)
 | Methods defined here:
 | 
 | __bool__(self, /)
 | self != 0
 | 
 | __repr__(self, /)
 | Return repr(self).
 | 
 | ----------------------------------------------------------------------
 | Static methods defined here:
 | 
 | __new__(*args, **kwargs) from builtins.type
 | Create and return a new object. See help(type) for accurate signature.
# 九九乘法表
# version1.0
for o in range(1,10): #控制外循环,从 1 到 9
 for i in range(1,o + 1): #内循环,每次从第一个数字开始,打印到跟行数相同的数量
 print(o*i, end=" ")
 print()
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 
# 函数化九九乘法表
def ninenine():
 for o in range(1,10): #控制外循环,从 1 到 9
 for i in range(1,o + 1): #内循环,每次从第一个数字开始,打印到跟行数相同的数量
 print(o*i, end=" ")
 print()
 return None 
ninenine()
ninenine()
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 
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 
# version2.0
def printLine(line_num):
 '''
 line_num:代表行号
 打印一行九九乘法表
 '''
 for i in range(1,line_num+1):
 print(i*line_num, end=' ')
 print()
 return None
def ninenine():
 for o in range(1,10):
 printLine(o) #实参传递
 return None
ninenine()
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 

参数详解

  • 参数分类
  • 普通参数/未知参数
  • 默认参数
  • 关键字参数
  • 收集参数
# 普通参数案例
def normal_para(one, two, three):
 print(one + two)
 return None
normal_para(1,2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-823d55c9dd2c> in <module>
 4 return None
 5 
----> 6 normal_para(1,2)
TypeError: normal_para() missing 1 required positional argument: 'three'
# 默认参数案例
def default_para(one, two, three=100):
 print(one + two)
 return None
default_para(1,2)
3
# 关键字参数
def keys_para(two, one, three):
 print(one + two)
 print(three)
 return None
keys_para(one=1, two=2, three=3)
3
3

str字符串

  • str
  • 转义字符
  • 格式化
  • 内建函数

字符串

  • 表示文字信息
  • 用单引号, 双引号, 三引号括起来
s = """
我
是
Yuan
shuo
"""
print(s)
我
是
Yuan
shuo

转义字符

  • 用一个特色的方法表示出一系列不方便写出的内容, 比如回车键、换行符、退格键
  • 借助反斜杠字符, 一旦字符串出现反斜杠, 则反斜杠后面一个或几个字符表示已经不是原来的意思了,进行了转移
  • 在字符串中, 一旦出现反斜杠就要加倍小心, 可能有转义字符出现
  • 不同操作系统对换行操作有不同表示
  • Windows:\n
  • Linux:\r\n
# 转义字符案例
# 想表达 Let's Go
# 使用转义字符
s = 'Let\'s Go' # "Let's Go"
print(s)
# 表示斜杠 
# 打印 c:\User\
c = "c:\\User\\"
print(c)
Let's Go
c:\User\

格式化

  • 把字符串按照一定格式进行打印或者填充
  • 格式化的分类:
  • 传统格式化
  • format
# 填充
s = "I Love Yuanshuo"
print(s)
s = "You Love Yuanshuo"
print(s)
s = "She Love Yuanshuo"
print(s)
I Love Yuanshuo
You Love Yuanshuo
She Love Yuanshuo

字符串的传统格式化方法

  • 使用 % 进行格式化
  • %占位符
# %s 表示简单的字符串
s = "%s Love Yuanshuo"
print(s)
print(s%'You')
%s Love Yuanshuo
You Love Yuanshuo

format格式化

  • 使用函数形式进行格式化,代替以前的百分号
# 不用指定位置,按顺序读取
# 方式1 
s = "{} {}!"
print(s.format("Hello", "world"))
# 方式2
s = "{} {}!".format("Hello", "world")
print(s)
# 设置指定位置
s = "{0} {1}!"
print(s.format("Hello", "world"))
s = "{0} {0}!"
print(s.format("Hello", "world"))
'''
s = "{} {}!"
print(s.format("Hello"))
# 报错
'''
# 使用命名参数
s = "我是{name}, 邮箱是{mail}, 球球是{qq}"
print(s.format(name="Yuanshuo", mail="Yuanshuozhangde@gmail.com", qq="325116067"))
Hello world!
Hello world!
Hello world!
Hello Hello!
我是Yuanshuo, 邮箱是Yuanshuozhangde@gmail.com, 球球是325116067
# 通过字典设置参数,需要解包
# 使用命名参数
s = "我是{name}, 邮箱是{mail}, 球球是{qq}"
s_dict = {"name":"Yuanshuo", "mail":"Yuanshuozhangde@gmail.com", "qq":"325116067"}
# **是解包操作
print(s.format(**s_dict))
我是Yuanshuo, 邮箱是Yuanshuozhangde@gmail.com, 球球是325116067
# 对数字的格式化需要用到
s = "Yuanshuo is {:.2f}m, {:.2f}Kg." # 小数点后两位
print(s.format(182.777, 66.777))
Yuanshuo is 182.78m, 66.78Kg.

str内置函数

  • 很多语言字符串使用string表示, 但Python中使用str表示字符串
help(str)
Help on class str in module builtins:
class str(object)
 | str(object='') -> str
 | str(bytes_or_buffer[, encoding[, errors]]) -> str
 | 
 | Create a new string object from the given object. If encoding or
 | errors is specified, then the object must expose a data buffer
 | that will be decoded using the given encoding and error handler.
 | Otherwise, returns the result of object.__str__() (if defined)
 | or repr(object).
 | encoding defaults to sys.getdefaultencoding().
 | errors defaults to 'strict'.
 | 
 | Methods defined here:
 | 
 | __add__(self, value, /)
 | Return self+value.
 | 
 | __contains__(self, key, /)
 | Return key in self.
 | 
 | __eq__(self, value, /)
 | Return self==value.
 | 
 | __format__(self, format_spec, /)
 | Return a formatted version of the string as described by format_spec.
 | 
 | __ge__(self, value, /)
 | Return self>=value.
 | 
 | __getattribute__(self, name, /)
 | Return getattr(self, name).
 | 
 | __getitem__(self, key, /)
 | Return self[key].
 | 
 | __getnewargs__(...)
 | 
 | __gt__(self, value, /)
 | Return self>value.
 | 
 | __hash__(self, /)
 | Return hash(self).
 | 
 | __iter__(self, /)
 | Implement iter(self).
 | 
 | __le__(self, value, /)
 | Return self<=value.
 | 
 | __len__(self, /)
 | Return len(self).
 | 
 | __lt__(self, value, /)
 | Return self<value.
 | 
 | __mod__(self, value, /)
 | Return self%value.
 | 
 | __mul__(self, value, /)
 | Return self*value.
 | 
 | __ne__(self, value, /)
 | Return self!=value.
 | 
 | __repr__(self, /)
 | Return repr(self).
 | 
 | __rmod__(self, value, /)
 | Return value%self.
 | 
 | __rmul__(self, value, /)
 | Return value*self.
 | 
 | __sizeof__(self, /)
 | Return the size of the string in memory, in bytes.
 | 
 | __str__(self, /)
 | Return str(self).
 | 
 | capitalize(self, /)
 | Return a capitalized version of the string.
 | 
 | More specifically, make the first character have upper case and the rest lower
 | case.
 | 
 | casefold(self, /)
 | Return a version of the string suitable for caseless comparisons.
 | 
 | center(self, width, fillchar=' ', /)
 | Return a centered string of length width.
 | 
 | Padding is done using the specified fill character (default is a space).
 | 
 | count(...)
 | S.count(sub[, start[, end]]) -> int
 | 
 | Return the number of non-overlapping occurrences of substring sub in
 | string S[start:end]. Optional arguments start and end are
 | interpreted as in slice notation.
 | 
 | encode(self, /, encoding='utf-8', errors='strict')
 | Encode the string using the codec registered for encoding.
 | 
 | encoding
 | The encoding in which to encode the string.
 | errors
 | The error handling scheme to use for encoding errors.
 | The default is 'strict' meaning that encoding errors raise a
 | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 | 'xmlcharrefreplace' as well as any other name registered with
 | codecs.register_error that can handle UnicodeEncodeErrors.
 | 
 | endswith(...)
 | S.endswith(suffix[, start[, end]]) -> bool
 | 
 | Return True if S ends with the specified suffix, False otherwise.
 | With optional start, test S beginning at that position.
 | With optional end, stop comparing S at that position.
 | suffix can also be a tuple of strings to try.
 | 
 | expandtabs(self, /, tabsize=8)
 | Return a copy where all tab characters are expanded using spaces.
 | 
 | If tabsize is not given, a tab size of 8 characters is assumed.
 | 
 | find(...)
 | S.find(sub[, start[, end]]) -> int
 | 
 | Return the lowest index in S where substring sub is found,
 | such that sub is contained within S[start:end]. Optional
 | arguments start and end are interpreted as in slice notation.
 | 
 | Return -1 on failure.
 | 
 | format(...)
 | S.format(*args, **kwargs) -> str
 | 
 | Return a formatted version of S, using substitutions from args and kwargs.
 | The substitutions are identified by braces ('{' and '}').
 | 
 | format_map(...)
 | S.format_map(mapping) -> str
 | 
 | Return a formatted version of S, using substitutions from mapping.
 | The substitutions are identified by braces ('{' and '}').
 | 
 | index(...)
 | S.index(sub[, start[, end]]) -> int
 | 
 | Return the lowest index in S where substring sub is found, 
 | such that sub is contained within S[start:end]. Optional
 | arguments start and end are interpreted as in slice notation.
 | 
 | Raises ValueError when the substring is not found.
 | 
 | isalnum(self, /)
 | Return True if the string is an alpha-numeric string, False otherwise.
 | 
 | A string is alpha-numeric if all characters in the string are alpha-numeric and
 | there is at least one character in the string.
 | 
 | isalpha(self, /)
 | Return True if the string is an alphabetic string, False otherwise.
 | 
 | A string is alphabetic if all characters in the string are alphabetic and there
 | is at least one character in the string.
 | 
 | isascii(self, /)
 | Return True if all characters in the string are ASCII, False otherwise.
 | 
 | ASCII characters have code points in the range U+0000-U+007F.
 | Empty string is ASCII too.
 | 
 | isdecimal(self, /)
 | Return True if the string is a decimal string, False otherwise.
 | 
 | A string is a decimal string if all characters in the string are decimal and
 | there is at least one character in the string.
 | 
 | isdigit(self, /)
 | Return True if the string is a digit string, False otherwise.
 | 
 | A string is a digit string if all characters in the string are digits and there
 | is at least one character in the string.
 | 
 | isidentifier(self, /)
 | Return True if the string is a valid Python identifier, False otherwise.
 | 
 | Use keyword.iskeyword() to test for reserved identifiers such as "def" and
 | "class".
 | 
 | islower(self, /)
 | Return True if the string is a lowercase string, False otherwise.
 | 
 | A string is lowercase if all cased characters in the string are lowercase and
 | there is at least one cased character in the string.
 | 
 | isnumeric(self, /)
 | Return True if the string is a numeric string, False otherwise.
 | 
 | A string is numeric if all characters in the string are numeric and there is at
 | least one character in the string.
 | 
 | isprintable(self, /)
 | Return True if the string is printable, False otherwise.
 | 
 | A string is printable if all of its characters are considered printable in
 | repr() or if it is empty.
 | 
 | isspace(self, /)
 | Return True if the string is a whitespace string, False otherwise.
 | 
 | A string is whitespace if all characters in the string are whitespace and there
 | is at least one character in the string.
 | 
 | istitle(self, /)
 | Return True if the string is a title-cased string, False otherwise.
 | 
 | In a title-cased string, upper- and title-case characters may only
 | follow uncased characters and lowercase characters only cased ones.
 | 
 | isupper(self, /)
 | Return True if the string is an uppercase string, False otherwise.
 | 
 | A string is uppercase if all cased characters in the string are uppercase and
 | there is at least one cased character in the string.
 | 
 | join(self, iterable, /)
 | Concatenate any number of strings.
 | 
 | The string whose method is called is inserted in between each given string.
 | The result is returned as a new string.
 | 
 | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 | 
 | ljust(self, width, fillchar=' ', /)
 | Return a left-justified string of length width.
 | 
 | Padding is done using the specified fill character (default is a space).
 | 
 | lower(self, /)
 | Return a copy of the string converted to lowercase.
 | 
 | lstrip(self, chars=None, /)
 | Return a copy of the string with leading whitespace removed.
 | 
 | If chars is given and not None, remove characters in chars instead.
 | 
 | partition(self, sep, /)
 | Partition the string into three parts using the given separator.
 | 
 | This will search for the separator in the string. If the separator is found,
 | returns a 3-tuple containing the part before the separator, the separator
 | itself, and the part after it.
 | 
 | If the separator is not found, returns a 3-tuple containing the original string
 | and two empty strings.
 | 
 | replace(self, old, new, count=-1, /)
 | Return a copy with all occurrences of substring old replaced by new.
 | 
 | count
 | Maximum number of occurrences to replace.
 | -1 (the default value) means replace all occurrences.
 | 
 | If the optional argument count is given, only the first count occurrences are
 | replaced.
 | 
 | rfind(...)
 | S.rfind(sub[, start[, end]]) -> int
 | 
 | Return the highest index in S where substring sub is found,
 | such that sub is contained within S[start:end]. Optional
 | arguments start and end are interpreted as in slice notation.
 | 
 | Return -1 on failure.
 | 
 | rindex(...)
 | S.rindex(sub[, start[, end]]) -> int
 | 
 | Return the highest index in S where substring sub is found,
 | such that sub is contained within S[start:end]. Optional
 | arguments start and end are interpreted as in slice notation.
 | 
 | Raises ValueError when the substring is not found.
 | 
 | rjust(self, width, fillchar=' ', /)
 | Return a right-justified string of length width.
 | 
 | Padding is done using the specified fill character (default is a space).
 | 
 | rpartition(self, sep, /)
 | Partition the string into three parts using the given separator.
 | 
 | This will search for the separator in the string, starting at the end. If
 | the separator is found, returns a 3-tuple containing the part before the
 | separator, the separator itself, and the part after it.
 | 
 | If the separator is not found, returns a 3-tuple containing two empty strings
 | and the original string.
 | 
 | rsplit(self, /, sep=None, maxsplit=-1)
 | Return a list of the words in the string, using sep as the delimiter string.
 | 
 | sep
 | The delimiter according which to split the string.
 | None (the default value) means split according to any whitespace,
 | and discard empty strings from the result.
 | maxsplit
 | Maximum number of splits to do.
 | -1 (the default value) means no limit.
 | 
 | Splits are done starting at the end of the string and working to the front.
 | 
 | rstrip(self, chars=None, /)
 | Return a copy of the string with trailing whitespace removed.
 | 
 | If chars is given and not None, remove characters in chars instead.
 | 
 | split(self, /, sep=None, maxsplit=-1)
 | Return a list of the words in the string, using sep as the delimiter string.
 | 
 | sep
 | The delimiter according which to split the string.
 | None (the default value) means split according to any whitespace,
 | and discard empty strings from the result.
 | maxsplit
 | Maximum number of splits to do.
 | -1 (the default value) means no limit.
 | 
 | splitlines(self, /, keepends=False)
 | Return a list of the lines in the string, breaking at line boundaries.
 | 
 | Line breaks are not included in the resulting list unless keepends is given and
 | true.
 | 
 | startswith(...)
 | S.startswith(prefix[, start[, end]]) -> bool
 | 
 | Return True if S starts with the specified prefix, False otherwise.
 | With optional start, test S beginning at that position.
 | With optional end, stop comparing S at that position.
 | prefix can also be a tuple of strings to try.
 | 
 | strip(self, chars=None, /)
 | Return a copy of the string with leading and trailing whitespace remove.
 | 
 | If chars is given and not None, remove characters in chars instead.
 | 
 | swapcase(self, /)
 | Convert uppercase characters to lowercase and lowercase characters to uppercase.
 | 
 | title(self, /)
 | Return a version of the string where each word is titlecased.
 | 
 | More specifically, words start with uppercased characters and all remaining
 | cased characters have lower case.
 | 
 | translate(self, table, /)
 | Replace each character in the string using the given translation table.
 | 
 | table
 | Translation table, which must be a mapping of Unicode ordinals to
 | Unicode ordinals, strings, or None.
 | 
 | The table must implement lookup/indexing via __getitem__, for instance a
 | dictionary or list. If this operation raises LookupError, the character is
 | left untouched. Characters mapped to None are deleted.
 | 
 | upper(self, /)
 | Return a copy of the string converted to uppercase.
 | 
 | zfill(self, width, /)
 | Pad a numeric string with zeros on the left, to fill a field of the given width.
 | 
 | The string is never truncated.
 | 
 | ----------------------------------------------------------------------
 | Static methods defined here:
 | 
 | __new__(*args, **kwargs) from builtins.type
 | Create and return a new object. See help(type) for accurate signature.
 | 
 | maketrans(x, y=None, z=None, /)
 | Return a translation table usable for str.translate().
 | 
 | If there is only one argument, it must be a dictionary mapping Unicode
 | ordinals (integers) or characters to Unicode ordinals, strings or None.
 | Character keys will be then converted to ordinals.
 | If there are two arguments, they must be strings of equal length, and
 | in the resulting dictionary, each character in x will be mapped to the
 | character at the same position in y. If there is a third argument, it
 | must be a string, whose characters will be mapped to None in the result.

递归函数

  • 递归:函数间接或者直接调用自己
  • 递归分两个过程
  • 往下调用, 分解的过程
  • 往上回溯, 综合的过程
  • 递归需要注意
  • 一定要有结束的条件
  • 以资源换取编写速度
def funca(n):
 print("I am Yuanshuo")
 return None
def funcb(n):
 funca(100)
 print("I am Cheung")
 return None
funcb(100)
I am Yuanshuo
I am Cheung
# 阶乘
def func(n):
 print(n)
 # 递归一定要有结束条件
 if n==1:
 return 1
 return n*func(n-1)
rst = func(5)
print("f(5) = " , rst)
5
4
3
2
1
f(5) = 120
# 斐波那契数列
# 1, 1, 2, 3, 5, 8, 13, ...
# f(n) = f(n-1)+f(n-2), n>=3
# f(n) = 1, n={1, 2}
def fib(n):
 if n==1 or n==2:
 return 1
 return fib(n-1) + fib(n-2)
rst = fib(5)
print("fib(5) = ", rst)
fib(5) = 5
# 汉诺塔
# 三个棍子a, b, c; n个盘子
a = 'A'
b = 'B'
c = 'C'
def hano(a, b, c, n):
 if n == 1:
 print("{}-->{}".format(a, c))
 return None
 if n == 2:
 print("{}-->{}".format(a, b))
 print("{}-->{}".format(a, c))
 print("{}-->{}".format(b, c))
 return None
 hano(a, c, b, n-1)
 print("{}-->{}".format(a, c))
 hano(b, a, c, n-1)
# 只有一个盘子
hano(a, b, c, 1)
A-->C
# 只有两个盘子
hano(a, b, c, 2)
A-->B
A-->C
B-->C
# 有三个盘子
hano(a, b, c, 3)
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
最近发表
标签列表