Python—函数和模块

函数包含 函数名字、参数、函数体

#定义一个简单的echo函数,来模仿Linux中的echo
>>> def echo(mesage):
    print(mesage)


>>> echo(1234)
1234
>>> echo("1232efsfds")
1232efsfds
>>> echo('324324fdf')
324324fdf
>>> def echo(mesage):
    print("ECHO> %s" % mesage)

>>> echo('324324fdf')
ECHO> 324324fdf

#多个参数的情况
>>> def echo(mesage1,mesage2):
    print("ECHO> %s %s" % (mesage1,mesage2))


>>> echo(33,44)
ECHO> 33 44

#缺少参数将报错
>>> echo(33)
Traceback (most recent call last):
  File "<pyshell#131>", line 1, in <module>
    echo(33)
TypeError: echo() missing 1 required positional argument: 'mesage2'

#return功能
>>> def add(a,b):
    return  a + b

>>> add(1,2)
3
>>> print(add(2,3))
5
>>> >>> def echo(mesage):
    print(mesage)

函数中的变量和作用域

如果一个变量定义在一个函数内部,那么在这个函数之外是没有方法调用这个变量的:


>>> c=3
>>> def add():
    a=1
    b=2
    return a+b+c

>>> add()
6
>>> print(a)
Traceback (most recent call last):
  File "<pyshell#155>", line 1, in <module>
    print(a)
NameError: name 'a' is not 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?
10
Oh,others!
>>> age_joke()
Please input you age?
11
You age is 11 ,you are young
>>> age_joke()
Please input you age?
22
You are still young!
>>> age_joke()
Please input you age?
32
You are not young!!
>>> age_joke()
Please input you age?
99
You are too old !!!
>>> age_joke()
Please input you age?
dfdfss
Traceback (most recent call last):
  File "<pyshell#190>", line 1, in <module>
    age_joke()
  File "<pyshell#184>", line 3, in age_joke
    age=int(sys.stdin.readline())
ValueError: invalid literal for int() with base 10: 'dfdfss\n'
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贤时间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值