Python tutorial help


#1

Hello!

I have a problem with one of the Python tutorial. I wrote a programme for checking if a number is prime or not. I used a range from 2 to x - 1, where x is the read number and it tells me that I have an error. Could somebody please tell me what I am doing wrong? Here is the code:

def is_prime(x):
      if(x > 1):
             for n in range(2, x - 1):
                    if x % n == 0:
                             return False
                    else:
          	            return True
      else:
      	   return False

Thank you! :smile:


#2

by default, a function returns none at the end of the function. If we want to return something else at the end of the function, we can use the return keyword. Thus, when a return keyword is reached, the function will end

so for x=9, in the first iteration of the loop the if condition is:

9 % 2 == 0

which evaluates to false, so else clause is executed, return True means a return keyword is reached, thus the function ends

see a problem with this behaviour?


#3

Oh! Wait! I’m so sorry! I intended to put the first else with the for. When I copied the code, it didn’t also take my tabs and spaces, so I had to put them.


#4

you have to use format to make indent show:

what error message do you get then?


#5

File “python”, line 3
for n in range(2, x - 1):
^
IndentationError: unindent does not match any outer indentation level


#6

can you post your code with format like explained in this topic:

i can’t solve an indent issue without being able to see the indent, if you prefer you can also post a repl.it


#7
def is_prime(x):
    if(x > 1):
          for n in range(2, x - 1):
                 if x % n == 0:
                      return False
          else:
                 return True
    else:
      	return False

Is that ok? :slightly_smiling_face:


#8

i ran your code here:

https://repl.it/@stetim94/DarkgreyPoliticalHeron

and its fine. Maybe re-indent the whole thing just to be sure? The editor sometimes has bit of indent issue


#9

ok. Thank you for helping me! :smiley:


#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.