Python函数中的变量和函数返回值
1.函數(shù)的變量
局部變量和全局變量:
Python中的任何變量都有特定的作用域
在函數(shù)中定義的變量一般只能在該函數(shù)內(nèi)部使用,這些只能在程序的特定部分使用的變量我們稱之為局部變量
在一個(gè)文件頂部定義的變量可以供文件中的任何函數(shù)調(diào)用,這些可以為整個(gè)程序所使用的變量稱為全局變量。
????def fun():
?????? ?x=100
?????? ?print x
????fun()
????x = 100
????
????def fun():
?????? ?global x?? //聲明
?????? ?x +=1
?????? ?print x
????fun()
????print x
外部變量被改:
????x = 100
????def fun():
?????? ?global x ? //聲明
?????? ?x +=1
?????? ?print x
????fun()
????print x
內(nèi)部變量外部也可用:
????x = 100
????def fun():
?????? ?global x
?????? ?x +=1
???????global y
?????? ?y = 1
?????? ?print x
????fun()
????print x
????print y
????x = 100
????def fun():
?????? ?x = 1
?????? ?y = 1
?????? ?print locals()
????fun()
????print locals()
????{'y': 1, 'x': 1}
????統(tǒng)計(jì)程序中的變量,返回的是個(gè)字典
????{'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:/PycharmProjects/untitled/python/2018.01.03/bianliang.py', '__package__': None, 'x': 100, 'fun': <function fun at 0x02716830>, '__name__': '__main__', '__doc__': None}
????
2. 函數(shù)的返回值
函數(shù)返回值:
函數(shù)被調(diào)用后會(huì)返回一個(gè)指定的值
函數(shù)調(diào)用后默認(rèn)返回None
return返回值
返回值可騍任意類型
return執(zhí)行后,函數(shù)終止
return與print區(qū)別
????def fun():
?????? ?print 'hello world'
?????? ???return 'ok'
?????? ?print 123
????print fun()
????hello world
????123
????None
????#/usr/bin/env python
????# -*- coding:utf-8 -*-
????# @time ? :2018/1/2 21:06
????# @Author :FengXiaoqing
????# @file ? :printPID.py
????import sys
????import os
????def isNum(s):
?????? ?for i in s:
?????? ? ? ?if i not ?in '0123456789':
???? ? ?return False
?????? ?return True
????for i in os.listdir("/proc"):
?????? ?if isNum(i):
???? print i
????
????import sys
????import os
????def isNum(s):
?????? ?if?s.isdigit():
?????? ? ? ?return True
????????return False
????for i in os.listdir("/proc"):
?????? ?if isNum(i):
?????? ? ? print i
或:
????#/usr/bin/env python
????# -*- coding:utf-8 -*-
????# @time ? :2018/1/2 21:06
????# @Author :FengXiaoqing
????# @file ? :printPID.py
????import sys
????import os
????def isNum(s):
?????? ?if s.isdigit():
?????? ? ? ?return True
????????else:
?????? ? ? ?return False
????for i in os.listdir("/proc"):
?????? ?if isNum(i):
?????? ? ? print i
習(xí)題
1. 設(shè)計(jì)一個(gè)程序,從終端接收10個(gè)數(shù)字,并使用自己編寫的排序函數(shù),對(duì)10個(gè)數(shù)字排序后輸出.
2. 設(shè)計(jì)一個(gè)函數(shù),接收一個(gè)英文單詞,從文件中查詢?cè)搯卧~的漢語(yǔ)意思并返回.
? ??
本文轉(zhuǎn)自 楓葉云 ?51CTO博客,原文鏈接:http://blog.51cto.com/fengyunshan911/2057207
總結(jié)
以上是生活随笔為你收集整理的Python函数中的变量和函数返回值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SQL Server 2005无法输入中
- 下一篇: python综合练习1-- 用户登录