Python学习笔记函数之返回值和return语句

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  我们调用len()函数时,向它传入“hello”这样的参数,函数调用后返回的值是整数5。此函数时求传入字符串的长度。

一般来说,函数调用求值的结果,称为函数的“返回值”。

  用def语句创建函数时,可以用return语句指定应该返回什么值。return语句包含以下部分:

  (1)return关键字

  (2)函数应该的值或表达式

  如果在return语句中使用了表达式,返回值就是该表达式求值的结果。

例如,使用上一篇将函数定义语句时的代码为例。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  1、传入字符串,代码示例:  

#
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
#import random
def hello(name):#使用def关键字,定义一个名为hello的函数
    return 'hello' + name#返回hello加传入的名字
print(hello("Li Rong Yang"))#函数调用并打印

  

  运行结果:

  1、传入整数,代码示例:

#
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
#import random
def Square(length,width):#使用def关键字,定义一个名为hello的函数
    square = length * width#求length和width的平方
    return 'Square is: '+str(square)#返回'Square is: '加length和width的平方

print(Square(2,5))#函数调用

  

  运行结果:

猜你喜欢

转载自www.cnblogs.com/lirongyang/p/9526743.html
今日推荐