Python基础学习:Python的方法构造

Python基础学习:Python的方法构造

讲的比较简单,希望能对刚开始学习Python的小伙伴们有所帮助

# 本篇主要讲解方法构造,主要包括基本的三种情况

# 1、普通方法,不需要入参,也不返回参数
def print_hello():
    print('hello')


# 调用方法的时候需要进行实例化
h = print_hello()
# 这个时候是没有给返回值的,所以会返回None
print(h)


# 2、需要入参的方法
def print_hello_price(price):
    print('hello,你调用我是需要付出代价的,你需要给我一个参数'+price+',并且这个参数是str类型')

# print_hello_price(1)
''' 结果返回会报错
Traceback (most recent call last):
  File "D:/test/PycharmProjects/untitled/test/function.py", line 24, in <module>
    print_hello_price(1)
  File "D:/test/PycharmProjects/untitled/test/function.py", line 22, in print_hello_price
    print('hello,你调用我是需要付出代价的,你需要给我一个参数'+price+',并且这个参数是str类型')
**TypeError: can only concatenate str (not "int") to str**
'''
# print_hello_price([1, 2, 3])
''' 结果返回会报错
Traceback (most recent call last):
  File "D:/test/PycharmProjects/untitled/test/function.py", line 33, in <module>
    print_hello_price([1,2,3])
  File "D:/test/PycharmProjects/untitled/test/function.py", line 22, in print_hello_price
    print('hello,你调用我是需要付出代价的,你需要给我一个参数'+price+',并且这个参数是str类型')
**TypeError: can only concatenate str (not "list") to str**
'''
print_hello_price('代价')
'''
    hello,你调用我是需要付出代价的,你需要给我一个参数代价,并且这个参数是str类型
'''


# 有入参,有返回值
def print_return(value1, value2):
    print('你输入的两个数的和为:%d' % (value1 + value2))
    return '你输入的两个数的和为:%d' % (value1 + value2) + ',这是你想要的返回值'


# 调用方法
s = print_return(1, 2)
'''
    你输入的两个数的和为:3
'''
# 打印返回值
print(s)
'''
    你输入的两个数的和为:3,这是你想要的返回值
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值