Python函数常见几种return返回值类型
长眠不觉晓 人气:0Python函数常见return返回值类型Python函数return返回值类型主要包括:
class 'int', class 'str', class 'tuple', class 'list', class 'dict', class 'bool', class 'NoneType
#返回一个数字:类型为int def demo(a,b): c = a + b return c print(demo(2,3)) print(type(demo(2,3))) print()
#返回多个结果会自动生成一个tuple:类型为class 'tuple' def demo1(a,b): c = a + b return a,b,c print(demo(2,3)) print(type(demo(2,3)))
#返回值结果可以直接作为元组使用: for i in demo1(2,3): print(i) print()
#返回1个元组:类型为class 'tuple' def demo2(a): return a print(demo2((1,2))) print(type((demo2((1,2))))) print()
#返回1个字符串:类型为class 'str' def demo3(a,b): c = a + b return c print(demo3('aaa','bbb')) print(type(demo3('aaa','bbb'))) print()
#传入1个列表:类型为class 'list' def demo4(a): return a j = demo4(list(range(5))) print('j =',j) print(type(j))
#返回结果可以直接作为列表使用: sum = 0 for i in j: sum += i print('sum = ',sum) print()
#这里注意实参前加*的区别,加*是作为多个实参传入名为a的空元组, #不加*的话是作为1个实参传入a形参,返回类型为:class 'tuple' def demo4(*a): return a k = demo4(list(range(5))) print('k =',k) print(type(k)) print(k[0][2:]) print()
#逆向传入列表,返回class 'tuple',可以作为元组直接使用 def demo4(*a): return a k = list(range(5)) m = demo4(*k) print('m =',m) print(type(m)) for i in m: print(i, end = '') print() print()
#返回1个字典:类型为class 'dict' def demo5(a): return a dict_demo = {'a':1,'b':2} d = demo5(dict_demo) print('d:',d) print('type of d:',type(d)) for i in d.values(): print(i) print()
#返回1个布尔类型:类型为class 'bool' def demo6(a): return True print(demo6(1)) print(type(demo6(1))) print()
#返回None:类型为'NoneType' def demo7(a): return None print(demo6(1)) print(type(demo7(1)))
加载全部内容