I was coding this simple 'Bank' program for my first exercise with classes in Python but when I run it, says:
tabError: inconsistent use of tabs and spaces in indentation
line 45
if self.datos[x]['nombre'] == nombre and self.datos[x]['idnum'] == idnum and self.datos[x]['email'] == email:^
I understand what it means, and I took a look on my code and tried to find if there was some problem with the methods, nevertheless I couldn't understand what is causing it, I believe something about the dictionaries has something to do with it. So this is my code:
class Cliente:
def __init__(self):
self.datos = []
def opciones(self):
menu = ['1: Mostrar saldo',
'2: Ingresar monto',
'3: Retirar monto',
'4: Cerrar']
for option in range(len(menu)):
print(option)
opc_escoger = int(input('Escriba el número de la opción que desee: '))
if opc_escoger == 1:
self.mostrar()
elif opc_escoger == 2:
self.Ingresar()
elif opc_escoger == 3:
self.retirar()
elif opc_escoger == 4:
print('Saliendo...')
exit()
elif opc_escoger == 5:
self.registrarse
self.opciones()
def registrarse(self):
print('REGISTRO')
nombre = input('Ingrese su nombre de usuario: ')
idnum = input('Ingrese su número de documento de identificación: ')
email = input('Ingrese su dirección de correo electrónico: ')
self.datos.append({'nombre':nombre, 'idnum':idnum, 'email':email, 'monto': 0})
def ingresar(self):
print('INGRESAR')
nombre = input('Ingrese su nombre de usuario: ')
idnum = input('Ingrese su número de documento de identificación: ')
email = input('Ingrese su dirección de correo electrónico: ')
for x in range(len(self.datos)):
if self.datos[x]['nombre'] == nombre and self.datos[x]['idnum'] == idnum and self.datos[x]['email'] == email:
print('Dinero actual: ', self.datos[x]['monto'])
monto = input('¿Cuál es el monto a ingresar?: ')
self.datos[x]['monto':monto]
else:
print('Los datos ingresados no coinciden con los de un usuario registrado')
self.registrarse()
#Here's some more code for the other methods, but are pretty similar to the 'ingresar' method
Related
I currently doing this tic tac toe project, but I am stuck because it does not work, so I need help identifying what errors I made. In addition, I need to allow the user to choose one letter ("X" o "O") and the "X" goes first. I don't know how can I code this. I hope that someone help me, please.
This is the code that I have developed:
# Variables globales
# Tablero vacio
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_",]
# Si juego continua
juego_continua = True # El juego continua desde el inicio.
# Quien gana o empata
ganador = None
# Turno asignado
actual_jugador = "X"
# Funcion que defin juego tic tac toe.
def jugar_juego (): #
display_board() # Se va a representar el tablero inicial en pantalla.
# Mientras el juego continua.
while juego_continua: # Booleano
# Definir un solo turno para un jugador arbitrario
handle_turn (actual_jugador)
# Verificar si se acabo el juego
verificar_si_termino_juego()
# Cambiar al otro jugador
cambio_jugador()
# El juego ha terminado
if ganador == "Jugador - X" or ganador == "Jugador - O":
print(ganador + "Ganaste.")
elif ganador == None:
print ("Hay empate.")
def display_board():
print ("\n")
print (board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print (board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print (board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print ("\n")
# Define un turno para el jugador arbitrariamente.
def handle_turn(jugador):
print(jugador + "turno.")
posicion = input("Elegir una posicion desde 1 hasta 9 para comenzar: ")
valid = False
while not valid:
while posicion not in ["1", "2", "3", "4", "5", "6", "7", "8" ]:
posicion = input("Por favor elegir una posicion desde 1 hasta 9 para jugar: ")
posicion = int(posicion) - 1
if board (posicion) == "_":
valid = True
else:
print ("Esta posición ya esta ocupada, elegir otra: ")
board[posicion] = jugador
display_board()
def verificar_si_termino_juego():
verificar_si_gano()
verificar_si_empate()
def verificar_si_gano():
# Establecer variable global
global ganador
# verificar filas
ganador_filas = check_filas()
# verificar columnas
ganador_columnas = check_columnas()
# verificar diagonales
ganador_diagonales = check_diagonales()
if ganador_filas:
ganador = ganador_filas
elif ganador_columnas:
ganador = ganador_columnas
elif ganador_diagonales:
ganador = ganador_diagonales
else:
#No hay ganador
ganador = None
def check_filas():
# Establecer variable global
global juego_continua
# Revisa si las filas son iguales, exceptuando "_"
fila_1 = board[0] == board[1] == board[2] != "_"
fila_2 = board[3] == board[4] == board[5] != "_"
fila_3 = board[6] == board[7] == board[8] != "_"
# Si alguna fila es igual, indica que hay un ganador
if fila_1 or fila_2 or fila_3:
juego_continua = False
# Devuelve el ganador (X o O)
if fila_1:
return board[0]
elif fila_2:
return board[3]
elif fila_3:
return board[6]
# Retorna ninguna si no hay ganador
else:
return None
def check_columnas():
# Establecer variable global
global juego_continua
# Revisa si las columnas son iguales, exceptuando "_"
columnas_1 = board[0] == board[3] == board[6] != "_"
columnas_2 = board[1] == board[4] == board[7] != "_"
columnas_3 = board[2] == board[5] == board[8] != "_"
# Si alguna columna es igual, indica que hay un ganador
if columnas_1 or columnas_2 or columnas_3:
juego_continua = False
# Devuelve el ganador (X o O)
if columnas_1:
return board[0]
elif columnas_2:
return board[1]
elif columnas_3:
return board[2]
else:
return None
def check_diagonales():
# Establecer variable global
global juego_continua
# Revisa si las diagonales son iguales, exceptuando "_"
diagonal_1 = board[0] == board[4] == board[8] != "_"
diagonal_2 = board[2] == board[4] == board[6] != "_"
# Si alguna diagonal es igual, indica que hay un ganador
if diagonal_1 or diagonal_2:
juego_continua = False
# Devuelve el ganador (X o O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
else:
return None
def verificar_si_empate():
global juego_continua
if "_" not in board:
juego_continua = False
return True
else:
return False
def cambio_jugador():
global actual_jugador
# Si actual jugador fue X, luego cambia a O
if actual_jugador == "X":
actual_jugador = "O"
# Si actual jugador fue O, luego cambia a X
elif actual_jugador == "O":
actual_jugador = "X"
jugar_juego()
The indentation is incorrect.
Here is the updated code:
def handle_turn(jugador):
print(jugador + "turno.")
posicion = input("Elegir una posicion desde 1 hasta 9 para comenzar: ")
valid = False
while not valid:
while posicion not in ["1", "2", "3", "4", "5", "6", "7", "8" ,"9"]:
posicion = input("Por favor elegir una posicion desde 1 hasta 9 para jugar: ")
posicion = int(posicion) - 1
if board[posicion] == "_":
valid = True
else:
print ("Esta posicion ya esta ocupada, elegir otra: ")
board[posicion] = jugador
display_board()
"I want to use the statement break, and also in case the condition is not True, to give some values to a new variable. The thing is, Python uses only one line, and still runs after i've inserted a number.
prompt = '\nDime tu edad y te dire el precio de tu entrada .'
prompt += '\n¿Cual es tu edad?'
while True:
edad = input(prompt)
edad = int(edad)
if edad < 3:
break
elif edad > 3: ## Here I'm trying to set the conditions as to give a new value to precio.
precio = '5€'
elif edad > 12:
precio = '10€'
elif edad > 18:
precio = '15€'
print(f" El precio es {precio}")
I'm new in the programming world, and I'm doing some studies to gain knowledge in the area of Data Science.
I have a Dataframe with a lot of information, among it gender and age. I want to bring the amount of lines of each gender (male and female) and classify them as children (0 to> 12 years), young (12 to> 18 years) and adults (18+ years).
The result would be something like:
Children Female: x amount
Young Female: y amount
Adult Female: z amount
Children Male: n amount
Young Male: k amount
Adult Male: j amount
I'm lost to the point of not knowing if I have started correctly... I have created another dataframe with the two columns I need.
df2 = df[["Sex", "Age"]].copy()
Little stuck from here
EDIT (sorry about some terms in the code, they are in portugues but the code is understandable
I could solve the problem.
Here what I did from begining:
Creation of a new DF with only the informations I need:
df2 = df[["Sex", "Age"]].copy()
Creation of a function to classify the values:
def definition(age):
if age >= 18:
return 'Adulto'
elif age >= 12:
return 'Jovem'
return 'Criança'
Add the new column to the DF
df2['Classification'] = df2['Age'].map(definition)
and PRINT
print("A quantidade de crianças do sexo masculino é de {}".format(len(df2.loc[df2['Classification'] == 'Criança'].loc[df2['Sex'] == 'male'])))
print("A quantidade de crianças do sexo feminino é de {}".format(len(df2.loc[df2['Classification'] == 'Criança'].loc[df2['Sex'] == 'female'])))
print("A quantidade de jovens do sexo masculino é de {}".format(len(df2.loc[df2['Classification'] == 'Jovem'].loc[df2['Sex'] == 'male'])))
print("A quantidade de jovens do sexo feminino é de {}".format(len(df2.loc[df2['Classification'] == 'Jovem'].loc[df2['Sex'] == 'female'])))
print("A quantidade de adultos do sexo masculino é de {}".format(len(df2.loc[df2['Classification'] == 'Adulto'].loc[df2['Sex'] == 'male'])))
print("A quantidade de adultos do sexo feminino é de {}".format(len(df2.loc[df2['Classification'] == 'Adulto'].loc[df2['Sex'] == 'female'])))
Result:
A quantidade de crianças do sexo masculino é de 36
A quantidade de crianças do sexo feminino é de 32
A quantidade de jovens do sexo masculino é de 22
A quantidade de jovens do sexo feminino é de 23
A quantidade de adultos do sexo masculino é de 519
A quantidade de adultos do sexo feminino é de 259
I would create the classes for age using pandas.cut and then group by the two columns and check the size. Let me know if I can elaborate on anything.
bins = [1, 5, 10, 15]
group_names = ['Children', 'Young', 'Adult']
age_groups = pandas.cut(df2.Age, bins, labels=group_names)
df2['Age Groups'] = age_groups.tolist()
df2.groupby(['Gender','Age Groups']).size()
My familiarity with the nuances of pandas.cut is a bit rusty so the above bins are not exactly what you want. I suggest playing around with the data in a notebook to get them where you want them. The docs here are helpful https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html
The code checks for a User ID (id_usager). If it doesn't check out, it performs the else as an error catch. If it does check out, it calls in the other functions and prints ("Pour la personne"etc). That being said, I want my program to continue onto autreRecommandation afterwards, however as it stands, it exits after the aforementioned print.
while True:
id_check = True
while id_check:
id_usager = input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}): ".format(n - 1))
if id_usager.isdigit():
if int(id_usager) in range(n):
id_usager = int(id_usager)
calculer_scores_similarite(reseau)
print("Pour la personne", id_usager, ", nous recommandons l'ami", recommander(id_usager, reseau, matrice_similarite), ".")
return id_check == True
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
autreRecommandation = input("Voulez-vous une autre recommandation (oui/non)?")
if autreRecommandation.lower() == "oui":
return True
else:
print("Merci d'avoir utiliser le programme de recommandation d'amis.")
break
The return id_check == True statement will return control to the caller of your function.
Instead you could use the break statement to come out of the inner while loop and the control will then return to the outer while loop and go to autreRecommandation as expected.
The code could be more like
calculer_scores_similarite(reseau)
print("Pour la personne", id_usager, ", nous recommandons l'ami",recommander(id_usager, reseau, matrice_similarite), ".")
id_check == True
break
have you tried the keyword continue ?
I seem to be having an issue with an error catch that I'm trying to implement in my code. Basically, if somebody writes something out of the scope from the range, I want my error message to show up. Otherwise, it'll just continue on with the program.
Here's the code.
n = 10
while True:
id_usager = input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}): ".format(n-1))
if id_usager in range(n):
calculer_scores_similarite(reseau)
print("Pour la personne", id_usager, ", nous recommandons l'ami", recommander(id_usager, reseau, matrice_similarite))
continue
else:
print(id_usager)
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
This breaks, because you do not cast id_usager to an integer. Checking if it's in the range only works if it's an integer.
You can use s.isdigit() to check if you can safely convert to an integer, and then s = int(s) to do the conversion.
** edited based on comment
I found the trick.
while True:
id_usager = input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}): ".format(n - 1))
if id_usager.isdigit():
if int(id_usager) in range(n):
id_usager = int(id_usager)
calculer_scores_similarite(reseau)
print("Pour la personne", id_usager, ", nous recommandons l'ami", recommander(id_usager, reseau, matrice_similarite))
continue
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
This allows me to filter out the strings if there are in order to return an error message.