Computer Science
Python Infinite Loop
A Python infinite loop is a loop that runs indefinitely without stopping. It occurs when the loop condition is always true or when there is no condition to stop the loop. This can cause the program to crash or become unresponsive.
Written by Perlego with AI-assistance
Related key terms
1 of 5
5 Key excerpts on "Python Infinite Loop"
- eBook - ePub
- Kuldeep Singh Kaswan, Jagjit Singh Dhatterwal, B Balamurugan(Authors)
- 2023(Publication Date)
- Chapman and Hall/CRC(Publisher)
5 Iterative Control StructureDOI: 10.1201/9781003202035-5Looping is a program or script procedure that performs repetitive (or iterative) tasks. The loop is a sequence of instructions (a block) that is executed repeatedly while or until some condition is met or satisfied. Each repetition is called an iteration. All programming and scripting languages provide loop structures, and, like other languages, Python has several looping constructs [28 ].Algorithm design is frequently based on iteration and conditional execution.5.1 The While Loop
The output of Program 5.1 (counting.py) counts up to five.print (5) print (4) print (3) print (2) print (1)Output 5 4 3 2 1How would you write the code to count to 10,000? Would you copy, paste, and modify 10,000 printing statements? You could, but that would be impractical! Counting is such a common activity, and computers routinely count up to very large values, that there must be a better way. What we would really like to do is print the value of a variable (call it count), then increment the variable (count += 1), repeating this process until the variable is large enough (count == 5 or maybe count == 10000). Python has two different keywords, while and for , that enable iteration [29 ].Program 5.2 (loopcounting.py) uses the keyword while to count up to five:count = 1 while count <= 5: print (count) count += 1Output 1 2 3 4 5The while keyword in Program 5.2 (loopcounting.py) causes the variable ‘count’ to be repeatedly printed then incremented until its value reaches five. The block of statementsprint(count) count += 1is executed five times. After each print of the variable count - eBook - PDF
- Haythem Balti, Kimberly A. Weiss(Authors)
- 2021(Publication Date)
- Wiley(Publisher)
If you changed the range to a different number, then the for statement would iterate that many times. NOTE If you’ve used other programming languages such as C, C++, or Java, then you might notice that the for loop in Python doesn’t use braces ({}) to mark the beginning and end of the code block that will be iterated with the loop. Rather, Python uses indenting to determine what code to run. THE WHILE LOOP An if statement evaluates a condition, performs specific activities based on that condition, and then moves on to the next set of instructions in the code. Although similar in execution, a while loop repeats a specific set of instructions as many times as needed as long as a con -dition is True. We use the term iteration to refer to each time a set of instructions runs. The basic syntax for a while loop is: while ( condition == True): < statement(s) > In order to iterate through a loop a given number of times, we use a counter variable to increment the variable by a constant measure. For example, we might increase the counter variable by 1, or we may double it. We often refer to that counter variable as an “incrementer.” 147 Lesson 7: Controlling Program Flow with Loops This changing of the counter variable used in the condition is extremely important as it ensures that the condition will eventually stop being True . Without such a condition, we would end up with an endless loop that would run forever, commonly referred to as an infinite loop. In the example of using a while statement presented in Listing 7.2, we simply display the integers 0 through 9. LISTING 7.2 Using a while statement i = 0 while ((i < 10) == True): print(i) i = i + 1 This listing goes through the following steps: 1. It starts by setting a variable i to 0. 2. It then uses a while loop that will run as long as i is less than 10. We can see that the while statement checks to see if i is less than 10. - eBook - PDF
- Cay S. Horstmann, Rance D. Necaise(Authors)
- 2019(Publication Date)
- Wiley(Publisher)
125 C H A P T E R 4 LOOPS C H A P T E R G O A L S To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To process strings To use a computer for simulations C H A P T E R C O N T E N T S © photo75/iStockphoto. 4.1 THE WHILE LOOP 126 SYN while Statement 127 CE 1 Don’t Think “Are We There Yet?” 130 CE 2 Infinite Loops 130 CE 3 Off-by-One Errors 131 ST 1 Special Form of the print Function 132 C&S The First Bug 132 4.2 PROBLEM SOLVING: HAND-TRACING 133 4.3 APPLICATION: PROCESSING SENTINEL VALUES 135 ST 2 Processing Sentinel Values with a Boolean Variable 138 ST 3 Redirection of Input and Output 138 4.4 PROBLEM SOLVING: STORYBOARDS 139 4.5 COMMON LOOP ALGORITHMS 141 4.6 THE FOR LOOP 145 SYN for Statement 145 SYN for Statement with range Function 146 PT 1 Count Iterations 148 HT 1 Writing a Loop 149 4.7 NESTED LOOPS 152 WE1 Average Exam Grades 155 WE2 A Grade Distribution Histogram 157 4.8 PROCESSING STRINGS 159 4.9 APPLICATION: RANDOM NUMBERS AND SIMULATIONS 164 WE 3 Graphics: Bull’s Eye 167 4.10 GRAPHICS: DIGITAL IMAGE PROCESSING 169 4.11 PROBLEM SOLVING: SOLVE A SIMPLER PROBLEM FIRST 174 C&S Digital Piracy 180 126 In a loop, a part of a program is repeated over and over, until a specific goal is reached. Loops are important for calculations that require repeated steps and for processing input consisting of many data items. In this chapter, you will learn about loop statements in Python, as well as techniques for writing programs that process input and simulate activities in the real world. 4.1 The while Loop In this section, you will learn about loop statements that repeatedly execute instructions until a goal has been reached. Recall the investment problem from Chapter 1. You put $10,000 into a bank account that earns 5 percent inter- est per year. - eBook - PDF
The Python Audio Cookbook
Recipes for Audio Scripting with Python
- Alexandros Drymonitis(Author)
- 2023(Publication Date)
- Focal Press(Publisher)
2.6 Loops in Python Python has structures that make parts of our code run in a loop, for a specified number of times. In this section we will look at two different ways to run loops in Python. Ingredients: • Python3 • An interactive Python shell Process: There are two different ways to run code in a loop, using the for or the while reserved keywords. Let us include the if test we already wrote, in a for loop. The code is shown in Shell 2.25. Shell 2.25 A for loop. >>> for i in range(10): ... if i == 5: ... continue ... print(i) ... >>> In this script, we have used the for keyword, combined with range(). range(), which is a class rather than a function (more on classes in Chapter 8), takes from one to three arguments. Here we have passed one argument which is the “stop” argument. This means that range() will iterate over a range from value 0, until it reaches [stop – 1], and it will increment by 1 every time. Essentially, when using range() with one argument only, it will iterate as many times as the argument we pass to it, in our case, it will iterate ten times. 26 Writing Your First Python Programs range() returns a list with the values it iterates over. In this code it will return the follow- ing list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The for loop will iterate over this list and will assign each of its values to the variable i, every time assigning the next item of the list. Inside the body of our loop we can use this variable for any task we want. This example is very simple and all it does is print on the console the value of i except from the iteration where i is equal to 5. This is achieved by using the reversed keyword continue. This word skips any code of the structure that includes it, that is written below it. So, when our if test is true, the code written below this test will be skipped, and the for loop will continue to the next iteration. Running this script will print the following on the console. - eBook - PDF
A Student's Guide to Python for Physical Modeling
Second Edition
- Jesse M. Kinder, Philip Nelson(Authors)
- 2021(Publication Date)
- Princeton University Press(Publisher)
If you have a loop like for ii in range (10**6): , then you could insert the following line: if ii % 10**5 == 0: print ( {:.0f} percent complete . format ( 100*ii/10**6 )) Here the percent sign indicates the arithmetic operation of remainder (Section 2.3.3). 3.1.4 Infinite loops When working with loops, there is the danger of entering an innite loop that will never terminate. This is usually a bug, and it is useful to know how to halt a program with an innite loop without quitting Python itself. The easiest way to halt a Python program is to issue a KeyboardInterrupt by typing . This will work on most programs and commands. Try it now. At the IPython command prompt, type while True : print ( Here we go again ... ) When you hit , Python will enter an innite loop. Halt this loop by typing . 1 can also be used to halt commands or scripts that are taking too long, or lengthy cal-culations that you realize are using the wrong input. Just click in the IPython console pane, and type . There is also a red Stop button in the upper-right corner of the IPython console that 1 If you are using a Jupyter notebook, will not work. You must use the “Interrupt Kernel” button (stop button) or the three-key sequence, , , . Jump to Contents Jump to Index 38 Chapter 3 Structure and Control will issue a KeyboardInterrupt from within Spyder (see Figure 1.1, page 7). Run the innite loop command again, and halt it with the Stop button. It may take a while for Python to respond, depending on what it is doing, but or the Stop button will usually halt a program or command. However, if Python is completely unresponsive, you may have to exit Spyder or force it to quit with the Restart kernel option in the Options menu to the right of the Stop button on the IPython console pane (again see Figure 1.1). If this happens, you could lose everything you have not saved, so be sure to save your work frequently.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.




