简体   繁体   English

For Loop Not Breaking(Python)

[英]For Loop Not Breaking (Python)

I'm writing a simple For loop in Python. 我在Python中编写一个简单的For循环。 Is there a way to break the loop without using the 'break' command. 有没有办法在不使用'break'命令的情况下打破循环。 I would think that by setting count = 10 that the exit condition would be met and the loop would stop. 我认为通过设置count = 10表示将满足退出条件并且循环将停止。 But that doesn't seem to be the case. 但事实似乎并非如此。

NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop. 注意:部分挑战是使用FOR循环,而不是WHILE循环。

import random

guess_number = 0 
count = 0
rand_number = 0

rand_number = random.randint(0, 10)

print("The guessed number is", rand_number)    

for count in range(0, 5):
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        count = 10
    else:
        print("Try again...")
        count += 1

I'm new to programming, so I'm just getting my feet wet. 我是编程新手,所以我只是弄湿了脚。 I could use a 'break' but I'm trying figure out why the loop isn't ending when you enter the guessed number correctly. 我可以使用'休息',但我正在试图弄清楚为什么当你正确输入猜测数字时循环没有结束。

The for loop that you have here is not quite the same as what you see in other programming languages such as Java and C. range(0,5) generates a list, and the for loop iterates through it. 你在这里的for循环与你在其他编程语言中看到的不完全相同,例如Java和C. range(0,5)生成一个列表, for循环遍历它。 There is no condition being checked at each iteration of the loop. 在循环的每次迭代中都没有检查条件。 Thus, you can reassign the loop variable to your heart's desire, but at the next iteration it will simply be set to whatever value comes next in the list. 因此,您可以根据心脏的需要重新分配循环变量,但在下一次迭代中,它将简单地设置为列表中下一个值。

It really wouldn't make sense for this to work anyway, as you can iterate through an arbitrary list. 无论如何,这对于工作来说真的没有意义,因为你可以遍历任意列表。 What if your list was, instead of range(0,5) , something like [1, 3, -77, 'Word', 12, 'Hello'] ? 如果您的列表是,而不是range(0,5) ,如[1, 3, -77, 'Word', 12, 'Hello']怎么办? There would be no way to reassign the variable in a way that makes sense for breaking the loop. 没有办法以一种对破坏循环有意义的方式重新分配变量。

I can think of three reasonable ways to break from the loop: 我可以想出三种合理的方法来摆脱循环:

  1. Use the break statement. 使用break语句。 This keeps your code clean and easy to understand 这使您的代码保持清洁,易于理解
  2. Surround the loop in a try-except block and raise an exception. 在try-except块中环绕循环并引发异常。 This would not be appropriate for the example you've shown here, but it is a way that you can break out of one (or more!) for loops. 这不适用于您在此处显示的示例,但它是一种可以突破一个(或更多!) for循环的方法。
  3. Put the code into a function and use a return statement to break out. 将代码放入函数中并使用return语句进行分解。 This also allows you to break out of more than one for loop. 这也允许您突破多个for循环。

One additional way (at least in Python 2.7) that you can break from the loop is to use an existing list and then modify it during iteration. 您可以从循环中断开的另一种方法(至少在Python 2.7中)是使用现有列表,然后在迭代期间修改它。 Note that this is a very bad way to it , but it works. 请注意,这是一个非常糟糕的方法 ,但它的工作原理。 I'm not sure that this will this example will work in Python 3.x, but it works in Python 2.7: 我不确定这个示例是否适用于Python 3.x,但它适用于Python 2.7:

iterlist = [1,2,3,4]
for i in iterlist:
    doSomething(i)
    if i == 2:
        iterlist[:] = []

If you have doSomething print out i , it will only print out 1 and 2, then exits the loop with no error. 如果你有doSomething打印i ,它只打印出1和2,然后退出循环没有错误。 Again, this is a bad way to do it . 同样, 这是一个糟糕的方法

You can use while : 你可以使用while

times = 5
guessed = False
while times and not guessed:
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        guessed = True
    else:
        print("Try again...")
            times -= 1

For loops in Python work like this. 对于Python中的循环,这样工作。

You have an iterable object (such as a list or a tuple ) and then you look at each element in the iterable, storing the current value in a specified variable 您有一个可迭代对象(例如listtuple ),然后查看iterable中的每个元素,将当前值存储在指定的变量中

That is why 这就是为什么

for i in [0, 1, 2, 3]:
    print item

and

for j in range(4):
    print alist[j]

work exactly the same. 工作完全一样。 i and j are your storage variables while [0, 1, 2, 3] and range(4) are your respective iterables. ij是您的存储变量,而[0, 1, 2, 3]range(4)是您的相应迭代。 range(4) returns the list [0, 1, 2, 3] making it identical to the first example. range(4)返回列表[0, 1, 2, 3] ,使其与第一个示例相同。

In your example you try to assign your storage variable count to some new number (which would work in some languages). 在您的示例中,您尝试将存储变量count分配给某个新数字(在某些语言中可以使用)。 In python however count would just be reassigned to the next variable in the range and continue on. 但是在python中, count只会被重新分配给range的下一个变量并继续。 If you want to break out of a loop 如果你想摆脱循环

  1. Use break . 使用break This is the most pythonic way 这是最pythonic的方式
  2. Make a function and return a value in the middle (I'm not sure if this is what you'd want to do with your specific program) 创建一个函数并在中间return一个值(我不确定这是否是您想要对特定程序执行的操作)
  3. Use a try/except block and raise an Exception although this would be inappropriate 使用try/except块并引发Exception尽管这不合适

As a side note, you may want to consider using xrange() if you'll always/often be breaking out of your list early. 作为旁注,您可能需要考虑使用xrange()如果您总是/经常早点退出列表。

The advantage of xrange() over range() is minimal ... except when ... all of the range's elements are never used (such as when the loop is usually terminated with break) xrange()over range()的优点是最小的...除非......从不使用所有范围的元素(例如当循环通常以break结束时)

As pointed out in the comments below, xrange only applies in python 2.x. 正如下面的评论中指出的那样, xrange仅适用于python 2.x. In python 3 all range s function like xrange 在python 3中,所有range的函数都像xrange一样

In Python the for loop means "for each item do this". 在Python中, for循环意味着“为每个项目执行此操作”。 To end this loop early you need to use break. 要尽早结束此循环,您需要使用break。 while loops work against a predicate value. while循环对谓词值起作用。 Use them when you want to do something until your test is false. 如果您想要做某事,请使用它们,直到您的测试结果为止。 For instance: 例如:

tries = 0
max_count = 5
guessed = False

while not guessed and tries < max_count:
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        guessed = True
    else:
        print("Try again...")
    tries += 1

What @Rob Watts said: Python for loops don't work like Java or C for loops. @Rob Watts说:Python for循环不像Java或C for循环那样工作。 To be a little more explicit... 要更明确一点......

The C "equivalent" would be: C“等价物”将是:

for (count=0; count<5; count++) {
   /* do stuff */
   if (want_to_exit)
     count=10;
}

... and this would work because the value of count gets checked ( count<5 ) before the start of every iteration of the loop. ...这会起作用,因为在循环的每次迭代开始之前, count的值被检查( count<5 )。

In Python, range(5) creates a list [0, 1, 2, 3, 4] and then using for iterates over the elements of this list, copying them into the count variable one by one and handing them off to the loop body. 在Python中, range(5)创建一个列表[0, 1, 2, 3, 4]然后for迭代这个列表的元素,将它们逐个复制到count变量中并将它们交给循环体。 The Python for loop doesn't "care" if you modify the loop variable in the body. 如果修改正文中的循环变量,Python for循环不会“关心”。

Python's for loop is actually a lot more flexible than the C for loop because of this. 因此,Python的for循环实际上比C for循环更灵活。

What you probably want is to use break and to avoid assigning to the count variable. 您可能想要的是使用break并避免分配count变量。

See the following, I've edited it with some comments: 请参阅以下内容,我编辑了一些评论:

import random

guess_number = 0 
count = 0
rand_number = 0

rand_number = random.randint(0, 10)

print("The guessed number is", rand_number)    

# for count in range(0, 5): instead of count, use a throwaway name
for _ in range(0, 5): # in Python 2, xrange is the range style iterator
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        # count = 10 # instead of this, you want to break
        break
    else:
        print("Try again...")
        # count += 1 also not needed

As others have stated the Python for loop is more like aa traditional foreach loop in the sense that it iterates over a collection of items, without checking a condition. 正如其他人所说,Python for循环更像是一个传统的foreach循环 ,因为它迭代了一组项目,而没有检查条件。 As long as there is something in the collection Python will take them, and if you reassign the loop variable the loop won't know or care. 只要集合中有东西,Python就会接受它们,如果重新分配循环变量,循环就不会知道或关心。

For what you are doing, consider using the for ... break ... else syntax as it is more "Pythonic": 对于你正在做的事情,考虑使用for ... break ... else语法,因为它更像是“Pythonic”:

for count in range(0, 5):
    guess_number = int(input("Enter any number between 0 - 10: "))
    if guess_number == rand_number:
        print("You guessed it!")
        break
    else:
        print("Try again...")
else:
    print "You didn't get it."

As your question states NOTE: Part of the challenge is to use the FOR loop, not the WHILE loop and you don't want to use break , you can put it in a function and return when the correct number is guessed to break the loop. 正如你的问题所述注意:部分挑战是使用FOR循环,而不是WHILE循环 ,你不想使用break ,你可以把它放在一个函数中,并在猜到正确的数字来打破循环时返回。

import random


def main():
    guess_number = 0
    count = 0
    rand_number = 0

    rand_number = random.randint(0, 10)

    print("The guessed number is", rand_number)

    for count in range(0, 5):
        guess_number = int(input("Enter any number between 0 - 10: "))
        if guess_number == rand_number:
            print ("You guessed it!")
            return
        else:
            print("Try again...")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM