美文网首页
python函数

python函数

作者: MagicalGuy | 来源:发表于2018-10-09 00:16 被阅读0次

encoding:utf-8

定义函数的关键字 : def

def fun():
print '我是函数'

带形参的函数

def max(n1 , n2):
'''
求两数中的最大值
:param n1: 第一个数
:param n2: 第2个数
:return: 返回最大值
'''
# 判断变量是否是某种类型
# 1. 是用is关系运算符
if n1 is not int :
return None
# 2. 也可以使用isinstance
if not isinstance(n2,int):
return None
# python中的三目运算符,相当于: n1>n2 ? n1 : n2
return n1 if n1 > n2 else n2

函数中的返回值

def fun3():
# 可以返回多个返回值,将多个返回值打包成元组
return 1,2,3,4

fun()
print max(1,1)
ret = fun3()
print type(ret)

对函数返回的元组返回值进行解包

n1, n2 , n3 , n4 = ret

print globals()

def fun4():
global g_nNum
g_nNum = 10000
print 'g_nNum = ', g_nNum
print('globals:')
for key,value in globals().items():
print(key,":",value)
print('locals:')
for key, value in locals().items():
print(key, ":", value)

print('globals:')
for key,value in globals().items():
print(key,":",value)
print '-'*40
fun4()

关键字参数 : 可以直接将实参传给指定的形参.

def connect1(ipAddress,username,passwd,port=80):
print ipAddress,port,username,passwd
connect1(passwd='123456',
ipAddress='192.168.1.1',
username='hello',
port=3306)

可变长参数

def conect(args,*kwargs):
print args,kwargs
conect('192.168.1.1',
port = 3306,
db = 'userdatabase')
tuple1 = '192.168.1.1',3306,12345678

在参数中对元组实参解包再传递: *tuple1

conect(*tuple1,
port=3306,
db='userdatabase' )

===================

encoding:utf-8

import random

生成一个随机数

print(random.random())
print(random.randint(0,500))
l = [1,2,3,4,5,6,7,8,9]
random.shuffle(l)
print(l)

相关文章

  • Python - 2017/01/28-函数

    调用python内置函数 函数名(参数) 即可调用python内置函数 help(函数名) 返回python对于函...

  • Python函数式介绍一 - 高阶函数

    Python函数式介绍一 - 高阶函数Python函数式介绍二 - 链式调用 最近为了给朋友推广Python函数式...

  • Python高阶函数学习笔记

    python中的高阶函数是指能够接收函数作为参数的函数 python中map()函数map()是 Python 内...

  • Python学习笔记1

    Python注释 Python变量 Python运算符 Python输入输出 输入函数 输出函数(3.x) ...

  • Python:内置函数

    python的内置函数,匿名函数 内置函数 内置函数就是python给你提供的,拿来直接用的函数,比如print,...

  • 二级Python----Python的内置函数及标准库(DAY

    Python的内置函数 嵌入到主调函数中的函数称为内置函数,又称内嵌函数。 python的内置函数(68个) Py...

  • python3 range() 函数和 xrange() 函数

    python3 range 函数 python3 取消了 xrange() 函数,并且和 range() 函数合并...

  • 7、函数

    1、Python之什么是函数 2、Python之调用函数 Python内置了很多有用的函数,我们可以直接调用。 要...

  • Python入门

    Python3教程 安装Python 第一个Python程序 Python基础 函数 高级特性 函数式编程 模块 ...

  • Python函数详解

    函数是Python里组织代码的最小单元,Python函数包含以下几个部分: 定义函数 调用函数 参数 函数的返回值...

网友评论

      本文标题:python函数

      本文链接:https://www.haomeiwen.com/subject/edulaftx.html