How can you tell if a while loop will not terminated? - python

how exactly will you know if it will not terminate? is there a function that makes it keep on going? If i want to stop the loop after a certain number of times, how would i do it?

Generally, it's impossible to know ahead of time whether a program will loop forever or eventually stop. This is called the Halting problem. Of course, in practice you can probably make a reasonable guess just by looking at the condition.
a while loop will keep going as long as its condition is true. You do not need a function to make it keep going.
while True:
print "hello, world!"
#no functions required here!
If you want something to loop a certain number of times, it's preferable to use a for loop:
for i in range(10):
print "hello, world!"
#prints ten times
although you still can use a while loop if you really want.
count = 0
while count < 10:
print "hello, world!"
count += 1

A while loop is terminated
if the condition it uses is false at the time it gets evaluated.
Example:
x = 10
while x > 5:
x -= 7
print x
x += 6
print x
successively will print the numbers 3, 9, 2, 8, 1, 7, 0, 6, -1, 5 and only then terminate.
x becomes <= 5 during execution, but only the state at the time where the loop is restarted is relevant.
if it is left meanwhile with break:
x = 10
while x > 5:
print x
x -= 1
break
only prints 10, because it is left "forcefully" afterwards.
A loop which runs a certain number of times would be done
x = 0
while x < n:
do_stuff()
x += 1
or better with for:
for x in range(n):
do_stuff()

Related

Print prime numbers within an interval [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
This code is running for the 1-10 interval but for interval 20-30 it is writing 21 and 27 and I am unable to understand what's wrong in the code. I don't want to know other code; I want to know what's wrong in my code.
start = int(input("Enter the first number of the interval")) #starting of interval
end = int(input("Enter the last number of the interval")). #end of interval
for i in range(start, end+1):
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
for x in range (2,end):
if (i == 0 or i==1):
break
elif (i % x != 0):
print(i)
break
else:
break
This part of code should
print a number if it's prime, otherwise break
but it doesn't.
Do you notice something strange in your code? I do, and it's the fact that in every case the inner for loop breaks after the first iteration, rethink this aspect of your code, and it will work fine.
First, I am not sure whether you want the period after the inputting for the end. Also, your code checks if i is not divisible by x, then print. So for example, your code checks if 21 is divisible by 2. It is not, so your code prints it out and breaks.
Introduction
Your code is effectively testing if a number is odd and if it is, it prints it out.
If start is 1 and end is any number greater than 1, your code is printing every odd number greater than 2 in the interval [1, end].
It is printing all odd numbers, but not all odd numbers are prime!
Dissecting your code
Let's consider the [1, 20] interval. Your code outputs every odd number greater than 2 in the interval [1, 20].
3, 5, 7, 9, 11, 13, 15, 17, 19.
2 is prime and is missing from this list. We can fix that by writing the following within the outer loop but above the inner loop:
if i == 2:
print(i)
Now the output is `
2, 3, 5, 7, 9, 11, 13, 15, 17, 19.
This is better but 9, 15 are not prime numbers.
The if statement with condition (i == 0 or i == 1) inside of your inner loop is not causing any problems. Let's simplify the inner loop by moving this just outside of the inner loop (just above) so that your code becomes
for i in range(start, end+1):
if (i == 0 or i == 1):
# 0 and 1 are not prime
continue
if (i == 2):
# 2 is prime
print(i)
for x in range (2,end):
if (i % x != 0):
print(i)
break
else:
break
All that remains as the potential culprit for your problems is the inner loop so let's focus on that.
Whenever i is even, in the first iteration of the inner loop, we
have x = 2. We know that if i is even that i % 2 is 0 and so i % x != 0 is False and so we move onto the else, in which case we
break out of the inner for loop. This is all fine because no even
integer greater than 2 is prime!
Whenever i is odd, in the first iteration of the inner loop, we
have x = 2. We know that if i is odd that i % 2 is NOT 0 and so
i % x != 0 is True and then we print i and then break out of
the for loop.
We never once have x = 3 or x = 4 and so on!
The above describes precisely what you code is doing, which is ignoring even integers and simply printing out every odd integer.
Solution that outputs what you want
It would help me if I knew what definition of a prime number you have and/or what algorithm you are trying to implement. But since I don't have this information, I can only suggest a solution.
In order to solve your problem, you need to clearly have in mind what a prime number is. There are many equivalent definitions of a prime number (see the Wikipedia prime number page for examples of definitions). I chose a definition that suggests a natural algorithm for finding prime numbers. Whatever definition of prime number you were given, it is possible to prove mathematically that it is equivalent to this (for some this is the first definition of a prime number that they see!):
An integer i is prime if and only if i > 1 AND for all k in {2, 3,
..., i - 1}, i % k != 0.
In words this says that an integer i is prime iff i is strictly greater than 1 and for all integers k from 2 up until i - 1, k does not divide i evenly.
Here it is
start = int(input("Enter Start: "))
end = int(input("Enter End: "))
print(f"\nPrime numbers between [{start}, {end}]:")
for i in range(start, end + 1):
if (i == 0 or i == 1):
# i is not prime
continue
if (i == 2):
# i is prime
print(i)
continue
for x in range(2, i):
if (i % x) == 0:
break
if (i % x) != 0:
print(i)
Example session:
Enter Start: 20
Enter End: 30
Prime numbers between [20, 30]:
23
29
The (i == 0 or i == 1) check should be placed outside the inner for loop. Otherwise, for all i greater than or equal to 2, for every iteration in the inner loop, you will be checking to see if it is less than 2 or not. You are doing this check too much.
We know that when i == 2 that i is prime.
For i > 2, we appeal to the definition of a prime number above.
The inner loop and the last statement applies the second part of the prime definition.

While Loop Counter Confusion

I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
for x in range(7):
y += 1
print('test')
The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.
This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
y += 1
print('test')
y = 0
while y < 5:
print("test")
y += 1
print("break")
Would work.
There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.
Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.
You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.
The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.
After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:
y = 0
while True:
if y < 5:
print('test')
y += 1
else:
print('break')
break
Try
i = 0
while True:
if i == 5:
break
print('test')
i = i + 1

When will python while loop break?

I'm new to python or coding in general. And encountered some while loop question in the following code.
a = int(input('input a number here: '))
def largest_factor(x):
factor = x - 1
while factor > 0:
if x % factor == 0:
return factor
factor -= 1
print(factor)
largest_factor(a)
I'm using python 3.5, and in my understanding, the loop will not break until 0 > 0, so I put the print(factor) to exam that, however, it stopped at the largest factor(e.g. when x = 100, factor prints from 99 all the way to 50, and stopped), and did not reach 0. Is the return statement killed the while loop? Thank you for your time.
There are two ways to leave this loop, waiting until the while statement terminates or by returning the factor.
Your assumption is correct. Once the loop hits the return statement, the function will end. Since 100 is divisible by 50, the loop ends with the function ending.

Why does my while loop output an out-of-bounds value?

So I was doing while loops and I noticed something strange.
count = 0
while count <= 5:
count += 1
print(count)
output:
1
2
3
4
5
6
it's not that I don't understand while loops. It's that how come the count is printed up to six? when it's supposed to print count only if count is less than or equal to 5?
and well 6 is beyond 5. why is this?
I know I could do
count = 0
while count != 5:
count += 1
print(count)
but I just want to understand why does putting <= behave in an odd way?
There is nothing odd about <=; your loop condition allows for numbers up to and including 5. But you increment count and then print it, so you will print 6 last.
That's because count = 5 satisfies your loop condition, then you add one to make it 6 and print. The next time through the loop count <= 5 is no longer true and only then loop ends.
So your code does this:
count = 0, count <= 5 -> True, count += 1 makes count = 1, print 1.
count = 1, count <= 5 -> True, count += 1 makes count = 2, print 2.
count = 2, count <= 5 -> True, count += 1 makes count = 3, print 3.
count = 3, count <= 5 -> True, count += 1 makes count = 4, print 4.
count = 4, count <= 5 -> True, count += 1 makes count = 5, print 5.
count = 5, count <= 5 -> True, count += 1 makes count = 6, print 6.
count = 6, count <= 5 -> False, end the loop.
You could increment the counter after printing:
while count <= 5:
print(count)
count += 1
or you could use < to only allow numbers smaller than 5:
while count < 5:
count += 1
print(count)
Let's walk through the code and see what's happening.
Note: If your code is doing something that you didn't expect it to do, this is a good practice to follow.
count = 0
while count <= 5:
count += 1
print(count)
The count starts at 0
count = 0
while count <= 5: # count = 0. Is 0 <= 5? Yes. Run the code.
count += 1
print(count)
Increment the count so it now equals 1. Print it.
while count <= 5: # count = 1. Is 1 <= 5? Yes. Run the code.
count += 1
print(count)
Increment. Print. Repeat.
Let's move on to the interesting case that's causing the problem.
while count <= 5: # count = 5. Is 5 <= 5? Yes. Run the code.
count += 1
print(count)
In this case the count still satisfies the inequality, so the code runs.
What happens?
The count, which is 5, is incremented and thus prints out 6.
Now that I hope you understand why the problem exists, let's explore alternatives and their advantages, disadvantages, and outputs.
Let's start with your code.
count = 0
while count <= 5:
count += 1
print(count)
Advantages: Does not print out 0
Disadvantages: Prints out 6
What if we removed the = sign?
count = 0
while count < 5:
count += 1
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want
Disadvantages: You have to start at 0 instead of 1
What if we did as you suggested and replaced the < sign with the ! sign?
count = 0
while count != 5:
count += 1
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want
Disadvantages: Fragile. If you ever changed your increment so that it increased by a number like, say, 3, the end point would be skipped over accidentally and the code would continue to run forever. Better to use an inequality
What if we wanted where we start to be the first number that is displayed? Well, to do this we'd have to print out the current number before we change it, so that means we have to flip the order of the events.
count = 1 # Change the first number so it's what we want displayed first.
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Advantages: Does what you want and starts on the first displayed number instead of below it.
Disadvantages: If you want to stick with while loops, this is the way to go, but there is a better way in this case.
In situations like this, where you increment numbers and then perform operations with them, it's much more logical to just use a for loop, which was designed for instances just like this one.
for count in range(1,5):
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want, easier to read, easier to write, less likely to cause bugs based on placement.
Disadvantages: The upper boundary must be known, unlike in a while loop.
It is simple when count equals five you add 1 and it becomes 6 then it is printed and you exit the loop.
Your problem is not about how <= works.
You are adding 1 to count before printing it, so when count is equal to 5, you then add 1 and therefore print 6.
To make things clear i will show the two scenarios with concrete explanation:
a=0
while (a<4):
a=a+1
print(a)
output would be 1,2,3,4
Variable a=0 should satisfy the condition(a<4) of while loop to continue the execution.
a=a+1 is calculated and saved in memory of the loop which is now 1.
Therefore the number 1 would be outputted not 0 as a result of print(a).
In order to iterate again inside the loop; the number 1(that was saved in the memory of the first loop is checked against the a<4 condition). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 2.
Then the number 2 is outputted
and is saved in the memory of the second loop and checked afterwards against the a<4). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 3.
Then the number 3 is outputted
and is saved in the memory of the third loop which is checked afterwards against the a<4). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 4.
Then the number 4 is outputted, even though the condition a<4 should be satisfied. The reason is that, i have stuck inside the loop after satisfaction of previous condition 3<4 and now after i am inside the loop, the execution of the statements is inevitable which will hold to output 4. The number 4 is now saved in the memory of the fourth loop which is checked against the a<4). Which is False, execution stop here.
This scenario would be amenable and understandable to the case of the opposite scenario
a=0
while (a<4):
print(a)
a=a+1
Output would be 0,1,2,3
Variable a=0 should satisfy the condition(a<4) of while loop to continue the execution.
First the print statement is executed, and the first value coined by a in the memory of the first loop is 0. Therefore 0 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which will change to be 1 and not 0.
In order to iterate again inside the loop; the number 1(that was saved in the memory of the first loop is checked against the a<4 condition). Which is True; continue execution as previous.
The print statement is executed, and the value coined by a in the memory of the second loop is now 1. Therefore 1 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 2.
In order to iterate again inside the loop; the number 2(that was saved in the memory of the second loop is checked against the a<4 condition). Which is True; continue execution as previous.
The print statement is executed, and the value coined by a in the memory of the third loop is now 2. Therefore 2 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 3.
In order to iterate again inside the loop; the number 3(that was saved in the memory of the third loop is checked against the a<4 condition). Which is True; continue execution as previous.
First the print statement is executed, and the value coined by a in the memory of the fourth loop is now 3. Therefore 3 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 4.
In order to iterate again inside the loop; the number 4(that was saved in the memory of the fourth loop is checked against the a<4 condition). Which is False; execution stops.
For completeness:
Many beginners have difficulty with this problem conceptually. They often expect the loop to exit as soon as the condition is met, even in the middle of an iteration.
It does not work that way. The while loop condition is only checked at the beginning of each loop. It is the same as how an if block works - if the condition is met at the beginning, the rest of the block will be run, even if the condition stops being met.
If you want to exit a loop partway through an iteration, break can do that. However, you need to check the condition again in order for it to matter. Also keep in mind that you are writing a condition to leave the loop, rather than a condition to stay; so the logic needs to be reversed.
A lot of the time, it is easier to write code logic that checks a condition only partway through, and use an unconditional loop. That looks like (admittedly this is a silly example):
while True:
count += 1
if count > 5:
break
print(count)
In Python 3.8 and above, it is sometimes possible to simplify that sort of code using the so-called "walrus" operator, which assigns a value but also creates an expression rather than a statement (like how = works in C and C++):
count = 0
while (count := count + 1) <= 5:
print(count)
(Note that we cannot use :+= or +:= to avoid repeating count; those simply don't exist.)

Why does this while loop make the program print out my sentence infinite times?

x = 1
while True:
print("This is line number %d"%(x))
x += 1
It seems logical to me that I equal x with number 1. So the next line says: "While it's true that x equals one, print out this sentence.".. But then I put the line "x += 1", which means that x will get bigger everytime... So x should be equal to number 2 the second time around, so "x = 1" is NOT True, so why does it still keep printing then? I don't undertsand While loops very well so if someone could explain it to me it would be great!
You need to place the condition after the while. In your case the condition True is, of course, always True, which is why you get an infinite loop.
Also be sure not to confuse assignment (=) with comparison (==).
x = 1 <-- assign 1 to x
while x == 1: <-- check if x is equal to 1
print("This is line number %d" % x)
x += 1
print(x) <-- outputs "2"
Because of While True.
In each iteration the condition will be checked and the condition for WHILE loop is always True. Being the condition to be true, the loop goes on and on. Thus you are getting infinite loop.

Categories

Resources