这些子程序是做什么的?

2024-09-30 01:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在练习Python—使用Python3.5.0—我遇到了这个使用子程序的简短程序。我想弄清楚每个子程序都做些什么?在

事先非常感谢。在

def A(target,mark)
    target=mark[0]
    for numbers in range(10):
        if mark[numbers] > target:
    target = mark[numbers]
    return target


def B (target, mark)
    target=mark[0]
    for numbers in range(10):
        if mark[numbers] < target:
            target = mark[numbers]
    return target


def C (vote,total,vote1,vote0)
    for noofvotes in range(total):
    if vote[noofvotes]==1:
    vote1=vote1 + 1
        else:
    vote0=vote0 + 1
    return vote0, vote1


def D(target,Name):
    found="NO"
    namesinarray=0
    while namesinarray != len(Name) and found == "NO":
        if Name[namesinarray]==target:
            found="YES"
            indexmark= namesinarray
        namesinarray = namesinarray +1

    if found=="YES":
        print(target + " has been found at position " + str(indexmark))
    else:
        print("This name is not in the list")

Tags: nameintargetforreturnifdefrange
1条回答
网友
1楼 · 发布于 2024-09-30 01:36:36

A()搜索mark的前10个元素,如果元素大于target,则继续更新target。结果是,它返回mark的最大元素。B()类似,但它返回mark的最小元素。但是,这些是不需要的,因为有一些名为max()min()的内置函数正是为此而设计的。C()为它的论据接收一个投票列表,给出的总票数,到目前为止对一个人的投票数,以及到目前为止对另一个人的投票数。它通过投票和检查来确定它是0还是1。然后,它会相应地更新选票计数。一旦它添加了所有的投票,它将在tuple中返回它们。(也就是说,如果缩进正确,它就会这样做)。D()被赋予target和{}作为其参数,它搜索{},直到找到{}。如果target被找到,它将打印出目标已在某个位置被找到。如果找不到,它将打印This name is not in the list。这个函数可以改进,因为它使用"YES"和{}作为布尔函数。布尔值是在Python语言中构建的,因此应该使用它。它还可以使用内置方法index(),如下所示:

def D(target, Name):
    try:
        index = Name.index(target)
    except IndexError:
        print("This name is not in the list")
    else:
        print(target + " has been found at position " + str(index))

相关问题 更多 >

    热门问题