Return does not return information - python

When wanting to return a value with the return and wanting to use it later in a variable, nothing is returned to me.
#Actualizacion de informacion
def messageHandler(update: Update, context: CallbackContext):
userName = update.effective_user['username']
#text = update.message.text
Usuario = userName
ConsultarServer = ("Ingresa tu nombre de troncal correcta de lo contrario no se te regresara ninguna informacion.")
if ConsultarSaldoSw2 in update.message.text:
context.bot.send_message(chat_id=update.effective_chat.id, text="Ingresa tu nombre de troncal correcta de lo contrario no se te regresara ninguna informacion.")
text2 = update.message.text
return text2
print (text2)
if text2 in update.message.text:
context.bot.send_message(chat_id=update.effective_chat.id, text="Ingresa el servidor sw o sw2")
text3 = update.message.text
return text3
print (text3)

If the function is exhausted, and it doesn't meet any of your conditions, it will return None by default. Consider this shortened example:
def messageHandler(update: Update, context: CallbackContext):
if ConsultarSaldoSw2 in update.message.text:
return text2
if text2 in update.message.text:
return text3
# None of these if conditions are met, so nothing is returned
If you don't enter any of these if statements, you never return a value.

Return ends the function and does not print anything to the console. Also seems that they're endpoints for conditionals that may not be met.

Related

how do i fix this function with dictionary to add and print added people?

currently im trying to solve a problem in the code i wrote, for some reason whenever i call imprimir() it only shows the last added person while it should show all the persons added.
libro = {}
def agregar(rut, nombre, edad):
estudiante = {}
estudiante['rut'] = rut
estudiante['nombre'] = nombre
estudiante['edad'] = edad
libro['rut'] = estudiante
def imprimir():
for rut in libro:
estudiante = libro[rut]
print(estudiante['rut'], estudiante['nombre'], estudiante['edad'])
def main():
contador = 0
while contador < 2:
rut = input("rut: ")
nombre = input("nombre: ")
edad = input("Edad: ")
contador = contador + 1
agregar(rut, nombre, edad)
imprimir()
main()
I had the code limited to only 2 people to be added. so if for the first person i write, rut = 1, nombre = 1 and edad = 1, and for the second, rut = 2, nombre = 2 and edad = 2. While using main(), it should print:
1 1 1
2 2 2
but instead it just prints 2 2 2 with 1 1 1 not found, my guess is that somehow the added person are not added but instead rewritten, but i cant find why, if i includo imprimir() inside the while in the main() it prints each person as soon as i finish adding one, but the idea its that the program should print all the added people once i finish adding them.
The problem is your adding the items with the same key so the dict just overrides the last value with each entry you add...
libro = {}
def agregar(rut, nombre, edad):
estudiante = {}
estudiante['rut'] = rut
estudiante['nombre'] = nombre
estudiante['edad'] = edad
# this would override the previous entry since it's always the same key
libro['rut'] = estudiante
# use a key that is unique and all entries will be preserved
libro[rut] = estudiante
# or for some truly unique keys
libro[str(uuid.uuid4())] = estudiante

Python file executable error

I did a fuel calculator program for a game with python and then I compiled to .exe with cx_Freeze. It converts it well to .exe and I can open the executable but when the script interacts with the user the window closes after pressing enter when the user introduce the requested information.
This is one part of the code, after requesting some information to the user the program does some calculations but I think it's irrelevant because the problem is in the input. I want that the program doesn't close when the user press enter in the input of info requested.
import sys
COMBUSTIBLE=chr(raw_input("Introduce unidad de combustible: "))
DURACION=chr(raw_input("Introduce unidad de duracion: "))
if COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos" and DURACION != "vueltas" and DURACION != "tiempo" and DURACION != "km":
print "Error: Ambos argumentos son invalidos"
print "Primer argumento debe ser 'litros' o 'kilos'"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(1)
elif COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos":
print "Error: Primer argumento invalido"
print "Primer argumento debe ser 'litros' o 'kilos'"
sys.exit(2)
elif DURACION != "tiempo" and DURACION != "vueltas" and DURACION != "km":
print "Error: Segundo argumento invalido"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(3)
else:
pass
# TIPO 1 - LITROS - VUELTAS
if COMBUSTIBLE == "l" and DURACION == "v":
# DATA REQUEST
RACE_DURATION=int(raw_input("Introduce el total de vueltas de la carrera: "))
CAR_FUEL=float(raw_input("Introduce los litros totales del coche: "))
FUEL_PER_LAP=float(raw_input("Introduce el consumo medio en litros por vuelta: "))
The window will be closed right after your proggram finished executing. So if you want the window stays open you should remove sys.exit() statements and add something at the end of your script like:
input("Press any key to exit: ")
in Python 3 or
raw_input("Press any key to exit: ")
in Python 2

NameError: global name 'Circulo_Mohr_v1_2' is not defined

I'm trying make a simple menu (options: 1,2,3) and the second option (input 2) should run a graphical menu.
When I try run python reports a NameError ("global name 'Circulo_Mohr_v1_2' is not defined").
I don't know the correct syntax
print "inicio"
import sys
from librerias import Circ_Mohr_motor_v2
import librerias.Circulo_Mohr_v1_2
from librerias import prueba_importacion
'''
def definicion_ventana():
Circulo_Mohr_v3_0.Ui_CalculodecirculosMohr()
#Ui_CalculodecirculosMohr.setupUi()
'''
def seleccion_de_libreria():
print '''Escoger opcion:
1) motor
2) Ventana
3) test
'''
opcion = raw_input ("Opcion seleccionada: ")
opcion = int (opcion)
if opcion == 1:
print "se ejecuta el motor de calculo"
punto_Ax = raw_input ("Insertar coordenada X de primer punto: ")
punto_Ay = raw_input ("Insertar coordenada Y de primer punto: ")
punto_Bx = raw_input ("Insertar coordenada X de segundo punto: ")
punto_By = raw_input ("Insertar coordenada Y de segundo punto: ")
Circ_Mohr_motor_v2.circulo_mohr(punto_Ax,punto_Ay,punto_Bx,punto_By)
elif opcion == 2:
print "se ejecuta la funcion ventana"
Circulo_Mohr_v1_2.Ui_CalculodecirculosMohr()
print "fin la funcion ventana"
else:
print "se ejecuta el test"
prueba_importacion.prueba_01()
seleccion_de_libreria()
print "fin"
How can I fix that?
try replace
import librerias.Circulo_Mohr_v1_2
with
from librerias.Circulo_Mohr_v1_2 import Ui_CalculodecirculosMohwith
and call directly Ui_CalculodecirculosMohr()
Ui_CalculodecirculosMohr()

Keys and Dictionaries

it seems that my code isn't working well, everytime i run it it seems that the key value of agenda is replaced by the next one I enter instead of adding it as a new one. Please help my find why is this happening and how to i fix it. Thanks!
def contactos():
q=int(raw_input("Desea agregar un contacto (1=si, 0=no): "))
while q==1:
a=raw_input("ingrese nombre contacto, telefono, mail (delimitados por espacio)")
d=a.split()
agenda={}
agenda[d[0]]= "nombre", d[0], "telefono: ", d[1], "mail :", d[2]
q=int(raw_input("Desea agregar otro contacto (1=si, 0=no): "))
print agenda.keys()
return agenda
You are resetting agenda to an empty dictionary each time through the loop. Initialize it once before the loop.
def contactos():
agenda = {}
q=int(raw_input("Desea agregar un contacto (1=si, 0=no): "))
while q==1:
a=raw_input("ingrese nombre contacto, telefono, mail (delimitados por espacio)")
d=a.split()
agenda[d[0]]= "nombre", d[0], "telefono: ", d[1], "mail :", d[2]
q=int(raw_input("Desea agregar otro contacto (1=si, 0=no): "))
print agenda.keys()
Do note Cyber's answer, as well, if you want to add multiple phone numbers and addresses for the same name.
Instead of assigning, which will overwrite the value
agenda[d[0]]= "nombre", d[0], "telefono: ", d[1], "mail :", d[2]
You would have to append
agenda[d[0]].append(["nombre", d[0], "telefono: ", d[1], "mail :", d[2]])
you should/could use class instead
https://docs.python.org/2/reference/datamodel.html
here is a very simple example
class contact:
def __init__(self, name="", phone="", mail=""):
self.phone = phone
self.name = name
self.mail = mail
a = contact("A name")
print a.name
a.mail = "test#gmail.com"
print a.mail

Keep the list through functions

I have this code wrote in Python:
liste_usager = input("Veuillez entrer la liste d'entiers:")
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
print(liste)
return liste
print('liste enregistrée')
print('que voulez-vous faire?')
boucle = True
while boucle:
print('''
1-afficher la liste
2-trier la liste
3-afficher la valeur maximale
4-afficher la valeur minimale
5-afficher la somme des valeurs
6-inverser la liste
7-modifier la liste
0-retour
''')
choix= input('choissisez une commande:')
if choix =='1':
print(liste_usager)
if choix =='2':
menu_tri()
else:
boucle= False
this just return a list of integer such as [1,2,3]. My problem is that I have other def function/module in this same .py file,and those module needs to use the resulting list of this gestionliste() module.For example a module sort the list,but how to keep the list or transfer it to other modules/functions without asking it again to the user? Thanks!
Return the list from the function, and pass it to other functions.
At the bottom of your function, add
return liste
When you call the function, use:
liste = gestionliste();
When you call a new function, pass it in like this:
otherFunction(liste)
Of course your other function must take it as a parameter.
def otherFunction(liste):
# You can now use liste inside this function.
You have the return the result list.
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
In your original copy of code, you did not return anything explicitly. So by default, it return None.
And to use the result in another function, to say func2, you could do like:
temp = gestionliste()
func2(temp)
Just change your print to return
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
# I used list comprehension instead of your for loop
liste = [int(n) for n in liste_usager.split(' ')]
return liste
Return liste from the function.
Example:
# In function definiton file
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
# In your main script
liste = gestionliste()

Categories