Pythonでの関数定義およびパラメータの例

1751 ワード

1.関数定義
                ,              ,          ,                   (        )

事前定義関数(直接使用可能)
カスタム関数(自己作成)
なぜ関数を使用しますか?
      ,                     ,              ,           ,         ,        ,         。

    ,      ,    。

関数の定義と呼び出し
def    ([    ])    //  
    ([    ])     //  

例:
    :def fun():

   print("hello world")

    :

fun()

hello world

スクリプトの例:
#/usr/bin/env python
# -*- coding:utf-8 -*-
# 2018/11/26 19:49
#FengXiaoqing
#int.py
def fun():

    sth = raw_input("Please input sth: ")
    try: #    

        if type(int(sth))==type(1):

        print("%s is a number") % sth
    except:

    print("%s is not number") % sth

fun()

2.関数のパラメータ
         

      ,     ,              ,    "  "      ,     ,              ,    "  "def fun(x,y):  //  print x + y

fun(1,2)     //  
3
fun('a','b')

ab

3.関数のデフォルトパラメータ
練習:
       PID

   /proc  

os.listdir()  

方法1:
#/usr/bin/env python
# -*- coding:utf-8 -*-
# 2018/11/26 21:06
# FengXiaoqing
# printPID.py
import sys
import os
def isNum(s):

    for i in s:       
     if i not  in '0123456789':            
         break    #             

     else:   #  for i        

            print  s
for j in os.listdir("/proc"):

  isNum(j)

関数のデフォルトパラメータ:
    (    )   
 def fun(x,y=100)    

        print x,y

    fun(1,2)

    fun(1)

  :    
def fun(x=2,y=3):

        print x+y



  :

    fun()    5

    fun(23)    26

    fun(11,22)    33