Nested for loop in python, understanding with dry run?

  • Context: Python 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    Loop Python
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
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?
 
Physics news on Phys.org
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
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
@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))