需要帮助理解一些代码(初学者)

时间:2016-06-24 20:20:55

标签: python python-3.x

我正在尝试了解while和for循环。此功能打印出列表中的最大数字。但是,我不完全确定它是如何工作的。任何人都可以打破它对我有用的方式。也许一步一步和/或用流程图。我很挣扎,想学习。

def highest_number(list_tested):
    x=list_tested[0]
    for number in list_tested:
        if x<number:
            x=number
    print(x)

highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3])

3 个答案:

答案 0 :(得分:4)

理解新代码最有用的一点是逐步完成:

PythonTutor有一个可视化工具:在代码中粘贴并点击可视化执行。

从第一个到最后一个数字,这是怎么回事说: 这个新号码比我的号码大吗?如果是,请保留新号码,如果不保留旧号码。

最后,x将是最大的数字。

答案 1 :(得分:1)

请参阅我对每行的逐步说明的评论

def highest_number(list_tested): # function defined to take a list
    x=list_tested[0] # x is assigned the value of first element of list
    for number in list_tested: # iterate over all the elements of input list
        if x<number: # if value in 'x' is smaller than the current number
            x=number # then store the value of current element in 'x'
    print(x) # after iteration complete, print the value of 'x'

highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3]) # just call to the function defined above

基本上,该函数按值查找列表中的最大数字。 它首先将大数(x)设置为列表的第一个元素,然后继续将其与列表的其他元素进行比较,直到找到一个大于迄今为止发现的最大数字的元素(存储在x中) )。所以最后,最大值存储在x。

答案 2 :(得分:0)

看起来你是编程世界的新手。也许你应该从一些基本概念开始,因为/ while循环是其中之一,在你跳到类似的东西之前对你有所帮助。

以下是您可以在互联网上轻松找到的解释之一http://www.teamten.com/lawrence/programming/intro/intro8.html