Python 函式和模組

2021-07-10 01:38:32 字數 2657 閱讀 4416

函式包含 函式名字、引數、函式體

#定義乙個簡單的echo函式,來模仿linux中的echo

>>>

defecho

(mesage):

print(mesage)

>>> echo(1234)

1234

>>> echo("1232efsfds")

1232efsfds

>>> echo('324324fdf')

324324fdf

>>>

defecho

(mesage):

print("echo> %s" % mesage)

>>> echo('324324fdf')

echo> 324324fdf

#多個引數的情況

>>>

defecho

(mesage1,mesage2):

print("echo> %s %s" % (mesage1,mesage2))

>>> echo(33,44)

echo> 33

44#缺少引數將報錯

>>> echo(33)

traceback (most recent call last):

file "", line 1, in

echo(33)

typeerror: echo() missing 1 required positional argument: 'mesage2'

#return功能

>>>

defadd

(a,b):

return a + b

>>> add(1,2)

3>>> print(add(2,3))

5>>> >>> def

echo

(mesage):

print(mesage)

如果乙個變數定義在乙個函式內部,那麼在這個函式之外是沒有方法呼叫這個變數的:

>>> c=3

>>>

defadd

(): a=1

b=2return a+b+c

>>> add()

6>>> print(a)

traceback (most recent call last):

file "", line 1, in

print(a)

nameerror: name 'a'

isnot defined

>>> print(c)

3>>>

到目前為止好像上面的功能和shell沒啥區別,這兒的模組能看出比shell的優越性了(社會主義比資本主義的優越性^_^),下面定義的這個函式要求使用者輸入自己的年齡然後根據不同的年齡段返回不同的資訊,注意輸入(必須是整型),其他型別將報錯,

函式匯入了sys模組,用到讀取輸入功能。

>>> def age_joke():

print('please input you age?')

age=int(sys.stdin.readline())

if age > 10

and age < 18:

print('you age is %s ,you are young' % age)

elif age > 20

and age < 30:

print('you are still young!')

elif age > 30

and age < 40:

print('you are not young!!')

elif age > 50:

print('you are too old !!!')

else :

print('oh,others!')

>>> age_joke()

please input you age?

10oh,others!

>>> age_joke()

please input you age?

11you age is 11 ,you are young

>>> age_joke()

please input you age?

22you are still young!

>>> age_joke()

please input you age?

32you are not young!!

>>> age_joke()

please input you age?

99you are too old !!!

>>> age_joke()

please input you age?

dfdfss

traceback (most recent call last):

file "", line 1, in age_joke()

file "", line 3, in age_joke

age=int(sys.stdin.readline())

valueerror: invalid literal for

int() with base 10: 'dfdfss\n'

>>>

python函式和模組

python中的函式有以下幾個特點 代表執行單獨的操作 採用零個或多個作為輸入 返回值作為輸出 冪函式符號 用於計算方程,也可用pow代替運算子 例如 2 8 可以用pow 2,8 來表示 1.python模組介紹 2.time datetime 3.random.4.os 5.sys 6.shut...

python函式和模組

def來定義函式,在函式執行完成後可以通過return來返回乙個值,相當於函式上的因變數。函式的重構 在不影響函式執行結果的前提下,對函式的結構進行調整。模組管理 由於沒有函式過載概念,同時定義兩個函式,後面的會覆蓋前面的 def main print 123456 def main print a...

python函式和模組 python內建函式與模組

一 函式中如果return是多個引數,只用乙個引數接收時,是元組 也可以用多個引數接收,那就是解包 def func a 1 b 2 c 3 return a,b,c q,w,e func print func type func q,w,e 輸出 1,2,3 1 2 3 二 函式自己呼叫自己,遞迴...