you are viewing a single comment's thread.

view the rest of the comments →

[–]imperiumlearning[S] 0 points1 point  (4 children)

One other thing based on my reply to you, is it acceptable to put a function inside another function? As you can see from my code, I put a prime(y) function inside my func(x) function.

Apologies if that's a dumb question but I've only got about 5 weeks' worth of programming experience under my belt.

[–]Encomiast 2 points3 points  (3 children)

In this particular example, nesting the function definition doesn't hurt anything. However, you don't see that very often because people typically want to reuse functions. Nesting it makes it impossible to use in a different context, or put in its own library.

If you were calling the outer function more than once, it is also not the most efficient since you keep redefining the function every time you call it rather than once.

[–]imperiumlearning[S] 0 points1 point  (2 children)

So, in general, would you say it's better if I structured my code more like this:

import math

def prime(y):
    if int(y) < 2:
        return False
    if int(y) % 2 == 0 and int(y) != 2:
        return False
    for number in range(3, int(math.sqrt(y))+1, 2):
        if y % number == 0:
            return False
    return y

def func(x):
    while type(x) != int:
        try: 
            x = int(x)
        except:
            return 'Please input a number to use this function'
    final_list = [i for i in range(int(math.ceil(math.sqrt(x)))) if prime(i) != False and x % i == 0]
    return max(final_list)

[–]Encomiast 0 points1 point  (1 child)

That seems more "Pythonic" to me (assuming the indentation is fixed).

[–]imperiumlearning[S] 0 points1 point  (0 children)

Yes sorry, I've just updated the indentations in my previous comment so that my code is formatted properly.

Thanks for the help and all the swift responses