[英]Problem with question 1, week 3, Introduction_to_Data_Science_in_Python coursera
[英]Python Data science beginner function question
我正在为数据科学训练营做准备,对编码一无所知。 我卡在了我现在正在做的这个实验室里。
所以我有这个列表:
travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
我需要编写一个名为 number_of_destinations 的 function,它返回列表 travel_destinations 中的目的地数量。
这是我的代码:
def number_of_destinations(travel_destinations):
x = len(travel_destinations)
print (x)
哪个返回:
<function __main__.number_of_destinations(travel_destinations)>
我尝试了很多不同的方法,而 python 基本上一直吐出“是的,这是一个函数”。 谁能帮我弄清楚我在这里做错了什么?
要调用函数,您需要在其名称中添加方括号(如果函数接受参数,则需要在方括号中添加一些参数)。 否则,如您所见,Python 只会让您知道您输入了一个函数的名称。
def my_function():
return "hello"
>>> my_function
<function __main__.my_function()>
>>> my_function()
'hello'
即使您的训练营应该不需要编码知识,您也应该尝试完成Python 教程中的示例。
听起来您没有将数据传递给函数。
def number_of_destinations(destinations):
x = len(travel_destinations)
print (x)
return x
travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
destinations_length = number_of_destinations(travel_destinations)
你可以试试:
def number_of_destinations(destinations):
return len(travel_destinations)
travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
print(number_of_destinations(travel_destinations))
您还可以在功能中传递默认参数。
travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
def number_of_destinations(destinations=travel_destinations):
return len(travel_destinations)
print(number_of_destinations())
或者,该函数可以更通用地返回列表的长度。 检查传递的参数是否为列表类型的 if 条件是可选的。 条件也可以是函数的一部分。
def func(lst):
return (len(lst))
travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
if type(travel_destinations=='list'):
x = func(travel_destinations)
print (x)
else:
print ('invalid input type')
您的函数不返回任何内容,因为您缺少 return 语句。 打印功能输出到终端但不返回,因此您需要将其换掉。
def number_of_destinations(travel_destinations):
x = len(travel_destinations)
return x
您可以使用 count 变量并遍历列表并使用 count_city 变量打印其中的值数
def num_of_destinations(travel_destinations):
city_count=0
for city in travel_destinations:
city_count+=1
print(city_count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.