printing even numbers with lists and brackets - python

When I run the following code for some reason it says that the break is incorrect but works if I delete the break.
Can anyone help me to understand why?
composites = []
for i in range(101):
for j in range(i):
if (i % j) == 0:
composites.append(i)
break
print("Composites: ", *composites)

The sample code provided threw a ZeroDivisionError instead of a break error. Problem is with the second range as the modulo function cannot be done with 0.
Since composites are non-prime numbers, factors checking should start from 2. Changing the second range function to range(2, i) should solve this.
composites = []
for i in range(101):
for j in range(2, i):
if (i % j) == 0:
composites.append(i)
break
print("Composites: ", *composites)

This code works for me in python 3.7, range(10) will produce [0,1,2,3,4,5,6,7,8,9] which will give ZeroDivisionError: integer division or modulo by zero
composites = []
for i in range(1,101):
for j in range(2,i):
if (i % j) == 0:
composites.append(i)
break
print("Composites: ", *composites)

Related

ZeroDivisionError when listing factors of a number

The program I am writing is tasked with creating a list of all possible factors of a number, excluding the number itself. My code is as follows:
def list_all_factors(num):
result = []
for i in range(0, num):
if num % i == 0:
result.append(i)
return result
When I call this function I get the following error:
ZeroDivisionError: integer division or modulo by zero
What is causing this issue, and how can I resolve it?
The for loop:
for i in range(0, num)
should be
for i in range(1, num)
We change the lower bound to avoid attempting to divide by zero.
That's because you are trying to divide by zero as the error says in the for loop. You should start the range from 1 to avoid it.
def list_all_factors(num):
result = []
for i in range(1, num+1):
if num % i == 0:
result.append(i)
return result
or list comprehension
def list_all_factors(num):
result = [i for i in range(1,num+1) if num % i == 0]
return result

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

How do I make a long list print in segments?

I'm trying to learn python by writing code I'm interested in, currently I want to list all of the primes up to a number of my choice at runtime. However, when I print the primes they just all get blurted out on one line. If you enter a big number this gets really really long. How can I make it so that my print always does like 10 indices then starts a new line?
Note: this is extremely verbose just for debugging purposes.
My code:
primes = []
numberToGoTo = int(input("Find primes up to what number?\n"))
for i in range(2, numberToGoTo):
for j in range(2, i):
print("Checking to see if {} is a prime. Current divisor: {}".format(i, j))
if i % j == 0 and j > 1 and j < i:
print("{} is not prime".format(i))
break
else:
print("{} is a prime! Adding to list.".format(i))
primes.append(i)
else:
#number of primes
print(len(primes))
#list all primes
print(primes)
You can use create custom print function to do this.
def custom_print(primes, index):
index /= 2
lim = index
while(lim <= len(primes)):
print(primes[lim-index:lim+index])
lim += index
custom_print(primes, 10)
I hope this helps.

prime numbers in python using for loop and break

I have written a python code to find prime numbers between 2 and 30. But my code is not evaluating for 2 and 3. Can anyone tell me what is wrong in this code?
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
break
The logic of your code is wrong. The else clause should be attached to the inner for loop, so it's only executed if the loop is exhausted without finding a divisor.
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
Also note that the outer loop only runs up to 29, since the upper boundary is not included in a range. The inner loop does not include i - 1, but that's totatlly fine, since any non-trivial divisor is less than i - 1.
The inner loop won't be entered at all for 2 and 3, since the range will be empty in these cases. This is fine as well, since the else clause will be immediately entered.
for i in range(2, 30):
prime = True
for j in range(2, i-1):
if ((i % j) == 0):
prime = False
# print(i, "is not a prime number")
break
# else:
# print(i, "is a prime number")
# break
if prime:
print(i, "is a prime number")
else :
print(i, "is not a prime number")
There are lot of online link to solve the prime number problem. To improve yourself search yourself and understand the. Hope this and this link help you a lot. Happy codding
It isn't working because the nested for declaration:
for i in range(2, 30):
for j in range(2, i-1):
Uses range(2, i-1) and until i is 4, range returns no value:
i = 2 --> range(2, 1) # No value
i = 3 --> range(2, 2) # No value
i = 4 --> range(2, 3) # 2
This is because the range function returns values from the first parameter (included) to the second parameter (not included).

Python prime listing repetition bug

Trying to create a program that lists the prime numbers in a set interval (has to be between 1 and 500), so user input isnt allowed. This is my code so far:
list=[]
for num in range(1, 500):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
list.append(str(num))
print(','.join(list))
However, when I run this code some of the primes are repeated multiple times in the list, making it much longer than it should be. How can i fix this? Thanks in advance for any help.
You only want to add the number to the list of primes after you've checked all the possible divisors. That means you only add it after the for loop has completed.
A good way to do this is with the optional else clause on for loops.
Loop statements may have an else clause; it is executed when the loop
terminates through exhaustion of the list (with for) or when the
condition becomes false (with while), but not when the loop is
terminated by a break statement.
You can improve this function by only checking the modulus of primes you've already found. Since all non-prime numbers have prime roots, you only need to check if a number is divisible by lesser primes to determine if it is a prime.
primes = []
for i in range(2, 501):
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
In the loop:
for i in range(2, num):
if (num % i) == 0:
break
else:
list.append(str(num))
you are appending the prime once for every i. The else should line up with the for:
for i in range(2, num):
if (num % i) == 0:
break
else: # note: different indentation!
list.append(str(num))
In python loops can have an else clause which is executed only if no break was executed inside the loop. They can be used to avoid boolean flags in a lot of cases.
So the code:
found = False
for x in iterator:
if predicate(x):
found = True
break
if not found:
# do default action
can be replaced by:
for x in iterator:
if predicate(x):
break
else:
#do default action
Make sure you are adding each only once.
The problem is that until you find a number i that divides num, num is added to the list. It is straightforward that you will have each prime in the list many times. In fact if n is prime, you will have n in the list n-2 times. You will also have all odd numbers in the list.
Only even numbers won't appear in the list, because the first number against which you are testing the divisibility is 2 and 2 divides all even numbers.
Without changing too much in your algorithm, you can introduce a flag isPrime that is set to True by default, and whenever you find i that divides num you set isPrime to True before breaking the loop. Your program becomes:
list=[]
for num in range(1, 500):
if num > 1:
isPrime=True
for i in range(2, num):
if (num % i) == 0:
isPrime = False
break
if isPrime:
list.append(str(num))
print(','.join(list))

Categories