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.
Related
I made a function that is being called recursively, and the condition for it to keep being called is a user input.
The recursion is working but the final value of the variable is being returned as None.
I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, etc.
Here is my code:
Main Py:
import funcoes_moeda
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
"1 - Aumentar Valor \n" \
"2 - Diminuir Valor \n" \
"3 - Dobrar Valor \n" \
"4 - Dividir Valor \n" \
"0 - Encerrar o Prorama"
)
valor = switch(valor)
print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))
Imported Functions:
def aumentar(valor):
quantia_aumentada = float(input('Insira a quantidade que voce deseja acrescentar: '))
valor += quantia_aumentada
return valor
def diminuir():
pass
def dobro():
pass
def metade():
pass
When i tried executing this, what i got was:
Insira o valor: 100.00
Escolha a funcao a ser aplicada no valor inserido:
1 - Aumentar Valor
2 - Diminuir Valor
3 - Dobrar Valor
4 - Dividir Valor
0 - Encerrar o Prorama
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 200.0
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 300.0
Escolha uma opcao... (0 para encerrar) : 0
Funcao foi aplicada. O valor final ficou: None
For a test case, you can use:
Chose 100.00, option 1 (2 times is enough), increment 100.00 each call.
Expected output: Current value = 300.00 (Because 100 + 100 + 100)
But i got None at the last print...
Please. What am i doing wrong??? :(
Thank you for all the help.
PS: I tried going through the following answers, but i was not able to solve this problem because the explanation was for the problems in the question, and i found it was a litle different than mine..
1 > Recursive function returning none - Dint understand.
2 > python recursive function returning none instead of string - This is treating a CSV file.
The problem is that when the case variable is equal to 0, the return valor statement is being executed within the switch() function, but this function is being called recursively so the value of valor is not being returned to the caller.
To fix this, you can add another return statement at the end of the switch() function that returns the value of valor when case is 0. This will ensure that the value of valor is returned to the caller, even when the switch() function is being called recursively.
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
# Return the value of valor when case is 0
return valor
When returning a value the recursion is braking and the value returns to the previous call of the function. If you want to return the value to the first call, you can return the value every time you call switch:
import funcoes_moeda
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
return switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
"1 - Aumentar Valor \n" \
"2 - Diminuir Valor \n" \
"3 - Dobrar Valor \n" \
"4 - Dividir Valor \n" \
"0 - Encerrar o Prorama"
)
valor = switch(valor)
print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))
Two issues:
The return at the end of the function 'switch' should be at the end of the function and not part of the 'else' case. Because if you select '1' you will change the value of 'valor', but after changing the value you exit the function withou returning a value.
The returned value of the recursive call to 'switch' in the code section of 'if case == 1:' is not saved and therefore lost.
If you only correct the first point above you will get changed values only from the top call to 'switch', but all changes from the recursive calls will get lost.
The solution proposed by thebjorn solves both above listed issues. But treating the issues one by one, might be easier to understand.
I wrote a program to count grades and the students' names and I want to implement a feature that shows the highest grade and the respective student. The whole program works except for this part, since I'm not sure how to pick the element with the highest value since it comes with a string attached.
I'll leave the entire program down but the part that I'm refering to is this:
mediafinal = []
elif resposta.upper() == 'N':
resposta = input('Check best student and grade? (Y/N):')
if resposta.upper() == 'Y':
print('Best student and grade is: ', max(mediafinal))
break
The rest of the code
media1 = []
media2 = []
media3 = []
mediafinal = []
nomes = []
while True:
resposta = input('Pretende introduzir um aluno? (Y/N): ')
if resposta.upper() == 'Y':
nome = (input('Indique o nome do aluno: '))
nomes.append(nome)
nota1 = eval((input(f'Indique a nota do primeiro teste {nome}: ')))
nota2 = eval((input(f'Indique a nota do segundo teste {nome}: ')))
m1 = ((nota1 + nota2)/2)
infoaluno1 = []
infoaluno1.extend([nome, m1])
media1.append(infoaluno1)
print(f'O nome e média do primeiro período do aluno é: {nome} {m1}')
nota3 = eval((input(f'Indique a nota do terceiro teste {nome}: ')))
nota4 = eval((input(f'Indique a nota do quarto teste {nome}: ')))
m2 = ((nota3 + nota4) / 2)
infoaluno2 = []
infoaluno2.extend([nome, m2])
media2.append(infoaluno2)
print(f'O nome e média do segundo período do aluno é: {nome} {m2}')
nota5 = eval((input(f'Indique a nota do quinto teste {nome}: ')))
nota6 = eval((input(f'Indique a nota do sexto teste {nome}: ')))
m3 = ((nota5 + nota6) / 2)
infoaluno3 = []
infoaluno3.extend([nome, m3])
media3.append(infoaluno3)
print(f'O nome e média do terceiro período do aluno é: {nome} {m3}')
mf = ((m1 + m2 + m3)/3)
mediafinal.extend([nome, mf])
print(f'Classificação final do aluno: {nome} {mf}')
elif resposta.upper() == 'N':
resposta = input('Pretende verificar o melhor aluno e nota? (Y/N):')
if resposta.upper() == 'Y':
print('O melhor aluno é:', max(mediafinal))
break
elif resposta.upper() == 'N':
print('Ok!')
break
The problem is much much MUCH simpler if you have a list of tuples instead of alternating strings and numbers:
mediafinal.extend([nome, mf])
should be:
mediafinal.append((mf, nome))
Then your max call just works out of the box like this:
mf, nome = max(mediafinal)
print('Best student and grade is: ', nome, mf)
Note that putting the score (mf) first in the tuple means that max will pick based on that. You could change the ordering, but then you need to tell max to make its selection based on the 2nd element:
mediafinal.append((nome, mf))
...
nome, mf = max(mediafinal, key=lambda m: m[1])
So without changing any of your code logic, and just fixing the max() line, I would have it as:
max(a, key=lambda el: el[1])
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=" * ")
Hey guys im trying to create N objects inside a for loop, but it gives me an error TypeError: cannot unpack non-iterable Jugador object.
can u help me pls?
what im doing wrong?
This is my code:
from Jugador import Jugador
class Juego():
tipoJuego = ""
nJugadores = ""
def __init__(self,tipoJuego, nJugadores):
self.tipoJuego = tipoJuego
self.nJugadores = nJugadores
nJugadoresInt = int(nJugadores)
tipoJuegoInt = int(tipoJuego)
if tipoJuegoInt == 1 or tipoJuegoInt == 2 or tipoJuegoInt == 3:
print("Has elegido el tipo de juego ",tipoJuegoInt, ", y van a jugar ", nJugadores, " Personas")
else:
print("Error: Tipo de juego invalido")
exit()
for i in range(1,nJugadoresInt):
print("Jugador",i, "introduzca el nombre de usuario:")
nUsu = input()
print("Introduzca la edad:")
age = input()
print("Introduzca la palabra elegida:")
word = input()
J,i = Jugador(nUsu, age, word)
If you intend to create a way to assign the N objects to find them back later, I can propose to store them in a list J :
from Jugador import Jugador
class Juego():
tipoJuego = ""
nJugadores = ""
def __init__(self,tipoJuego, nJugadores):
self.tipoJuego = tipoJuego
self.nJugadores = nJugadores
nJugadoresInt = int(nJugadores)
tipoJuegoInt = int(tipoJuego)
if tipoJuegoInt == 1 or tipoJuegoInt == 2 or tipoJuegoInt == 3:
print("Has elegido el tipo de juego ",tipoJuegoInt, ", y van a jugar ", nJugadores, " Personas")
else:
print("Error: Tipo de juego invalido")
exit()
J = []
for i in range(1,nJugadoresInt):
print("Jugador",i, "introduzca el nombre de usuario:")
nUsu = input()
print("Introduzca la edad:")
age = input()
print("Introduzca la palabra elegida:")
word = input()
J.insert(i,Jugador(nUsu, age, word))
For reference : https://docs.python.org/3.8/tutorial/datastructures.html
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