Anon
Anon

Reputation: 35

Having a problem with displaying the output for the function

I've written out my function where it gets an input from a user and decides if its prime or not. If it prime, it should just return the value the user entered. If not, just return 0. When i take my for loop out of the function, it works fine but when i put it inside of a function, it works but doesn't display the same thing.

def is_prime(): 
p = int(input("enter a number: "))
for i in range(2, int(p / 2)):
    if p % i == 0:
        print(0)
        break
else:
    print(p)

is_prime()

enter a number: 5
5
but it also does the same thing when i enter a non-prime number
enter a number: 4
4
When its supposed to return 0.

Upvotes: 0

Views: 23

Answers (1)

Michael Butscher
Michael Butscher

Reputation: 10959

You must take into account that the end value of range is excluded, therefore add 1 to it:

def is_prime(): 
    p = int(input("enter a number: "))
    for i in range(2, int(p / 2) + 1):
        if p % i == 0:
            print(0)
            break
    else:
        print(p)


is_prime()

Tests:

enter a number: 4
0

enter a number: 5
5

enter a number: 15
0

Upvotes: 1

Related Questions