Nested for loop in python, understanding with dry run?

  • Python
  • Thread starter shivajikobardan
  • Start date
  • Tags
    Loop Python
In summary: Output:In summary, The code that I am talking about-n=int(input("Enter a number"))for num in range(2,n+1):if isprime(num):print(num,end=" ")
  • #1
shivajikobardan
674
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
  • #2
You need ##num +1## in the second range.
 
  • #3
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
  • #4
Yes, I just saw the empty loop and assumed that was the problem!
 
  • #5
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
  • #6
I would only check for divisors up to the square root of the number!
 
  • #7
@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))
 

FAQ: Nested for loop in python, understanding with dry run?

What is a nested for loop in python?

A nested for loop in python is a loop within a loop. This means that there is an outer loop that runs multiple times and within that loop, there is an inner loop that also runs multiple times. This allows for more complex iterations and is commonly used when working with multi-dimensional data.

How do you write a nested for loop in python?

To write a nested for loop in python, you start by writing the outer loop, followed by the inner loop indented inside the outer loop. The inner loop will run completely for each iteration of the outer loop. It is important to pay attention to the indentation as it determines which code is part of the outer loop and which is part of the inner loop.

What is the purpose of a nested for loop in python?

The purpose of a nested for loop in python is to iterate through multi-dimensional data or to perform repetitive tasks that require multiple levels of iteration. It allows for more complex logic and can save time and effort when working with large datasets or performing calculations.

How do you debug a nested for loop in python?

To debug a nested for loop in python, you can use the print() function to output the values of the variables used in the loop. This will help you track the progress of the loop and identify any errors or unexpected behavior. Another helpful technique is using a dry run, where you manually trace through the code to see how it executes.

What are some common mistakes to avoid when using nested for loops in python?

Some common mistakes to avoid when using nested for loops in python include using the wrong variable names, forgetting to indent the inner loop, and creating an infinite loop. It is also important to make sure the logic of your loops is correct and to avoid unnecessary or redundant loops. It is helpful to test and debug your code as you go to catch any errors early on.

Similar threads

Replies
5
Views
1K
Replies
9
Views
2K
Replies
16
Views
2K
Replies
10
Views
1K
Replies
3
Views
1K
Replies
1
Views
2K
Back
Top