Search code examples
pythonfunctiondefined

Python "not defined" in lottery


Im learning for a book "Intr. Python 2.6.6" and I have the this error in a example

line 12, in <module>
aux=num_ele
NameError: name "num_ele" is not defined

But I do not understand what the problem

# -*- coding:utf-8 *-*

import random
import os

def combinacion(num_ele, total_num, repetir=False, ordenar_resultado=True):
    elementos=[]
    if num_ele>total_num and not repetir:
        print ("No puedes sacar mas valores de los que ya tienes!")
        return

aux=num_ele

while aux>0:
    numero = int(random.uniform(1,total_num))
    if repetir:
        elementos.append(numero)
        aux=aux-1
    else:
        if elementos.count(numero)==0:
            elementos.append(numero)
            aux=aux-1

if ordenar_resultado:
    elementos.sort()
print (elementos)

def menu():
    print ("""
    Menu Principal

    Este programa genera combinaciones de juegos de azar. elige el juegos
    que mas te guste.

    1) Loteria Primitiva
    2) Euromillones
    9) Salir 
    """)

    opcion = input("")
    return opcion

def aplicacion():
    os.system(cls)
    opcion = ("")
    while opcion!=("9"):
        opcion = menu()
        if opcion ==("1"):
            print ("")
            print ("Combinacion para loteria primitiva: ")
            combinacion(6,49)
            print ("")

        if opcion == ("2"):
            print ("")
            print ("Euromillones")
            print ("Combinacion ganadora: ")
            combinacion(5,50)
            print ("Estrellas: ")
            combinacion(2,9)
            print ("")

aplicacion()

thank you for your time.


Solution

  • I assume you meant to have aux=num_ele and the code onwards inside your combination function:

    # -*- coding:utf-8 *-*
    import random
    import os
    
    def combinacion(num_ele, total_num, repetir=False, ordenar_resultado=True):
        elementos=[]
        if num_ele>total_num and not repetir:
            print ("No puedes sacar mas valores de los que ya tienes!")
            return
        aux=num_ele
    
        while aux>0:
          numero = int(random.uniform(1,total_num))
          if repetir:
            elementos.append(numero)
            aux=aux-1
          else:
            if elementos.count(numero)==0:
              elementos.append(numero)
              aux=aux-1
          if ordenar_resultado:
            elementos.sort()
          print (elementos)
    
    def menu():
        print ("""
        Menu Principal
    
        Este programa genera combinaciones de juegos de azar. elige el juegos
        que mas te guste.
    
        1) Loteria Primitiva
        2) Euromillones
        9) Salir 
        """)
    

    The indentation level of your aux=num_ele and the following code puts it outside combination's scope.