Good afternoon! I'm a beginner in coding and i'm trying to do an exercise done for Python.
Building a nested While Loop, i'm with a bug in my little he last line of the code says elif continua == "N"or "n": i = -1 and it should exit all the while loop (the nested and the first one), since i=-1 and the condition for the while loop to work in this code is i > 0 (or at least this is my purpose doing this line of coding.). But all of the sudden the loop starts again and i dont know why.
Can someone help me to get out of this loop?
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua == "S"or "s":
b=0
valorTotal = 0.00
Audiencia = True
listadevalores = []
i=0
elif continua == "N"or "n":
i = -1
There were several errors in your code.
missing : at the end of if or elif statemennts
several incorrect intendations (maybe a formating issue while copy paste)
You cannot chain bool checks lile continua == "N" or "n" use continua == 'n' or continua == 'N' or in this case even better continua.lower() == 'n'
You are searching for break. Here is a working version of your code:
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True:
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False:
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
b=0
valorTotal = 0.0
Audiencia = True
listadevalores = []
i=0
elif continua.lower() == "n":
break
The flow of your code is a bit hard to read. Especially it is difficult to understand what your i,a,b variables are doing. Here is a second version which showes how to make your code a bit easier to understand.
def floatInput(input_str):
number = None
while not number:
try:
number = float(input (input_str))
except:
print('not a float number in Portuguese')
return number
while True:
a = int(floatInput("Digite a quantidade de itens de audiência que serão calculados: "))
listadevalores = []
for i in range(a):
v = floatInput("Insira os valores: ")
listadevalores.append(v)
mean = sum(listadevalores) / len(listadevalores)
if sorted(listadevalores) == listadevalores:
print ("Audiência sempre crescente. Média de audiência: ", (mean))
else:
print ("Audiência nem sempre crescente. Média de audiência: ",(mean))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
continue
break
Here is some explanation to the improved parts.
Inputs
The input may be not a number although it is needed. This might create crashes. The exception for strings that cannot be parsed are handled by try: ... except: The second while loop is moved in a seperate function and out of the main flow to make it easier to read. Also it now can be called several times without the need for reapeating code. The while loop is self terminating when number gets a valid value.
Variabels
The meaning of i,a and b are not directly self explanatory. Also they are set at different positions in the code. You already have all information you need in the list.
Ascending lists by definition does not change when they get sorted. We can use this trick to check if the sorted list is the original list sorted(listadevalores) == listadevalores. So we don't need to work on the list elements.
The mean value can be calculated by dividing the sum of all list elements, using the build in sum by the lengt of the list sum(listadevalores) / len(listadevalores).
It seems that you have wrong indentation in question. Please fix this.
Also, it may help you:
create variable that tells your loops to proceed and set it to False when you need to stop the loops. An example:
loop = True
while your_condition and loop:
// Do some stuff here
while your_next_condition and loop:
// Do some stuff here
if something_happened:
loop = False
zero = False
while not zero:
nombre = int(input("Entrez un nombre entier positif (0 pour terminer): "))
facteurs = []
if nombre == 0:
zero = True
else:
while nombre % 2==0:
facteurs.append(2)
nombre //= 2
diviseur = 3
while nombre != 1 and diviseur <= nombre:
if nombre % diviseur == 0:
facteurs.append(diviseur)
nombre //= diviseur
else:
diviseur += 2
print("La décomposition en facteurs premiers est: ")
print(*facteurs, sep=" * ")
*** So this is my code now I need the program to restart when the user input is not zero but now that I added my line // zero = False // My program doesn't print any answer and completely ignores the rest of the code. What is happening and how can I fix it ??
Thank you for your help !
Your line states that zero = False.
Your code will run while not zero, which is equivalent to say while zero is False. So you'll enter this decision branch: if your input is 0, I'm immediately prompt again with the question for my input. Otherwise, you go in the other branch.
Now, since your indentation is messed up, the final statement printing the answer is outside of the first while loop. You'll run until diviseur += 2 and start all over again, never exiting, since the second branch never sets zero = True.
nombre = -1
while nombre < 0:
nombre = int(input("Entrez un nombre entier positif (0 pour terminer): "))
if nombre == 0:
break
elif nombre > 0:
facteurs = []
while nombre % 2==0:
facteurs.append(2)
nombre //= 2
diviseur = 3
while nombre != 1 and diviseur <= nombre:
if nombre % diviseur == 0:
facteurs.append(diviseur)
nombre //= diviseur
else:
diviseur += 2
print("La décomposition en facteurs premiers est: ")
print(*facteurs, sep=" * ")
With the indentation below your code runs with the expected behaviour... Tested with Python3.7 in Spyder4
zero = False
while not zero:
nombre = int(input("Entrez un nombre entier positif (0 pour terminer): "))
facteurs = []
if nombre == 0:
zero = True
else:
while nombre % 2==0:
facteurs.append(2)
nombre //= 2
diviseur = 3
while nombre != 1 and diviseur <= nombre:
if nombre % diviseur == 0:
facteurs.append(diviseur)
nombre //= diviseur
else:
diviseur += 2
print("La décomposition en facteurs premiers est: ")
print(*facteurs, sep=" * ")
I do not understand why it does not run, I have all day trying to fix it. The program is supposed to be used to calculate the level of punctuation, and I no longer know what to do.
bonificacion = 2400
inaceptable = 0.1
aceptable = 0.4
meritorio = 0.6
puntos = float(input("Introduce tu puntuacion: ")
if puntos == inaceptable
nivel = Inaceptable
print(nivel)
elif puntos == aceptable
nivel = Aceptable
print(nivel)
elif puntos == meritorio
nivel == Meritorio
print(nivel)
else:
nivel = ""
#Mostrar nivel de rendimiento
if nivel = "":
print("Esta puntuacion no es valida")
else:
print("Tu nivel de rendimiento es %" nivel):
print("Te corresponde cobrar %" puntos * bonificacion)
This should work (assuming some recent Python for f-strings).
Notes:
I compare strings instead of floats, which often calls for trouble.
Learn the difference between = (assignment) and == (comparison)
if expressions must always be ended with colon :
This code is not elegant but does the job and might best help you understand the flow (more streamlined version below)
bonificacion = 2400
inaceptable = '0.1'
aceptable = '0.4'
meritorio = '0.6'
puntos = input("Introduce tu puntuacion: ")
if puntos == inaceptable:
nivel = 'inaceptable'
print(nivel)
elif puntos == aceptable:
nivel = 'aceptable'
print(nivel)
elif puntos == meritorio:
nivel = 'meritorio'
print(nivel)
else:
nivel = ""
# Show performance level
if nivel == "":
print("Esta puntuación no es válida")
else:
print(f"Tu nivel de rendimiento es {nivel}")
print(f"Te corresponde cobrar {float(puntos) * bonificacion}")
Update: A shorter version using a dict to map points to levels
bonificacion = 2400
levels = {
'0.1': 'inaceptable',
'0.4': 'aceptable',
'0.6': 'meritorio',
}
puntos = input("Introduce tu puntuacion: ")
nivel = levels.get(puntos, "")
# Show performance level
if nivel == "":
print("Esta puntuación no es válida")
else:
print(f"Tu nivel de rendimiento es {nivel}")
print(f"Te corresponde cobrar {float(puntos) * bonificacion}")
Sorry if my English is bad but it is not my native language
I'm starting my programming studies in Python, And I need to make this code for my class.
Basically consists of a checklist of the workers of a company to calculate their salary, applying some discounts and bonuses. In Option 4 of the menu, I must show all registered ID's with their final salary
I need to put the variable Sueldo Descontado Which is in the function Def Calcular_Sueldo() within the function Def Liquidaciones_Rut
Someone told me to define it as a class and add it to the registry List [] but I don't know how to do this :/
PS: If I define the variable SueldoDescontado as global Prints the same value for all ID's :/
I hope someone can help me
Heres my 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')
Small example
class Trabajador:
def __init__(self, number, month, year):
self.number = number
self.month = month
self.year = year
Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']
T1 = Trabajador(10, Mess[0] , 1979)
print (T1.number)
print (T1.month)
print (T1.year)
__init method is class constructor,but read the link I gave you
Run this from command line in Linux
python example1.py
You will get
10
enero
1979
I am trying to write a program for a class, that given a sold ticket, my matrix (15x30) should replace the available seat "#" by sold seat "*".
seats = []
for i in range (1,16):
for i in range (1,31):
seats.append("#")
while True:
try:
x = int(input("SVP entrer le numéro de la rangée (1-15): "))
for x in range (1,16):
y = int(input("SVP entrer le numéro du siège (1-30): "))
for y in range (1,31):
b = ((x-1) * 30) + (y-1)
s = "*"
for b in len(seats):
seats[b] = seats[s]
z = input("Voulez-vous acheter un autre sièges (o/n)? ")
if z == "o":
return True
else:
return False
except ValueError:
print("Désoler, ce siège à déjà été acheter.")
print(seats)
print("Fin du programme")
However, I have an error:
File "/Users/staceypoulet/Desktop/temp1.py", line 15, in <module>
if z in len(seats):
for b in len(seats):
TypeError: 'int' object is not iterable
Could anyone help me see the mistake?
Thank you in advance to anyone who gives me the time :)
You want to check if z in seats. len(seats) is an integer number and does not have membership.