My goal is to make a program that prints onscreen all of the prime numbers it can find, however I have this issue where the while loop runs only once, instead of repeating forever.
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
i = 3
while i * i <= num:
if num % i == 0:
return False
i += 2
x = 1
while True:
x += 1
if isPrime(x):
print (x)
I also have tried adding print("You can see this.") at the very end of the code, and it runs, but only once.
I'm sure it's a common mistake, since Python is very strict on indentation, but could you guys help me discover it? Thanks in advance.
You need to return True at the very end, after and outside the final loop. Otherwise the function ends without explicitly returning anything, so it implicitly returns None which is interpreted as false.
The i +=2 is indented too deep, the inner loop never quits.
It should read
while i * i <= num:
if num % i == 0:
return False
i += 2
Otherwise i never increases and the loop goes on and on and on.
Related
When I run this code and give input as 25 it should return me its not a prime num,
But when I debug the code the range values are not iterating into if condition, only the first value of the range is passed and if its not == 0 it moves to the else part.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
else:
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Please help me why its working like this , I am new to programming . TIA
As stated in a comment, this is an easy fix. Simply move the else statement's return to outside of the loop.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. use print instead.
I discovered that for whatever reason for loops never run with the final value an easy fix is to just add 1 to the ending value.
I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while X repeats when X equals to True so in while True it's always True. It only breaks with break statement.
In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.
If you want to use while:
i = 0
while i < 10:
i += 1
print(i)
Or
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while:
for i in range(10):
print(i)
while True
will make the loop run forever because "true" always evaluates to true. You can exit the loop with a break.
To achieve what you want to do, I would use
while i < 10:
print (i)
i++
That is because there isn't anything telling you to terminate the loop. So it will continue even after the if statement isn't satisfied.
This is why it is generally not a great practice to use while True
You can achieve the same thing with a for loop when the break condition is built into the loop:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True which means statement will never gets false so there is never end to while loop even if if condition gets fail. So the while loop will continue running till you interrupt.
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop to false when if loop fails
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False
Hey guys I know this question might seem dumb, but I just started. This is Python 3.7.
Any way I have written 2 versions of the code, the second one works, but I've added another while loop where I thought it wasn't needed. Why doesn't the first version work? Its iterating a list of numbers (nums).
This is from a problem statement:
Write a function that takes in a list of integers and returns True if it contains 007 in order.
spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False
My first code was this, and it always returned False:
z = 0
for i in nums:
while z < 2:
if i != 0:
break
else:
z += 1
break
if i != 7:
break
else:
return True
return False
Why does this change, make it work?
z = 0
for i in nums:
while z < 2:
if i != 0:
break
else:
z += 1
break
while not z < 2:
if i != 7:
break
else:
return True
return False
Thanks very much!
Your problem is the way you're using the while-loop. The code in the while-loop is executed as long as the condition is met. However, you call a break or return inside the while-loop in each way.
So what you actually want to use is an if-statement instead of the while-loop. Then the break would work the way you expected it to work in the first example. The break makes the program jump out of the current loop, that is the while-loop. But for the first example to work correctly, it should jump out of the higher for-loop. Using if instead of while should fix this.
Maybe try something like this:
z = 0
for i in nums:
if z < 2:
if i == 0:
z += 1
else:
if i == 7:
return True
return False
Note - Go down to the edits if you want the more recent code, look here if you want to see the original question. I have made edits to the code, however, so mistakes in this code block may be outdated.
As a self-taught Python 3 programmer, I have been working on a way to simplify radical expressions. The one part of the program that does not work, however, is the square factorization. I have a function that detects square numbers, which works fine. The function that does not work is the following-
def sqfactorslist(num):
factors = []
counter = num // 2 + 1
while counter > 0:
if counter == 1:
factors.append(num) #if no square ints other than 1 square into num, append and finish.
while is_square(counter) == True and counter != 1: #If counter is a valid square integer, append it's square and subtract it from num.
if (counter ** 2) >= num:
factors.append(counter ** 2)
num -= counter ** 2
else: #Else, continue with a program.
break
if counter > 0:
counter -= 1 #If counter more than 0, subtract 1 from it
else:
break #If number is equal to or less than 0, break
return factors #If the input is 32, this should return 16 and 2.
It doesn't return anything other than an infinite loop. Anyone know whats wrong?
Edit 1 -- I have changed the program so that it runs, but now I have a stranger issue: If I input a square number as num, for example 16, I get a number larger than the input, e.x. 81, in the return list. I get no returned elements for a non-square number.
To make it run, I indented the first if statement after the end of the second while loop.
Edit 2 -- I have changed the program again, but I come up with another issue similar to the one above. After eliminating another mistake, where I squared numbers already shown to be square, found in the second while loop, the program now has a new problem - If I use a non-square integer, it returns an empty list, and if I use a square integer, like 16, it gives me an infinite loop. Current code shown below --
def findsqfactors(num):
factors = []
counter = num // 2 + 1
while counter > 0:
if counter == 1:
factors.append(num) #If no square ints other than 1 square into num, append then finish.
while is_square(counter) == True and counter != 1: #
if counter >= num:
factors.append(counter)
num -= counter
else:
break
if counter > 0:
counter -= 1
else:
break
return factors
I am new to python and i am still strugling to understand how the sytnax works, how you need to allign your If and else to make it work correctly. How do i really know which else goes with which if? especially when using nested code blocks.
In the code below for the else followed by the comment Prime! from what i understand that else goes with the statement if (n % div == 0): but then why is it alligned with the FOR statement instead?
the last else statement i think goes with if n == 2: but the else is not alligned with it, instead it is after. For the same statement if n == 2: why is n += 1 alligned before pime_count +=1 and not after it.
I understand that the placement of the Else and if is very important because if i decided to move any of them the code stops working. What i can't seem to understand is how does python know which else goes with which if, if the allignment doesnt seem to be consistent.
#!/usr/bin/env python
#
# Problem Set 1a
#
# A program that computes and prints the 1000th prime number.
# Finds primes using trial division (least efficient method)
#------------------------------------------------------------
prime_count = 0
n = 2
while (prime_count <= 1000):
#if even, check for 2, the only even prime
if (n % 2 == 0):
if n == 2:
prime_count += 1
n += 1
else:
# number is odd, possible prime
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else:
# prime!
prime_count += 1
if prime_count == 1000:
print "The 1000 prime is", n
else:
n += 1
The rule is very simple: the else clause must have the same indentation as the statement it refers to (most commonly, an if statement).
Now, here:
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else:
...
you are not using if-else, you are using for-else!
This construct means "execute the else block unless the loop has terminated through a break".
See for ... else in Python for a discussion.
An if goes with an else at the same indentation, so long as there are no other things at lower indentation between them. They have to be in the same "block". However, in your case, the else that's followed by # prime! is not actually joined to an if at all, but rather to the for div in range(3, n, 2): loop before it!
An else attached to a for loop means "execute this code if the for loop completed without hitting a break statement". It can be useful sometimes, but it is often confusing for people who haven't encountered it before!
I think this can help you to understand how python indentation works http://psung.blogspot.com/2007/12/for-else-in-python.html
In a construct like this one:
for i in foo:
if bar(i):
break
else:
baz()
the else suite is executed after the for, but only if the for terminates normally (not by a break).
In other situations else goes after if
There are 2 rules which are fairly simple,
The indent of the if and else have to be the same
for x in range(15):
if x > 10:
print 'x is more than 10'
else:
print 'x is less than or equal to 10'
Nothing with an indent lower than or equal to that of if and elseshould come in between them
So, this is invalid/ will raise a SyntaxError.
for x in range(15):
if x > 10:
print 'x is more than 10'
print x
else:
print 'x is less than or equal to 10'
Also, As stated in PEP 8
Use 4 spaces per indentation level.
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else: # at same indent as for
# prime!
Also, your indent above means for...else loop is made (here else clause is executed if the for loop is exited using break), not if..else.