Why Continue in While loop is not working in Python? - python

Hello while I was practicing while loop in Python my code was not giving any outputs whatsoever. I am learning python from books only, so it may sound basic: but where is the problem in this code? I was trying to print integers less than 100 which are not divisible by 5.
x=0
while (x<101):
if (x%5==0):
continue
print (x, end=" ")
x=x+1
I was trying to print integers less than 100 which are not divisible by 5

continue goes back to the beginning of the loop, skipping over the rest of the body. This means it skips over x = x + 1. So you keep testing the same value of x.
Instead of a while loop, use a for loop, so the increment isn't in the body that you skip over.
for x in range(100):
if x % 5 == 0:
continue
print(x, end=" ")
If you really want to use while and continue, you can duplicate the code that increments x.
while x < 101:
if x % 5 == 0:
x += 1
continue
print(x, end=" ")
x += 1
Or you could move the increment before the test
while x < 101:
x += 1
if x % 5 == 1:
continue
print(x-1, end=" ")
But notice that this makes it more complicated because you have to subtract 1 when printing to get the value from before the increment.

You should try stepping through your code with a debugger before posting a question here. If you had done this you would have found the problem right away.
Your code gets stuck in an infinite loop. Try this:
x=0
while (x<101):
if (x%5 != 0):
print (x, end=" ")
x=x+1

You got an infinite loop on execution...
when x is 0, it's true, the loop continue on next execution
but x is not incremented. So on the next loop execution, the same result: 0 % 5 == 0 returns true
Solution: increment x before the continue;
so you'll have:
x=0
while (x<101):
if (x%5==0):
x=x+1
continue
print (x, end=" ")
x=x+1
This should be fine !

Related

What is happening to my python program, please tell me? How both if else statement can be true? [duplicate]

This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 1 year ago.
I am currently using python3.9. I have coded a python block of code in which I have put an if else Condition but when I enter my input such as 15 then both conditions became true like the following. I want to know how an if-else condition can be true in both case. You can see it in following screenshot so that you can understand well and help me in this.:
x = input("Enter a number: ")
x = int(x)
def my_func(y):
for i in range(1, y):
if y % i == 0:
print("It is consecutive")
elif y < 2:
print("It is smaller than 2")
else:
print("It is prime")
break
my_func(x)
you are checking multiple times, on one iteration condition may return one aswer, on next - other, in your case firstly it is divisble by 1, prints "It is consecutive", then not divisble by 2 and prints "It is prime", then meets break statement, make an individual check for <2 and then iterate over numbers, and then if it does not return anything print "It is prime", like this
x = input("Enter a number: ")
x = int(x)
def my_func(y):
if y<2:
print("It is smaller than 2")
return
else:
# A prime will not have any factors greater than 1
for i in range(2, y):
if y % i == 0:
print("It is consecutive")
return
print("It is prime")
my_func(x)
The result you are getting is because of the for loop .
For the first iteration the if condition evaluates to true (15 % 1 == 0). So "It is consecutive" is printed , the remaining elif and else conditions are not checked for
For the second iteration, if condition is false (15 % 2 == 0 is false) .It goes to elif condition (y < 2) which is false too , since 15 < 2 is false . The flow goes into the else block and does whatever is specified in it (in this case prints "it is prime" and breaks from the loop )
Hence you get both the statements.
Conclusion - The if-else block isn't executing simultaneously . It is due to the for loop the condition changes and hence the result
So your for-loop is doing the following:
for i in range(1, 15): # Iterate over 1,2,3,4,..
# 1 - [(15 % 1) = 0, True, print("It is consecutive")
# 2 - [(15 % 2) != 0, False...
# (y < 2), False...
# print("It is prime")]
I suspect you want something more like the following:
x = input("Enter a number: ")
x = int(x)
def my_func(y):
# Any number less than 2 is not prime
if y < 2:
print("It is smaller than 2")
# Exit the function early and don't continue onto the for loop
return
for i in range(2, y):
# if this evaluates as True for any of i < y then y is not prime
if y % i == 0:
print("It is consecutive")
# Exit the function and do not complete the for loop
return
# If we have reached here then the for loop has executed fully and no values of i have been found to be factors of y, therefore y is prime
print("It is prime")
my_func(x)
It isn't True in multiple if branches. but for different values of the for loop. If that's code is a primality test, it should be more like that
def my_func(y):
if y < 2:
print("Lower than 2")
return
for i in range(2, y):
if y % i == 0:
print("It is consecutive, because of", i)
break
else:
print("It is prime")
# else is triggered if no `break` used

Which is the most pythonic way for writing a prime number function using for and while loop?

I am about to execute a function which aim is to return a Prime/Not prime statement if its argument is or isn't a prime number. I succeeded using a for loop:
def prime1(n):
z = []
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")`
Then I tried to do the same but using the while loop:
def prime2(n):
z = []
i = 1
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")
Unfortunately, my system continues to calculating without printing me an output.
Can you explain me where I have made a mistake?
The i = i + 1 does nothing in your for loop, since the value of i is overwritten with the next value of the iterator; effectively, the for loop is performing i = i + 1 for you on every iteration, whether or not i divides n. You need to do the same thing in your while loop:
while i < n + 1:
if (n/i).is_integer():
z.append(i)
i = i + 1
The most pythonic way I could think of is below:
def isPrime(n):
return all(n % i for i in range(2, int(n ** 0.5) + 1)) and n > 1
for i in range(1, 20):
print(isPrime(i))
Explanation:
all makes sure that every item in the given expression returns True
n % i returns True if n != 0 (even negative numbers are allowed)
int(n ** 0.5) is equivalent to sqrt(n) and as range always returns numbers up to n - 1 you must add 1
n > 1 makes sure that n is not 1
The problem in your code is that your i = i + 1 in the wrong scope
Your program checks if (n/i).is_integer() which returns False as n / 2 is not a integer
Improving your code:
Instead of (n/i).is_integer() you can use n % i == 0, which returns the remainder equals 0
Next you must place i = i + 1 in the outer scope
And personally, I was never a fan of i = i + 1. Use i += 1
I think the best way is using the code I have shown above.
Hope this helps!
Edit:
You can make it print 'Prime' or 'Not Prime' as follows:
def isPrime(n):
print('Prime' if all(n % i for i in range(2, int(n ** 0.5) + 1))
and n > 1 else 'Not Prime')
for i in range(1, 20):
isPrime(i)
You are increment the iterable variable i inside the if statement, so the variable is never incremented, stucking on an infinite loop.
When you used for it worked because the iterable changes itself after every full iteration of the block.
Moving the incremenf of i one identation block to the left (inside the while instead of for) will work just fine
Code adapted from https://www.programiz.com/python-programming/examples/prime-number
You don't need to check until num and you can go 2 by 2 if you don't have a database of prime numbers
import math
#num = 437
if num > 1:
# check for factors
for i in range(2, int(math.ceil(math.sqrt(num))), 2):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
Our preferred method should not be while loops if we don't need to use them, that being said, we could use list comprehensions:
def prime(n):
z = []
[z.append(i) for i in range(1, n+1) if (n/i).is_integer()]
[print("Prime") if len(z) == 2 else print("Not Prime")]
prime(101)
But lets take a loop at what you got your for loop:
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
The line i = i + doesn't serve the purpose you intend, the loop is going to iterate from 1 to n+1 no matter what
Now the while loop:
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
# i=i+1 does not go inside if statement
i += 1
Now you do need to increment i but if that incrementing only occurs when the if conditions are met, then if the if condition is not met you are going to be stuck at the same i looping over it.
Also try using i += 1 means the same thing

Why is my code running infinitely?

this is an even odd calculator that runs infinitely without any errors. Does anyone know how to fix this? Is it ok for me to call the method with the input from times?
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i + 1
x=0
y=0
if (int(num) % 2 == 0):
even = True
print("even")
elif (int(num) % 2 != 0):
odd = True
print("odd")
if (odd == True):
x += 1
elif (even == True):
y += 1
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
Just a few things you have wrong, the rest are pretty good, explain are in the comments:
All the variables in [x, y , even , odd] are useless at all, so that's why I erased them.
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i+=1 # important thing here, to update the value the symbol is +=, not just +
if (int(num) % 2 == 0):
print("even")
else: # there is no need of elif, if the number is not even, by definition, it is odd
print("odd")
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
you can try it here, and see how do correctly the job :) -> https://repl.it/Nm70/0
Line number 5 should be i = i+1
I'm assuming you have a formatting issue with stackoverflow and not a formatting issue with your actual code. The lines after your while loop need to be indented which I'm assuming you are doing. The problem you have is that you aren't incrementing i. The first line after your input you have i + 1. That does nothing as you aren't assigning it to anything. You have x += 1 and y += 1 later on in your code which increments and assigns. So basically change your i+1 line to be i += 1 or i = i + 1
Everything that you want in the while loop needs to be indented by one "tab" like so:
while i <= time:
#Code goes here

try to use python to find least common multiple, but why doesn't my code work?

hi I am a newbie of python. I was trying to find smallest positive number that is evenly divisible by all of the numbers from 1 to 20, but I was keep getting 20 which obviously is wrong; I don't know why is that.
def even_divisible():
x=1
for i in range(1,21):
if x%i!=0:
x+=1
print x
even_divisible()
anybody knows why ?
Your code has a significant logical flaw; when the for loop ends (after 20 loops), the current value of x is printed, without checking whether it is divisible by the appropriate numbers. You don't restart the for loop from 1 each time you increment x.
You need an outer loop to run until an appropriate x is found; a while loop, as we don't know how long it will run for. To minimally fix your code:
def even_divisible():
x=1
while True: # outer loop
for i in range(1,21): # inner loop
if x % i != 0:
x+=1
break # break for loop
else: # for loop ran to end without break
break # break while loop
print x
You can simplify with any or all for the inner loop. There are a few mathematical simplifications, too; given that we know that x % 20 == 0, we only need look at multiples of 20, and since all integers are integer multiples of 1 we can start from 2:
def evenly_divisible(n):
x = n
while True: # outer loop over multiples of n
if all(x % i == 0 for i in range(2, n+1)): # inner loop over 2-n
return x
x += n

print factors of a number in python

I'm trying to print the factors of the number 20 in python so it goes:
20
10
5
4
2
1
I realize this is a pretty straightforward question, but I just had a question about some specifics in my attempt. If I say:
def factors(n):
i = n
while i < 0:
if n % i == 0:
print(i)
i-= 1
When I do this it only prints out 20. I figure there's something wrong when I assign i=n and then decremented i, is it also affecting n? How does that work?
Also I realize this could probably be done with a for loop but when I use a for loop I can only figure out how to print the factors backwards so that I get: 1, 2, 5, 10....
Also I need to do this using just iteration. Help?
Note: This isn't a homework question I'm trying to relearn python on my own since it's been a while so I feel pretty silly being stuck on this question :(
while i < 0:
This will be false right from the start, since i starts off positive, presumably. You want:
while i > 0:
In words, you want to "start i off at n, and decrement it while it is still greater than 0, testing for factors at each step".
>>> def factors(n):
... i = n
... while i > 0: # <--
... if n % i == 0:
... print(i)
... i-= 1
...
>>> factors(20)
20
10
5
4
2
1
The while condition should be i > 0 and not i < 0 because it will never satisfy it as i begins in 20 (or more in other cases)
Hope my answer helps!
#The "while True" program allows Python to reject any string or characters
while True:
try:
num = int(input("Enter a number and I'll test it for a prime value: "))
except ValueError:
print("Sorry, I didn't get that.")
continue
else:
break
#The factor of any number contains 1 so 1 is in the list by default.
fact = [1]
#since y is 0 and the next possible factor is 2, x will start from 2.
#num % x allows Python to see if the number is divisible by x
for y in range(num):
x = y + 2
if num % x is 0:
fact.append(x)
#Lastly you can choose to print the list
print("The factors of %s are %s" % (num, fact))

Categories