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

Discussion Overview

The discussion revolves around understanding a nested for loop in Python, specifically in the context of identifying prime numbers. Participants explore the behavior of the code during a dry run and suggest modifications to improve the implementation.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant presents a code snippet intended to find prime numbers and notes an issue with the output for the number 2 during a dry run.
  • Another participant suggests adding ##num +1## in the second range to address the issue with the empty range when num equals 2.
  • A later reply clarifies that the dry run failed because the range for num = 2 is (2,2), which is empty, leading to an immediate skip of the loop.
  • One participant proposes an alternative approach by moving the inner loop to a function to eliminate the nested loop structure.
  • Another participant suggests checking for divisors only up to the square root of the number to optimize the prime-checking process.
  • A different participant shares a more complex script that finds and counts prime numbers up to a specified maximum, using a list of known primes for efficiency.

Areas of Agreement / Disagreement

Participants generally agree on the need to address the empty range issue and explore alternative methods for finding prime numbers. However, there are multiple competing views on the best approach to optimize the prime-checking process, and the discussion remains unresolved regarding the most efficient implementation.

Contextual Notes

Some limitations include the assumption that the reader understands Python syntax and the implications of nested loops. The discussion does not resolve the optimal method for prime checking or the best practices for structuring such algorithms.

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
5K
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 16 ·
Replies
16
Views
2K