Python indentation issue?

I am new to python. This is my first experience with classes in python. When I try to run this script, I get

IndentationError: indentation block expected

What is wrong with that?

import random class Individual: alleles = (0,1) length = 5 string = "" def __init__(self): #some constructor work, here. def evaluate(self): #some stuff here. def mutate(self, gene): #mutate the given gene. def onePointCrossover(self, partner): #at some random point, crossover. def twoPointCrossover(self, partner): #at two random(?) points, crossover. class World: def __init__(self): #stuff. def buildPopulation(self): #stuff. for individual in self.population(): for i in range(0, individual.length): print random.random() def display(self): #print some output stuff. if __name__ == '__main__': print "hi there" 
+4
source share
8 answers

All of these methods are only comments.

To fix it, for example, do it

 def twoPointCrossover(self, partner): #at two random(?) points, crossover. pass 

Comments are not considered compilation statements, so you have a bunch of empty blocks. This is why it gives you an indent error.

+11
source

If you are using something that ends with : waiting for a pending block, and you have nothing you want to post there (other than a comment), you need to use pass .

eg.

 def doNothing(self): pass 
+4
source

When you simply highlight your classes and get many methods that do nothing, you need to insert a pass statement to indicate that nothing is happening.

Same:

 class Individual: alleles = (0,1) length = 5 string = "" def __init__(self): #some constructor work, here. pass def evaluate(self): #some stuff here. pass ... 

An unexpected indent message is that python is looking for an indented instruction to follow the method definition.

+3
source

Edit:

 class World: def __init__(self): #stuff. 

To:

 class World: def __init__(self): #stuff pass 

etc. for all methods.

+2
source

If you are not shortening your code for this post, you will need a pass after all those functions that have no code.

+2
source
 def __init__(self): #stuff. 

This does not look right at first glance. Try changing it to this:

 def __init__(self): #stuff. pass 
+2
source

Double check the tabs and spaces in the whole code, make sure you don't mix them. A line with several spaces may coincide with a line with one tab.

+2
source

Others have considered pass , so I’ll just add that for beginners, Python programmers may get a little used to the importance of spaces.

Until you get used to it, you may want to get in the habit of converting tabs to spaces or spaces to bookmarks when saving a file. Personally, I prefer tabs, because it’s easier to tell the difference if it is disabled by one (especially at the beginning / end of a nested block).

0
source

Source: https://habr.com/ru/post/1299491/


All Articles