从While循环结构转换为函数C

2024-04-24 21:29:36 发布

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

我正在学习Python中的一个例子,就是Python,我只是想不通。我想我只是在讨论改变程序的理论元素,而不是写物理行,但我可能完全错了。在

i = 0
numbers =[]
while i < 6:
    print "At the top i is %d" %i
    numbers.append(i)

    i += 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" %i

print "The numbers: "
for num in numbers:
    print num

这是我正在使用的代码,问题/提示如下:

Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.

如果你能帮忙,用外行的话二次写出每一行的意义,那对我会有很大的帮助。在

这是我的第一次尝试:

^{pr2}$

Tags: thein元素istop物理理论num
3条回答

它要求您用函数调用来模拟while循环。您只需要递归地调用函数本身。在

def f(i,x,numbers):
    if (i < x):
        print "At the top i is %d" %i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" %i
        f(i,x,numbers)
    return numbers

numbers = f(0,6,[])
for num in numbers:
    print num

输出:

^{pr2}$

上面由布莱克·伯德提出的第一个问题是来自zedshaw的Learn Python the Hard Way。在

在ex33sd1中,Shaw要求您以练习中的while循环为例,将其转换为一个函数,将硬编码的循环条件替换为变量。虽然上面的一些答案实现了目标,但没有一个遵循Shaw所概述的指令,即只需要传递一个参数(上面最后一个答案很接近,但通过了两个)。下面是两个答案。第一个是最好的答案,符合肖的研究演习1从ex33与读者已经学到的这一点。只传递一个参数。第二个函数获取用户输入,而不是在函数调用中硬编码一个数字。在

第一个答案:

def buildList(num):
    numList = []    
    i = 0       
    while i < num:
        numList.append(i)
        i += 1
        print "i: %d, " % i,
        print "list: ", numList
    #note: you don't need to return a value

#you can hard code any number here, of course
buildList(6)

第二个答案是:

^{pr2}$

我回答这个问题晚了,但我也在上这门课,我想我可以补充一下讨论内容。我认为下面的代码正确回答了本课的1-3个学习练习。在

    numbers = []
    def numbers_list(x,y):
        i = 0
        while i < x:
            print "At the top of i is %d" % i
            numbers.append(i)
            i += y
            print "Numbers now: ", numbers
            print "At the bottom of i is %d" % i
        return numbers

    numbers_list(6,1)
    print "the numbers: "

    for num in numbers:
        print num

输出将与上述相同。在

相关问题 更多 >