Python数据科学初学者函数问题

Python数据科学初学者函数问题,python,function,Python,Function,我正在为数据科学训练营做准备,对编码一无所知。我被困在我现在正在做的这个实验室里 因此,我有以下清单: travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia'] 我需要编写一个名为number_of_destinations的函数,返回旅游目的地列表中的目的地数 这是我的密码: def number_of_destinations(travel_destinations):

我正在为数据科学训练营做准备,对编码一无所知。我被困在我现在正在做的这个实验室里

因此,我有以下清单:

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
我需要编写一个名为number_of_destinations的函数,返回旅游目的地列表中的目的地数

这是我的密码:

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)
返回:

<function __main__.number_of_destinations(travel_destinations)>

我尝试了很多不同的方法,python总是说是的,这基本上是一个函数。有人能帮我找出我做错了什么吗?

您的函数没有返回任何内容,因为您缺少一个return语句。打印功能输出到终端,但不返回,因此需要将其交换

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    return x

听起来好像您没有向函数传递数据

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))

要调用函数,需要在其名称中添加方括号,如果函数采用参数,则需要在方括号中添加一些参数。否则,正如您所看到的,Python只会让您知道您已经输入了函数名

def my_function():
    return "hello"

>>> my_function
<function __main__.my_function()>
>>> my_function()
'hello'

即使你的训练营可能不需要任何编码知识,你也应该试着学习中的例子。

你也可以在function中传递默认参数

旅游目的地=[‘阿根廷’、‘墨西哥’、‘意大利’、‘芬兰’、‘加拿大’、‘克罗地亚’] def目的地数量目的地=旅行目的地: 返回目的地 打印目的地的数量
您可以使用count变量并在列表中循环并打印其中的值的数量 使用count_城市变量

def num_of_destinations(travel_destinations):
city_count=0
for city in travel_destinations:
    city_count+=1
print(city_count)

或者,该函数可以更一般化,以返回列表的长度。检查传递的参数是否为list类型的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语句。我们在代码中看到的只是一个函数,我们需要了解如何调用函数。如果您打印了目的地的编号,而不是目的地的编号旅行目的地,那么您将看到输出。请尝试python教程的函数部分。这并不能解释他得到的结果。这篇文章是在我回答后编辑的,这可能会有帮助。我看到的唯一编辑只是修正了格式,他们没有改变问题。最初没有。是的,这是一个格式问题。他没有把它放在一个代码块中,所以它被当作一个HTML标记,因为。这不能解释他得到的结果。没有看到OP的编辑。不管怎样,这个解决方案应该对他有效,并解决他的问题,但当我尝试调用函数number_of_destinations时,它只是返回而不是6。但是如果我只是运行你在上面发布的代码行,它会工作并返回“6”,这是正确的。当您调用函数number_of_destinations而不使用参数travel_destinations时,它将返回有关函数的信息,该函数是uu main_u的函数,即您正在运行的脚本。谢谢!成功了。你们帮了我的忙,我很感激+10是解释用户为什么会得到那个输出的唯一答案。虽然这段代码可能会解决这个问题,但它如何以及为什么会解决这个问题将真正有助于提高你的帖子的质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。