Python Nested for loop in python, understanding with dry run?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Loop Python
AI Thread Summary
The discussion centers on a Python code snippet designed to find and print prime numbers up to a given integer n. The initial code runs correctly, outputting 2, 3, and 5 for n=5. However, a dry run reveals an issue with the range for num=2, which is empty (2,2), causing the loop to skip the evaluation of 2 as a prime number. The suggestion is made to adjust the inner loop's range to include num+1, which would incorrectly conclude that 2 is not prime. An alternative approach is proposed, introducing a function to check for primality, which simplifies the code and avoids nested loops. Additionally, a more efficient method is shared that checks for divisors only up to the square root of the number, enhancing performance when finding primes up to a larger maximum number.
shivajikobardan
Messages
637
Reaction score
54
Here is the code that I am talking about-:
Code:
n=int(input("Enter a number"))
for num in range(2,n+1):
    for i in range(2,num):
        if(num%i==0):
            break
    else:
        print(num,end="")

If I give n=5 output should be 2,3,5.

Here is my dry run. Everything is fine except for 2 where I am not getting 2 as output. What has gone wrong here? I don't understand what is gone wrong here?
 
Technology news on Phys.org
You need ##num +1## in the second range.
 
PeroK said:
You need ##num +1## in the second range.
I don't think the question is "what is wrong with my program", but it is "what went wrong with the dry run (see picture)". The program runs fine and outputs 2,3 and 5.
The dry run went wrong because the range for num =2 is (2,2). This is an empty range. A for loop for an empty range doesn't run the first part at all, and will immediately go to the else: (or skip the entire thing if there is no else:).
If there was num+1 in the second range, the range would be (2,3), the 2%2 would be tried and there would be the wrong conclusion that 2 is not prime.
 
  • Like
Likes PeroK
Yes, I just saw the empty loop and assumed that was the problem!
 
I would also eliminate the nested for loop by moving the inner loop in a function
Python:
def isprime(num):
    for divisor in range (2,num):
        if (num % divisor) == 0:
            return False
    return True

n=int(input("Enter a number"))
for num in range(2,n+1):
    if isprime(num):
        print(num,end=" ")
I don't really like nested loops, unless it's something like rows and columns.
 
  • Like
Likes PeroK
I would only check for divisors up to the square root of the number!
 
@shivajikobardan here's my basic python script to find prime numbers:

Python:
# Find, count and print all primes up to max_num
#
primes = [2, 3, 5, 7, 11, 13, 17, 19]
#
max_num = 1000
prime_flag = False
#
for n in range(23, max_num+1, 2):
    sqrt_n = n**0.5
    for p in primes:
        if n % p == 0:
#            print(f"{n} is not prime")
            prime_flag = False
            break
#
# Only search for primes less than or equal to the square root of n
        if p > sqrt_n:
#            print(f"{n} is prime")
            prime_flag = True
            break
#
    if prime_flag:
        primes.append(n)
#
print(primes)
print(len(primes))
 
Back
Top