Nested for loop in python, understanding with dry run?

  • Context: Python 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Loop Python
Click For Summary
SUMMARY

The discussion focuses on the implementation of a nested for loop in Python to identify prime numbers. The original code fails to output '2' due to an empty range in the inner loop when num equals 2. The solution involves adjusting the range to include num + 1, ensuring that the condition for checking primality is met. An alternative approach using a function to encapsulate the prime-checking logic is also suggested, which improves code readability and efficiency.

PREREQUISITES
  • Understanding of Python programming syntax
  • Familiarity with for loops and range function in Python
  • Basic knowledge of prime number identification algorithms
  • Experience with function definition and usage in Python
NEXT STEPS
  • Learn about Python's range function and its behavior with different parameters
  • Explore the implementation of prime number algorithms, including the Sieve of Eratosthenes
  • Study the concept of time complexity in algorithms, particularly for nested loops
  • Investigate Python's built-in functions and libraries for mathematical computations
USEFUL FOR

Python developers, educators teaching programming concepts, and anyone interested in optimizing algorithms for prime number generation.

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   Reactions: 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   Reactions: 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))
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
1
Views
2K
  • · Replies 34 ·
2
Replies
34
Views
5K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 28 ·
Replies
28
Views
4K
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 16 ·
Replies
16
Views
2K