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,这是你想要的返回值
'''