Python函数中的变量和函数返回值
1.函數的變量
局部變量和全局變量:
Python中的任何變量都有特定的作用域
在函數中定義的變量一般只能在該函數內部使用,這些只能在程序的特定部分使用的變量我們稱之為局部變量
在一個文件頂部定義的變量可以供文件中的任何函數調用,這些可以為整個程序所使用的變量稱為全局變量。
????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
內部變量外部也可用:
????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}
????統計程序中的變量,返回的是個字典
????{'__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. 函數的返回值
函數返回值:
函數被調用后會返回一個指定的值
函數調用后默認返回None
return返回值
返回值可騍任意類型
return執行后,函數終止
return與print區別
????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
習題
1. 設計一個程序,從終端接收10個數字,并使用自己編寫的排序函數,對10個數字排序后輸出.
2. 設計一個函數,接收一個英文單詞,從文件中查詢該單詞的漢語意思并返回.
? ??
本文轉自 楓葉云 ?51CTO博客,原文鏈接:http://blog.51cto.com/fengyunshan911/2057207
總結
以上是生活随笔為你收集整理的Python函数中的变量和函数返回值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL Server 2005无法输入中
- 下一篇: date -d的灵活应用