In summary, I know 2 is a prime number because it is divisible by 1 and itself but why does it still print 2 if 2%2 = 0 and the range is between 2 and the number you're checking, which in this case is 2. Shouldn't it start at 3?
for num in range (1, 1000):
if num > 1:
for i in range (2, num):
if (num % i ) == 0:
break
else:
print (num)
I expected 3 to be the first output.
2 is printed because for i in range(2, num) performs no iterations when num == 2. This is because the second argument to range() is not included in the list that range() generates. So for the 2 iteration of your outer loop, the equivalent iteration code is:
num = 2
if num > 1:
for i in []:
if (num % i ) == 0:
break
else:
print (num)
which will print 2 since the 'break' line won't be executed.
Python for loops include the first number, but exclude the last number. Because of this, the clause for i in range(2,2) won't actually return any numbers. This is why the number 2 gets printed in your else block.
It also helps to keep your if and else blocks at the same indent level to avoid confusing the computer.
Related
for num in range(2,101):
for i in range(2,num):
if (num % i) == 0:
break
else :
print(num, end = ' ')
I don't understand why the output starts from 2
I thought num starts with 2, and the i also starts with 2
so, (num % i) == 0 is right
What's wrong with me?
When num == 2, range(2, num) is empty, because ranges stop before the end number.
So for i in range(2, num): never executes the body in that case, and therefore it never tests num % i == 0. The loop ends immediately, without executing break, so it goes into the else: block.
I'm trying to make a program that will stop when it gets 5 prime numbers from a range.
I've completed most of the program except the part where it is supposed to stop after it gets 5 numbers.
I've added a condition for it to stop, once the counter reaches 5 but it does not stop and continues to list all the numbers in the range.
Here is code I have:
condition = 0
while condition < 5:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
The condition+=1 never goes through and it lists all the prime numbers from 1 to 20 even though I just want the first 5.
I've tried spacing options with the "condition +=1" but it still does not work
Any help would be appreciated
While is out of for loop, so cannot work obviously. A simple solution is to check required condition later:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
if condition >=5:
break
I think the real problem you are having is that you have written bad code. A much better approach to this problem is to isolate as many pieces as possible.
for example:
def is_prime(x):
"return true if x is prime, otherwise false"
# implement me!
return True
def get_first_n_primes_less_than_y(n, y):
number = 2
condition = 0
while condition != n and number < y:
if is_prime(number):
print(number)
condition += 1
number += 1
get_first_n_primes(5, 20)
The above code, with some tweaking can perform the same task. However, code like this is much simpler to debug and reason about because we have isolated chunks of code (is_prime, has nothing to do with the while loop)
num_results = 5
counter = 0
range_start = 2
range_end = 20
# iterate range
for number in range (range_start, range_end):
# iterate divisors
for divisor in range (2, number):
# check division
if (number % divisor) == 0:
break
else:
print ("%s is a prime number" % number)
counter += 1
break
# check if number of results has been reached
if counter == num_results:
break
# check if number of results has been reached
if counter == num_results:
break
The problem is that you need to run the entire content of the while block before you test the condition again.
Here is a way around
condition = 0
numbers=2
while condition < 5 and numbers < 20:
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
numbers+=1
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
I am trying to print prime numbers in python in the range 3-50. Here is the code:
for i in range(3,51):
flag=0
for j in range(3,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
The code is running correctly except THAT IT IS ALSO PRINTING 4. Please tell if there is anything wrong with the logic of the code (ignore the efficiency issues).
print(2)
for i in range(3,51):
flag=0
for j in range(2,int(i/2)):
if(i%j==0):
flag=1
if(flag==0):
print(i)
When i = 4, the range will be range(2,2) which is 0. It will not enter the if(i%j == 0): block. Thus your flag would always be 0 when i = 4.
One way to solve it would be to just add a check if i is 4.
if(flag==0 and i != 4):
Edit : As commented by others, by incrementing the range by 1 would be a better fix than checking if the value is 4.
for j in range(2,int(i/2)+1)
change range(3,i) to range(2,i) because if we use range(3,i), 4 is not checked with division by 2. As a result 4 is returned as prime.
for i in range(3,51):
flag=0
for j in range(2,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
However, a more structural and efficient way is to use the following:-
def isPrime(num):
for i in range(2,num/2+1):
if (num%i==0):
return False
return True
for i in range(3,51):
if isPrime(i):
print i
We don't need to check the division by all numbers till the number itself for prime. Because if we can check till the half of the given number only for increased efficiency.
start = 3
end = 50
for val in range(start, end + 1):
# If num is divisible by any number
# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)
a = int(input("enter smaller no."))
b = int(input("enter larger no."))
for i in range (a,b+1):
if i>1:
for c in range(2,i):
if i%c == 0:
break
else:
print(i)
In the code above we ran a for loop from minimum to the maximum number and storing the value in i
for i in range (a,b+1):
then we check that the number stored in i is greater than 1 or not as all numbers are divisible by 1 and we don not want to consider it.
if i>1:
after this we run another loop, this time from 2 to 1 less then the number stored in i
for c in range(2,i):
Now we check that the number stored in i is divisible by any of the number from 2 to 1 number less then itself.
if i%c == 0:
If yes then clearly it is not a prime number and we break the loop.
break
And if no we print the number.
else:
print(i)
For 4 it probably does not go inside the if loop. So I increased the range for i.
print(2)
for i in range(3,51):
flag=0
for j in range(2,int(i/2)+1):
if(i%j==0):
flag=1
if(flag==0):
print(i)
for i in range(3,51):
flag=0
for j in range(2,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
This prints
3
5
7
11
13
17
19
23
29
31
37
41
43
47
4%2 = 0
4%3 = 1
So if you start from 3 you will miss out that 4%2 is = 0
If your list would have bigger numbers, you should change
range(2,int(i/2)+1)
for
range(2,math.floor(math.sqrt(n)+1))
For instance, 400 will try numbers until 20 instead of 200.
tryfor j in range(2,i):the numbers 4 is divisible is 1,2,4 if you start from 3 and continue until 4 but not four you can't find any divisors that is why it is considering 4 as a prime
import math
for num in range(1,50):
if num>1:
if num==2:
print(num)
elif num%2==0:
continue
else:
for i in range(3,math.ceil(math.sqrt(num)),2):
if num%i==0:
break
else:
print(num)
It is more efficient as it avoids even numbers and also check for the odd divisors up-to square root of the number which is more efficient than checking up-to only half of the given numbers
I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!
def main():
while (num >= 100) and (num <= 200):
for (num % 5 == 0) or (num % 6 == 0)
print (num)
main()
This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.
n = 0
for i in range(100,201):
if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0):
n += 1
if n%10 == 0:
print(i)
else:
print(str(i) + ", ", end="")
You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add num = num + 1 at the end of your loop block.
It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.
Should be like this:
def main():
num = 100
while (num >= 100) and (num <= 200):
if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0):
print (num)
num = num + 1
main()