[GIS] Counting number of vertices of object on vector layer PyQGIS

pyqgispythonqgis

First of all, I want to say that I know that similar issue was raised before, but it didn't provide satisfying solution.

I need to get the number of vertices of every object on vector line layer.
Basing on this article: https://joseguerreroa.wordpress.com/2014/07/28/contar-y-extraer-nodos-vertices-para-vectoriales-de-linea-o-poligono-mediante-pyqgis/

I did this code:

layer = qgis.utils.iface.activeLayer()
feat = layer.getFeatures()
for feature in feat:
    geom = feature.geometry()

n = 1
ver = geom.vertexAt(0)
points=[]

while(ver != QgsPoint(0,0)):
    n +=1
    points.append(ver)
    ver = geom.vertexAt(n)

print n

And as the result I get number of vertices, but only of the last object. I guess I'm missing one while loop on the layer (to get number for every object), am I right? But I don't know how it should look.

I know that there is 'Vertices counter" plugin, but it doesn't work (doesn't even start) in my case (QGIS 2.12, Win 8.1). And I need it to be done in Python.

By the way, don't you think guys, that it is ridiculously hard to get number of vertices while it is so easy to get to coordinates of every vertex?

EDIT:
@nwduncan ( @ArMoraer too) suggested fixing up an indentation, and it was good clue. I noticed that Python console need refreshment, because sometimes it can't handle indentations. Hope it will help other beginners. The final code is:

layer = qgis.utils.iface.activeLayer()
feat = layer.getFeatures()
for feature in feat:
    geom = feature.geometry()
    n   = 1
    ver = geom.vertexAt(0)
    points=[]

    while(ver != QgsPoint(0,0)):
        n +=1
        points.append(ver)
        ver=geom.vertexAt(n)

    print n

Best Answer

Indentation.

The first part of your code is correct, but the rest can be greatly simplified if you just want the number of vertices:

layer = qgis.utils.iface.activeLayer()
feat = layer.getFeatures()

for feature in feat:
    if feature.geometry().isMultipart(): # new part for multipolylines
        vertices = feature.geometry().asMultiPolyline()
        print [len(v) for v in vertices]
    else:
        vertices = feature.geometry().asPolyline()
        n = len(vertices)
        print n

If you also want the coordinates of the vertices, then you can write (polylines only):

layer = qgis.utils.iface.activeLayer()
feat = layer.getFeatures()

for feature in feat:
    vertices = feature.geometry().asPolyline()
    points = []

    for v in vertices:
        points.append(v)