Python 如何在函数内部使用while循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21074086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:59:32  来源:igfitidea点击:

How to use while loop inside a function ?

pythonwhile-loopraw-input

提问by kartikeykant18

I decide to modify the following while loop and use it inside a function so that the loop can take any value instead of 6.

我决定修改以下 while 循环并在函数中使用它,以便循环可以采用任何值而不是 6。

i = 0
numbers = []
while i < 6:
    numbers.append(i)
    i += 1

I created the following script so that I can use the variable(or more specifically argument ) instead of 6 .

我创建了以下脚本,以便我可以使用变量(或更具体地说是参数)而不是 6 。

def numbers(limit):
    i = 0
    numbers = []

    while i < limit:
        numbers.append(i)
        i = i + 1
    print numbers

user_limit = raw_input("Give me a limit ")      
numbers(user_limit)

When I didn't use the raw_input()and simply put the arguments from the script it was working fine but now when I run it(in Microsoft Powershell) a cursor blinks continuously after the question in raw_input()is asked. Then i have to hit CTRL+ Cto abort it. Maybe the function is not getting called after raw_input().

当我不使用raw_input()并简单地将脚本中的参数放入时,它工作正常,但是现在当我运行它时(在 Microsoft Powershell 中),在提出问题后光标会连续闪烁raw_input()。然后我必须点击CTRL+C来中止它。也许函数在 之后没有被调用raw_input()

Now it is giving a memory error like in the pic. enter image description here

现在它给出了如图所示的内存错误。 在此处输入图片说明

采纳答案by Kobi K

You need to convert user_limitto Int:

您需要转换user_limitInt

raw_input()return value is strand the statement is using i which is int

raw_input()返回值是str并且语句使用的是 iint

def numbers(limit):
    i = 0
    numbers = []

    while i < limit:
        numbers.append(i)
        i = i + 1
    print numbers

user_limit = int(raw_input("Give me a limit "))
numbers(user_limit)

Output:

输出:

Give me a limit 8
[0, 1, 2, 3, 4, 5, 6, 7]