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()
Related
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.
I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.
Here is my code :
while number != None:
try:
while True:
number = int(input("Donnez la longueur de votre liste: "))
if number > 0:
break
except TypeError:
print("Tu doit donner un nombre entier")
The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.
You can sidestep any warnings with a more idiomatic loop:
while True:
number = input("Donnez la longueur de votre liste: ")
try:
number = int(number)
except ValueError:
print("Tu doit donner un nombre entier")
continue
if number > 0:
break
I have a question. I'm programming the gallows game. Everything's fine, but I'm stuck with something. The user selects a letter, which will be displayed on the screen and in the corresponding box. But every time the user selects a letter, the, Those I used to choose are gone.
You can see:
import pyfiglet
import random
import os
def start():
print(pyfiglet.figlet_format("BIENVENIDO AL JUEGO DEL AHORCADO"))
print("""
¡ A D I V I N A L A P A L A B R A !
""")
def game():
with open("./archivos/data.txt", "r", encoding="utf-8") as f:
palabras = list(f)
palabra = random.choice(palabras)
palabra = palabra.replace("\n", "")
letras = [i for i in palabra]
guiones = []
for i in letras:
guiones.append("_")
print(" ".join(guiones))
print("")
guiones = []
while guiones != letras:
letra = input("Elige una letra: ")
for i in palabra:
if i == letra:
guiones.append(letra)
else:
guiones.append("_")
print(" ".join(guiones))
guiones.clear()
def run():
start()
game()
if __name__ == "__main__":
run()
Since You are working with lists (which are mutable), You can flip the "_" to the guessed letter and not touch the rest of guiones. To do so, one solution is to use an index to access the list at the given position, like in the code snippet below :
# guiones = [] do NOT clear guiones!
while guiones != letras:
letra = input("Elige una letra: ")
for i in range(len(palabra)):
if palabra[i] == letra:
guiones[i] =letra
print(" ".join(guiones))
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
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()