Python Forum
Return result from multiple iteration condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return result from multiple iteration condition
#1
Hi people, the codes print out the desire output but I couldn't return the value to the function. Eg. integer = 90, next prime number is 97 but the return value is 95. Appreciate your help. Thanks


print('This program displays the next prime number of the entered integer')

def f_nextPrime(integer):
    if integer <= 1:
        print('Enter integer greater than 1')

    if integer == 2:
        next_prime = 3
        return next_prime
        
    if integer % 2 == 0:
        while True:
            for i in range (2 , integer):
                while integer % i == 0:
                    integer += 1
                    print('1 : ' , integer , i)
    
    if integer % 2 != 0:
        integer += 1
        while True:
            for i in range (2 , integer):
                while integer % i == 0:
                    integer += 1
                    print('2 : ', integer , i)

def main():
    integer = 90
    print(f_nextPrime(integer))
    
main()
Reply
#2
You are doing the right things, but you are doing them out of order.

The first two if clauses are fine, but you should have a return statement for the first one, giving a dummy value (None or -1).

Then you want to check the input for being odd. If it is, add 2, otherwise add 1. This gets you to the next odd number.

Then have the while loop. In the while loop have the for loop that checks for the number being prime (you only need to check up to int(sqrt(integer)) + 1, not all the way up to integer). If the for loop says the number is not prime, add 2 (to get to the next odd number). If it is prime, break out of the loop and return it.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hi ichabod801, thanks for the reply. The program is to find the next prime number. Meaning if I entered 89 (which is a prime number), it should return 97 as the next prime number. While if I entered 90 (which is not a prime number), it should also return 97 as the next prime number.

The loops actually have got the correct value but I don't know how to return it to the function as all the return values at different indent never seem to return the final value of the iteration.
Reply
#4
That's because your while loops are infinite loops. They find the answer and keep on going. You should do your loops the way I explained.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiple return from function Grimmar 7 3,598 Mar-22-2021, 09:20 PM
Last Post: Grimmar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020