why my conditions do not display anything? - python-3.x

my code choose a random number and the user must find the random number
but if I write a bigger or smaller number it doesn't display anything
from random import *
nb_au_hasard = (randint(1, 50))
print(nb_au_hasard)
nb_choisi = (int(input("choisi un nombre entre 1 et 50")))
while nb_choisi == nb_au_hasard:
if nb_choisi < nb_au_hasard:
print("le nombre est plus grand")
else:
print("le nombre est plus petit")
if nb_choisi == nb_au_hasard:
print("tu as reussi ")
break

Related

Finding the cause of a tab error inside a Class

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

"How to fix" 'Cant give more values to the variable' Python3

"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}")

Python - Select 2 columns in a Dataframe and classify them

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

Loop in Loop - Performing an error check

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 ?

If y in range Python Error Catching

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.

Resources