[Tutor] Help With A Program
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Apr 3 03:54:34 EDT 2021
On 03/04/2021 04:11, Caleb Benz wrote:
> I am currently writing a program that takes an integer, n,
> from a user, and outputs all of the prime numbers up to
> and including n.
When you are trying to debug a program its often a
good idea to walk through the program writing down
the variable values as you go. Lets try that for
your program assuming a first input value of 1.
We'll look at n,x and result...
> def generatePrimes():
> n=int(input('Enter a number:'))
> integer_list=list(range(2,(n+1)))
> result=[2,3]
> x=1
At this [oint
n = 1, x = 1
result - [2,3]
> for i in range(2,(n+1> x=x+1
No
n = 1, x = 2, result = [2,3]
and i = 2
> if i==(((6*x)-1) or ((6*x)+1)):
This line doesn't do what you think it does,
lets plug in our values...
if 2 == (11 or 13):
'or' is a boolean operator so always returns True or False.
But things are really a lot more complicated than that unfortunately.
Python considers anything non-zero to be True. And the or
operator is lazy so it returns the first value that it
finds True (there could be many values) and does not
bother calculating the rest.
So in your case it calculates 11, sees it is True and
returns that value. The second part is only ever calculated
if the first part is zero. Which will never happen in
your code. So really we have
if 2 == 11
Which is false
> result.append(i)
> print(result)
So it prints [2,3]
Which is wrong because n was 1...
Let's try again with a value of n == 5
def generatePrimes():
n=int(input('Enter a number:'))
integer_list=list(range(2,(n+1)))
result=[2,3]
x=1
n = 5, x = 1, result = [2,3]
for i in range(2,(n+1)):
x=x+1
if i==(((6*x)-1) or ((6*x)+1)):
i = 2
n = 5, x = 2, result = [2,3]
if 2 == 11 is False
i = 3
n = 5, x = 3, result = [2,3]
if 3 == 17 is False
i=4
n = 5, x = 4, result = [2,3]
if 2 == 23 is False
i = 5
n = 5, x = 5, result = [2,3]
if 2 == 29 is False
That's the end of the for loop
result.append(i)
print(result)
result = [2,3]
I'm not sure how you think that function is
working out primes. Try working through
it line by line with other values. It isn't
working because your algorithm is broke.
You don't use integer_list anywhere.
x is the same value as i.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list