関数の戻り値の例で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を返した後、

リターンの戻り値

戻り値は、ケの任意のタイプとすることができます

機能を実行するための復帰が終了した後、

戻って違いを印刷

def fun():

    print 'hello world'

      return 'ok'

    print 123

print fun()

hello world

123

None
#/usr/bin/env python

# -*- coding:utf-8 -*-

# FengXiaoqing

#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
#/usr/bin/python

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 -*-

# FengXiaoqing

# :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

おすすめ

転載: blog.51cto.com/fengyunshan911/2416875