若要让函数返回值,请使用return语句:def my_function(x): return 2 * xprint(my_function(6))print(my_function(5))print(my_function(8))执行结果:121016
回答于 2022-05-31 16:52
可以,可以将任何数据类型的参数传递到函数(字符串,数字,列表,字典等),并且传递到函数体内后,参数类型保持不变。def my_function(food): for x in food: print(x)fruits = ["apple", "banana", "cherry"]my_function(fruits)执行结果:applebananacherry
回答于 2022-05-31 16:49
当我们调用函数的时候不传递任何实参,它将使用默认值:def my_function(str = "中国人"): print("我是 " + str)my_function("小学生")my_function("初中生")my_function()my_function("大学生")执行结果:我是 小学生我是 初中生我是 中国人我是 大学生
回答于 2022-05-31 16:41
在我们调用函数的时候,如果不知道传递到函数中的参数个数,我们就可以在参数名称之前添加一个星号*,表示任意参数,在Python中,任意参数通常缩写为*args。这样,在函数调用的时候,无论我们传递了几个参数,都将被按照元组形式接收,并可以访问这些元组项。def my_function(*args): print("The fruit name is " + args...
回答于 2022-05-31 15:52
当我们调用函数的时候,如果不知道要传递的关键字参数的个数,就可以在参数名称前面添加两个星号**,这样,函数将接收参数字典,并可以访问这些字典项。上面提到关键字参数,那什么又是关键字参数呢?当我们调用函数传递参数的时候,使用键=值的这种语法传递参数,就是关键字参数,具体就是“参数名=参数值”得语法形式,...
回答于 2022-05-31 15:48
可以,我们可以使用键=值的这种语法形式传递参数,这样,参数的顺序就无关紧要了。def my_function(fruit1,fruit2,fruit3): print("The fruit name is " + fruit2)#调用函数my_function(fruit1="apple",fruit2="orange",fruit3="banana")执行结果:The fruit name is orange
回答于 2022-05-31 14:04
如果不知道将传递到函数中的参数个数,可在函数定义中的参数名称之前添加 一个星号 *这样,该函数将接收参数元组,并可以相应地访问这些元组项:def my_function(*args): print("The fruit name is " + args[2])#调用函数my_function("apple", "orange", "banana")执行结果:The fruit name is banana
回答于 2022-05-31 14:00
可以用for循环访问字符串;例如fruit = 'apple'for i in fruit: print(i)执行结果:apple
回答于 2022-05-31 12:54
for循环不需要事先设置迭代变量;fruits = ['apple','orange','banana']for i in fruits: print(i)执行结果:appleorangebanana
回答于 2022-05-31 12:52