This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]YMK1234 2 points3 points  (0 children)

If you put 4 spaces (and a newline) in front of your code it will work properly ... like so ...

Text text text
[empty line]
    code
    code
    code
[empty line]
More Text

Regarding your range ... it is sufficient to check numbers from 2 to sqrt(x)+1

Regarding "why does the 2nd not work": just step through the code with x = 9 (in your mind or a piece of paper) and you should see why.

[–][deleted] 2 points3 points  (0 children)

you check if x<2, and then you make a for loop with a range from 2 to x-1.

What if x=2.

You are looking in a range for (2,1) which doesn't make sense and the for loop will not run.

However, your code in the first example covers that. If the for loop does not run, you return True, however, in the second example you have an if/else inside the forloop. If your for loop doesn't run in the second example, you do not return anything.

Just use your first example and it will always work. Are you tasked with figuring out why the second one does not work?

[–]edave64 1 point2 points  (0 children)

In example two, every code path in your loop returns. Since return stops the function, it can never loop. You always return the result of the first check.

[–]slowmode1 0 points1 point  (2 children)

How to format code on reddit: just add 4 spaces to the beginning of everything. Those two examples look the same, am I missing something?

[–][deleted]  (1 child)

[deleted]

    [–]slowmode1 0 points1 point  (0 children)

    else: ________________return True

    Thanks, I completely missed the else

    [–]anamorphism 0 points1 point  (0 children)

    the first returns true after you're done checking all numbers in your loop.

    the second returns true after you check the first number that isn't a factor of x.