-1

if a vowel is found, it takes the position where it is and the sum if the position is even or odd


def conteo_vocales(cadena: str)->int:
    
    numero_vocales =  0 
    
    longitud = len(cadena)
    
    i = 0 
    
    pares = 0
    
    impares = 0 
    while i<longitud :
        
        if cadena[i] == "a" or cadena[i] == "e"or cadena[i] == "i"or cadena[i] == "o"or cadena[i] == "u":
            
            numero_vocales += 1 
            if i %2 == 0 :
                pares +=1
            else:
                impares +=1
        i += 1 
    
    
    if impares > pares:
        rta = 1
    elif pares < impares:
        rta = 2 
    elif pares == impares:
        rta = 0 
    return rta

    
h = conteo_vocales("hormigas")
print(h)

then the console bounces "local variable 'rta' referenced before assignment"

arp5
  • 169
  • 10
  • Does this answer your question? [Python 3: UnboundLocalError: local variable referenced before assignment](https://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment) – Suraj Rao Oct 23 '21 at 17:05

2 Answers2

0

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. If you don't want it ot be local you must declare it as global. you also have an issue in the comparision operator. if and else if are the same

rta =0
def conteo_vocales(cadena):
    global rta
    numero_vocales =  0
    
    longitud = len(cadena)
    
    i = 0 
    
    pares = 0
    
    impares = 0 
    while i<longitud :
        
        if cadena[i] == "a" or cadena[i] == "e"or cadena[i] == "i"or cadena[i] == "o"or cadena[i] == "u":
            
            numero_vocales += 1 
            if i %2 == 0 :
                pares +=1
            else:
                impares +=1
        i += 1 
    
    if impares > pares:
        rta = 1
    elif impares < pares:
        rta = 2 
    elif pares == impares:
        rta = 0 
    return rta

    
h = conteo_vocales("hormigas")
print(h)
arp5
  • 169
  • 10
0

I think the indentation of your code in the question is probably wrong. Also, this could be simplified:

def conteo_vocales(s):
    oe = [0,0]
    for i, c in enumerate(s):
        if c in 'aeiou':
            oe[i%2] += 1
    return 1 if oe[1] > oe[0] else 2 if oe[0] > oe[1] else 0

print(conteo_vocales("hormigas"))

Note: I have ignored numero_vocales because it doesn't appear to be used