A function executes an algorithm that returns a value.
Its initial function uses variables that need user interaction to inform what it wants.
To leave only the function returning the lists, you will need:
- Remove user information requests from function
- The Function will receive the values of variables as parameters of function.
That is, you need to divide your current function into two parts, the first part being the "application" that will collect the necessary entries that will be passed as parameter to the function.
Based on your example, we would have that the function now predicts the receipt of 4 possible parameters def entrada_soma(entrada,n,x1,x2):
.
The Function
def entrada_soma(entrada,n,x1,x2):
parcela1 = list()
parcela2 = list()
if entrada == 1:
for c in range(0, n):
parcela1.append(x1)
for c in range(0, n):
parcela2.append(x2)
else:
for c in range(0, n):
parcela1.append(random.randint(0, 9))
for c in range(0, n):
parcela2.append(random.randint(0, 9))
return parcela1, parcela2
Note that the above function does not require anything else from the user, as this request will be separate from the function.
The Application using the function
The App will be responsible for collecting the necessary information to be passed to the function as a parameter and display the received result.
print("Digite a opção desejada :")
print("[1] - Valores pelo Teclado / [2] - Gerar aleatoriamente")
entrada = int(input())
print("Quantos inteiros cada sequência terá ?")
n = int(input())
x1 = 0 # Declarando variáveis possíveis a serem utilizadas
x2 = 0 # A segunda variável "x" que havia sido utilizada na função original
if entrada == 1:
print("Digite a sequência de inteiros da parcela 1 :")
x1 = int(input())
print("Digite a sequência de inteiros da parcela 2 :")
x2 = int(input())
p1, p2 = entrada_soma(entrada, n, x1, x2)
print("Valores gerados para a parcela 1 :", end=' ')
print(p1)
print("Valores gerados para a parcela 2 :", end=' ')
print(p2)
I tried to change the name of your variables as little as possible and I did not analyze the logic of your algorithm. Apparently it’s not working properly.
The function aims to reuse code.
I do not see as good practice the fulfillment of requests to the user in the body of the function.
The application that will call the function is that will be in charge of collecting the values to be passed to the function as parameter.
The function must declare parameters that will be used in the body of the algorithm.
Below, let’s make an analogy with another code, say you had the next code and wanted to remove the requests from the function:
Function with prints and inputs
# Função com prints e requisições do usuário
def somaDoisNumeros():
print('Soma de 2 números')
print('Informe o primeiro número:')
numero1 = int(input())
print('Informe o segundo número:')
numero2 = int(input())
resultado = numero1 + numero2
return resultado
# Aplicativo utilizando a função
soma = somaDoisNumeros()
print('A soma é:',soma)
Now let’s remove the prints and inputs from the function, passing the requests to be made to the user to the body of the "application"
Function without prints or inputs
# Função sem prints e sem requisições do usuário
def somaDoisNumeros(numero1, numero2):
resultado = numero1 + numero2
return resultado
# Aplicativo utilizando a função. Coleta entradas necessárias
print('Soma de 2 números')
print('Informe o primeiro número:')
n1 = int(input())
print('Informe o segundo número:')
n2 = int(input())
soma = somaDoisNumeros(n1, n2)
print('A soma é:',soma)
The main purpose of the function is to help us organize programs in pieces that correspond to how we imagine a solution of the problem.
Example to request user option
def lerOpcao():
print("Informe como deseja gerar suas listas")
print("[1] - Valores pelo Teclado")
print("[2] - Gerar aleatoriamente")
entrada = int(input())
return entrada
This function lerOpcao()
could be called while the user reported a value other than 1 or 2 as follows:
opcao = 0
# Garantir que seja informada umas das opções possíveis
while opcao not in [1,2]:
opcao = lerOpcao()
This way, a function was created to request the user’s option, I’m not saying it is the best way, but you will do the functions according to your programming logic.
Function to return list of numbers entered manually
You could create a function to be used whenever you need the user to inform the list of the number that should appear in the sequence, n
will be the number of the sequence, as in the following example:
def lerNumerosManuais(n):
lista = []
print(f'Informe os {n} números da lista')
for i in range(0,n):
print("Informe um número :", end=' ')
valor = int(input())
lista.append(valor)
return lista
Would use the function lerNumerosManuais
next form:
if opcao == 1:
print("Digite a sequência de inteiros da parcela 1 :")
parcela1 = lerNumerosManuais(n)
Function to return list of numbers when the option is Random
def geraNumerosAleatorios(n):
lista = []
for i in range(0,n):
valor = random.randint(0, 9)
lista.append(valor)
return lista
Example of the call:
parcela1 = geraNumerosAleatorios(n)
I hope it helps.
Hi , in other cases I also would not do this way kk , I found strange the possibility of being able to do this in python , actually I did in trying to meet the requirements of an issue , follows the description of the problem : -----> 1. input() that make the input and its checks c by and ask to Usu Rio what the integer n each sequence will have and whether the user wants to enter integer sequences or whether he wants to randomly generate them. In the second case, use the Random library to & #Xa;generate pseudo-random numbers for the two lists:
– Lailson San
See if I understand the problem correctly. In the description of the problem, I understood that you must create a function to validate the user’s data entry. I believe I should check that what the user has reported is actually an integer, for example. Is that it? Could reformulate the description of the problem to facilitate understanding?
– Clarck Maciel
More or less, I added an image to the file, which shows the statement .
– Lailson San
@Lailsonsan, I didn’t see the image that shows the statement. It was actually sent?
– Clarck Maciel
I had put for some reason gone , however I already sent the incorrect file even , for partial correction , even so it would be interesting for me to remedy this doubt , if you want to send your email I can send you , I’m new here , if you do not tranquil kk !
– Lailson San
Please inform here, what is the statement, to seek to improve the question and the answer in order to help both you and other users who may have a similar question.
– Clarck Maciel
I guess now it was, I hadn’t saved
– Lailson San
Now I got to see the statement in question. You really want to take all prints and inputs from the function
entrada_soma()
? I ask, for the reason of the statement inform that there will be user interaction to choose (1) Type of sequence generation, (2) Number of numbers to be informed / generated for each sequence. So, if you need information passed by the user and this function is the intended to collect this information and return only the resulting list, I think theprints
andinputs
are mandatory.– Clarck Maciel
Yes exactly , I interpreted this way , however every time I try to get the parameters that this function returns , the function runs again , I was not able to save in a list without the inside parameters were not executed
– Lailson San
I wonder if the function entrada_soma() link would solve your problem? In this function, you would output a list
parcelas
where each item would be a sequence or portion that can be accessed later with the loopfor
as demonstrated in the function. Access the function by clicking on the following link ideone.– Clarck Maciel