从While循环结构转换为函数调用

时间:2014-06-15 00:32:58

标签: 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

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

  

将此while循环转换为可以调用的函数,并使用变量替换测试中的6(i&lt; 6)。

如果你可以提供帮助,并在外行人的条款中写下每一行的重要性,那对我有很大的帮助。

这是我的第一次尝试:

def whilefunc(i):
    numbers = []
    for i in range(0,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
    for num in numbers: 
        print num

9 个答案:

答案 0 :(得分:3)

black_bird提出的上述问题是来自Zed Shaw Study Drill 1 from Exercise 33Learn Python the Hard Way

在ex33 SD1中,Shaw要求你从练习循环中获取他的示例并转换为将硬编码循环条件替换为变量的函数。虽然上面的一些答案完成了目标,但没有一个遵循Shaw概述的指令,这些指令只需要传递一个参数(上面的最后一个答案是关闭的,但是传递了两个)。以下是两个答案。第一个是与ex33的Shaw's Study Drill 1一致的最佳答案,与读者在这一点上学到的内容一致。只传递一个参数。第二个获取用户输入,而不是在函数调用中对数字进行硬编码。

第一个回答:

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)

这是第二个答案:

def buildList(num):
    #Convert num to int else infinite loop because num is a string
    num = int(num)  
    numList = []    
    i = 0       
    while i < num:
        numList.append(i)
        i += 1
        print "i: %d, " % i,
        print "list: ", numList

#getting/passing a string; converted to int within the function
answer = raw_input("Enter a number less than 10: ")
buildList(answer)

答案 1 :(得分:1)

它要求您使用函数调用模拟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

<强>输出:

At the top i is 0
Numbers now:  [0]
At the bottom, i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom, i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom, i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom, i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom, i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom, i is 6
0
1
2
3
4
5

答案 2 :(得分:1)

我对这个问题迟到了,但我也参加了本课程,并认为我可以加入讨论。我认为以下代码正确回答了本课程的1-3次学习练习。

public class FXMLDocumentController implements Initializable, NativeMouseListener {

@FXML
private TextField txt_Search;

@Override
public void initialize(URL url, ResourceBundle rb) {

   txt_Search.setText("dvdf"); //this is work and no problem is in here
           Listener();
}
public void Listener() {
    // Clear previous logging configurations.
    LogManager.getLogManager().reset();
    // Get the logger for "org.jnativehook" and set the level to off.
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.OFF);
    try {
        GlobalScreen.registerNativeHook();
    } catch (NativeHookException ex) {
        System.err.println("There was a problem registering the native hook.");
        System.err.println(ex.getMessage());

        System.exit(1);
    }
    // Construct the example object.
    FXMLDocumentController example = new FXMLDocumentController();
    // Add the appropriate listeners.
    GlobalScreen.addNativeMouseListener(example);
}

 @Override
public void nativeMouseClicked(NativeMouseEvent nme) {
    if (nme.getClickCount() == 2) {
        System.out.println("Double Click Event");
        txt_Search.setText("Mouse clicked");
    }

}

@Override
public void nativeMousePressed(NativeMouseEvent nme) {
    // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void nativeMouseReleased(NativeMouseEvent nme) {
    //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

输出与上述相同。

答案 3 :(得分:1)

认为Zed Shaw只是希望我们将while循环(而不是for循环)转换为函数...所以我认为它就像这一样简单。

def functiontocallforlist(x):
numList = []
i = 0
while i < x:
    print "At the top i is %d" % i
    numList.append(i)

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

#You can put whatever number you want as x really.
functiontocallforlist(8)

答案 4 :(得分:0)

    def list_of_numbers(length):
       working_list = []
       for i in range(length):
          print "At the top i is %d" %i
          working_list.append(i)
          print "numbers now: ", working_list

       return working_list


    numbers = list_of_numbers(6)

    print "The numbers: "

    for num in numbers:
       print num

输出:

At the top i is 0
numbers now:  [0]
At the top i is 1
numbers now:  [0, 1]
At the top i is 2
numbers now:  [0, 1, 2]
At the top i is 3
numbers now:  [0, 1, 2, 3]
At the top i is 4
numbers now:  [0, 1, 2, 3, 4]
At the top i is 5
numbers now:  [0, 1, 2, 3, 4, 5]
The numbers: 
0
1
2
3
4
5

答案 5 :(得分:0)

def while_loop(number, increment):

    i = 0
    numbers = []

    while i < number:
        print "At the top i is %d" % i
        numbers.append(i)   

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


    print "The numbers: "


    for num in numbers:
        print num

while_loop(int(raw_input("Enter a number: ")), int(raw_input("Enter increment: ")))

答案 6 :(得分:0)

# get the input from the user for i
i = int(input("i>"))
# create an empty list and fill it later
numbers = []
# get input from user for the variable to use in while
num = int(input("num>"))
# Create a function and use while loop
def yourfunction(i):
    while i < num:
        # if user input for "i" is less than the user input for "num"
        print(f"at the top of i is {i}")
        # once i is printed, Add i to the list
        numbers.append(i)
        #once i is added to the list, print the list
        print("numbers now", numbers)
        # Then increment i by 1
        i = i + 1
        #once incremented, print i and repeat
        print(f"At the bottom of i is {i}")
# Call the function
yourfunction(i)
# print the newly created list
print(f"the new list is {numbers}")
# use of for loop 
for num in numbers:
    print(num)][1]

以下链接中提供了输出

答案 7 :(得分:0)

正如@alwayslearnedstuff回答的那样,我认为ZED SHAW并不是要创建一个功能类似于while循环而不是使用while循环的函数。但是我很想念,在尝试了很长时间之后,我在里面使用了for循环。我只想在这里分享我有趣的代码,尽管您已经得到了答案。

def function_as_while(length):
numbers = []
for i in range(length):
    print(f"At the top i is {i}")
    numbers.append(i)
    print(f"numbers now: {numbers}")

return numbers
numbers = function_as_while(int(input("Enter list length:  ")))
print("The numbers: ")
for number in numbers:
    print(number)

我所做的是创建了一个充当while循环的功能。为了获得更多乐趣,我给了length参数,这个值是我int(input("Enter list length: "))从用户那里得到的一个小部分。

我希望你喜欢它!

答案 8 :(得分:-1)

我有一个解决方案,我认为可能更简单!我才刚刚起步,我认为我的无知使事情变得简单。另外,我正在研究Zed A Shaw的Python 3书。

这是我想出的:

def loop(material):  #here is where I define the function (loop) with a variable (material)

    i = 0      #the rest of the exercise can remain pretty much intact
    numbers = []

    while i < material:    #I have replaced the number 6 with my variable
        print(f”At the top i is {i}”)
        numbers.append(i)

        i = i + 1
        print(“Numbers now: “, numbers)
        print(f”At the bottom i is {i}”)

    print(“The numbers: “)

    for num in numbers:
        print(num)

loop(10)   #here I call the function and define the variable as 10

希望这很有道理!