Pass the value of a variable from one function to another function in Python

0

I am starting my studies in Python and I need to make this code for my class.

Basically it consists in the registration of the workers of a company to calculate their salary / salary, applying some discounts and bonuses / incentives.

In option 4 of the menu, I must print all registered Rut / IDs with their respective final salary.

I need to put SueldoDescontado that is in the function Def Calcular_Sueldo() in of the function Def Liquidaciones_Rut

They told me to define it as Class and add it to the List [] register.

PS: if I define SueldoDescontado as global it prints the same value for all the Rut / ID.

I hope someone can help me.

Here's my PasteBin code

Lista = [] #<----- Array


Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
        'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre',
        'ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO', 'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']

Rank =  ['novato', 'experto', 'supervisor', 'administrativo',
         'Novato', 'Experto', 'Supervisor', 'Administrativo',
         'NOVATO', 'EXPERTO', 'SUPERVISOR', 'ADMINISTRATIVO']

SistemaSalud = ['a', 'b', 'c',
                'A', 'B', 'C']



class Trabajador: #Class <----
    Mes = '' 
    Año = 0
    Rut = ''
    Nombre = ''
    Categoria = ''
    DiasOff = 0
    AFP = ''
    SSalud = ''
    SueldoBruto = 0
    SueldoDescontado = 0

def Ingresar_Datos():
    Elementos = int(input('Ingrese cantidad de trabajadores que desea agregar: \n')) #<--- How many people do you want to add
    for Trabajadores in range(Elementos):
        dato = Trabajador()

        while True:
            Nombre = input("Ingrese un nombre: ") #<--- Name
            if vacio(Nombre):
                print ('No puede dejar el campo vacio')
            else:
                dato.Nombre = Nombre
                break

        while True:
            Rut = input('Ingrese Rut: ') # <---- ID Number
            if vacio(Rut):
                print ('No puede dejar el campo vacio')
            else:
                dato.Rut = Rut
                break

        while True:
            Mes = input('Ingrese mes: ') # <---- Month when start at work
            if vacio(Mes):
                print ('No puede dejar el campo vacio')
            elif Mes in Mess:
                dato.Mes = Mes
                break
            else:
                print('Mes invalido')


        while True:
            Año = input('Ingrese año: ') # <---- Year when start at work
            if vacio(Año):
                print ('No puede dejar el campo vacio')
            else:
                dato.Año = Año
                break

        while True:
            AFP = input('Ingrese AFP: ') # <---- NVM just a company name can be put here, not relevant
            if vacio(AFP):
                print ('No puede dejar el campo vacio')
            else:
                dato.AFP = AFP
                break

        while True:
            SSalud = input('Sistema de salud A B o C\nDigite opcion: ') # <---- System Health, Here is A, B or C, This make a discount%
            if vacio(SSalud):
                print ('No puede dejar el campo vacio')
            elif SSalud in SistemaSalud:
                dato.SSalud = SSalud
                break
            else:
                print ('::::::::::::::::::::ERROR Opcion Invalida::::::::::::::::::::')


        while True:
            Categoria = input('Categoria; Novato, Supervisor, Experto o Administrativo: ') # <---- Worker rank, Expert have a 2xBonus for 0 days off
            if vacio(Categoria):
                print ('No puede dejar el campo vacio')
            elif Categoria in Rank:
                dato.Categoria = Categoria
                break
            else:
                print ('::::::::::::::::::::ERROR Categoria invalida::::::::::::::::::::')


        while True:
                DiasOff = input('Ingrese cantidad de dias de ausencia: ') #<------ Days of absence, 0 days have a bonus$
                if dato.DiasOff < 0 or dato.DiasOff > 30:
                    print ('Dias de ausencia no puede ser negativo o mayor a 30')
                else:
                    dato.DiasOff = DiasOff
                    break


        while True:
            try:
                SueldoBruto = int(input('Ingrese sueldo bruto: ')) # <------- Gross Salary
                if dato.SueldoBruto < 0:
                    print ('El monto del sueldo bruto no puede ser negativo')
                else:
                    dato.SueldoBruto = SueldoBruto
                    break
            except ValueError:
                print('error')

        print("------------------------------------------------")
        Lista.append(dato)


def vacio(x):
    if x and x.strip():
        return False
    return True 


def Calcular_Sueldo():
    Bono = 50000 #<-------- Bonus for 0 Days of absence
    for Trabajadores in Lista:
        print('Nombre trabajador: ',Trabajadores.Nombre,'\n')

        if Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('Experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('EXPERTO'):
            SueldoBono = Trabajadores.SueldoBruto + Bono*2 #<-------- There is if 0 days absence and rank experto, 2xBonus
            print('Sueldo bruto + Bono (Experto) por 0 faltas: ',SueldoBono)


        elif Trabajadores.DiasOff == '0': #<-------- Bonus for 0 Days of absence, nvm about rank here
            SueldoBono = Trabajadores.SueldoBruto + Bono
            print('Sueldo bruto + Bono por 0 faltas: ',SueldoBono)


        else:
            SueldoBono = Trabajadores.SueldoBruto #<-------- No bonus for days absence
            print('Tiene faltas/ausencia, no tiene derecho a Bono: ',SueldoBono)


        DctoAFP = SueldoBono - (SueldoBono * 0.1) #<-------- This makes a 10% descuento for AFP, the nvm'company name
        print('Sueldo bruto + Recorte del 10% por AFP ',Trabajadores.AFP,': ',DctoAFP)



        if Trabajadores.SSalud == 'a' or Trabajadores.SSalud == 'A': #<-------- If Sistem Health is A, make a 5,7% discount
            DctoSalud = (DctoAFP/100) * 5.7
            print('Recorte del sistema de salud A: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)





        if Trabajadores.SSalud == 'b' or Trabajadores.SSalud == 'B': #<-------- If Sistem Health is B, make a 6.1% discount
            DctoSalud = (DctoAFP/100) * 6.1
            print('Recorte del sistema de salud B: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)





        if Trabajadores.SSalud == 'c' or Trabajadores.SSalud == 'C': #<-------- If Sistem Health is C, make a 6.5% discount
            DctoSalud = (DctoAFP/100) * 6.5
            print('Recorte del sistema de salud C: ',DctoSalud)
            SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
            print('Total a pagar: ',SueldoDescontado)




    print('--------------------------------------')

def Liquidaciones_Rut(): #<------- Here i need to print all the ID's number's with his Final Salary (SueldoDescontado)
    for Trabajadores in Lista:
        print('Rut: ',Trabajadores.Rut,'Total a pagar: $',SueldoDescontado) #<----- To here --------- !"#$"!#%!"#%!#"%"#$%$"#----------




def Listar_Empleados(): #<------------------ Here just print the names of all workers
    for Trabajadores in Lista:
        print("Empleados registrados: ", Trabajadores.Nombre)






opcion = 7
while (opcion != 6):
    print(' ========== Administracion NovaVision ========== ')
    print('Menu')
    print('1.- Ingresar Datos') #<-------------------------- Enter Data
    print('2.- Calcular Sueldo') #<-------------------------- Calculate Salary
    print('3.- Listar Empleados') #<----------------------------- List employees (by his name)
    print('4.- Mostrar Liquidaciones por RUT') # <--------- List numbers ID with his Respective Salary
    print('5.- Salir')
    opcion = int(input('Ingrese su opcion: '))
    if (opcion == 1):
        Ingresar_Datos() 
    elif (opcion == 2):
        Calcular_Sueldo()
    elif (opcion == 3):
       Listar_Empleados()
    elif (opcion == 4):
        Liquidaciones_Rut()
    elif (opcion == 5):
        print('Saliendo .. ')
    else:
        print ('Opcion no valida')
    
asked by iFabio 08.07.2017 в 07:24
source

1 answer

0

Fabio, you have done a great job within the scope of your application and I really wonder why you have not been able to do it, if what you need is something that you did everywhere in your script less in SueldoDescontado .

Either way, the answer is as follows:

The only thing that you have been missing is to save the variable SueldoDescontado in each object Trabajadores of the list that you pass when you invoke the function Calcular_Sueldo() . I made the comment at the beginning, because you have done it throughout your script, but for some reason in this part you have forgotten it. It would have to look something like this: (I will only put the parts of the code that need changes)

1.Changes in the function Calcular_Sueldo()

 if Trabajadores.SSalud == 'a' or Trabajadores.SSalud == 'A': 
        DctoSalud = (DctoAFP/100) * 5.7
        print('Recorte del sistema de salud A: ',DctoSalud)
        Trabajadores.SueldoDescontado = DctoAFP - DctoSalud
        #SueldoDescontado = DctoAFP - DctoSalud 
        print('Total a pagar: ',Trabajadores.SueldoDescontado)

 if Trabajadores.SSalud == 'b' or Trabajadores.SSalud == 'B': 
        DctoSalud = (DctoAFP/100) * 6.1
        print('Recorte del sistema de salud B: ',DctoSalud)
        Trabajadores.SueldoDescontado = DctoAFP - DctoSalud
        #SueldoDescontado = DctoAFP - DctoSalud 
        print('Total a pagar: ',Trabajadores.SueldoDescontado)

 if Trabajadores.SSalud == 'c' or Trabajadores.SSalud == 'C': 
        DctoSalud = (DctoAFP/100) * 6.5
        print('Recorte del sistema de salud C: ',DctoSalud)
        Trabajadores.SueldoDescontado = DctoAFP - DctoSalud
        #SueldoDescontado = DctoAFP - DctoSalud 
        print('Total a pagar: ',Trabajadores.SueldoDescontado)

As you can see, we refer to the object Trabajadores and its property SueldoDescontado , instead of just doing it to a variable like you were doing before (see commented line). In the print function that follows we no longer refer only to the variable (as you did before) but to the object with its property.

  • Changes in the function Liquidaciones_Rut()

    def Liquidaciones_Rut(): 
        for Trabajadores in Lista:
            print('Rut: ',Trabajadores.Rut,'Total a pagar: $',Trabajadores.SueldoDescontado) 
    
  • In this case it is even more evident. Instead of trying to call a variable SueldoDescontado that has not been declared anywhere, we call the object that is being iterated and get its property SueldoDescontado that we previously saved in the function Calcular_Sueldo()

    That should solve your problem. Greetings.

        
    answered by 08.07.2017 / 16:52
    source