Cur123
Cur123

Reputation: 89

Python output printing more than once and function giving parameter not identified error

I know this is pretty basic, but I am kind of stuck in a minor step. Noob to python, please excuse my ignorance. Question is to generate all prime numbers strictly between 2 random user input numbers (which means first and 2nd numbers not included). Also, if there are no prime numbers between the 2 numbers, "No Primes" output should be printed. My code:

Firstno=int(input("number1: "))
Secondno = int(input("number2: "))
for num in range(Firstno+1,Secondno -1):
  if num>1:
    for i in range (2,num):
      if (num%i) == 0:
        break 
      else:
        print(num)

This gives part of desired output, but "No primes" is not displayed. If I include print("No primes") in place of break statement and test with numbers 23 and 29, "No Primes" output is repeated twice. I also tried defining a function(with my little knowledge)

def is_prime(n):
  for i in range(x,n):
    if (n%i) == 0:
      return "No Primes"
  return True

Firstno=int(input("number1: "))
Secondno = int(input("number2: "))

for num in range(Firstno+1,Secondno -1):
  if is_prime(num):
    print(num)

Which I know is not right..because x is not defined. Please provide your suggestions on improving my code to get the desired output.

Upvotes: 0

Views: 585

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22410

You Basically need to remove the -1 from the line for num in range(Firstno+1,Secondno -1): to understand why look at code for inclusive range: for num in range(Firstno,Secondno+1):

Here is your first attempt code tidied up a little:

lower_boundry = int(input("Enter the lower boundry number: "))
upper_boundry = int(input("Enter the upper boundry number: "))

print("Prime numbers between", lower_boundry , "and", upper_boundry , "exclusive are:")

primes_found = []

for num in range(lower_boundry + 1, upper_boundry):
  if num > 1:
    for i in range(2,num):
      if (num % i) == 0:
        break
    else:
      primes_found.append(num)

if len(primes_found) > 0:
  print(primes_found)
else:
  print("No Primes")

Example Usage with Primes in between:

Enter the lower boundry number:  2
Enter the upper boundry number:  6
Prime numbers between 2 and 6 exclusive are:
[3, 5]

Example Usage with No Primes in between:

Enter the lower boundry number:  2
Enter the upper boundry number:  3
Prime numbers between 2 and 3 exclusive are:
No Primes

Try the above code here!

Upvotes: 1

Related Questions