Question:
I'm having difficulty with this code, I adapted it in two functions as guided by prof. but I'm having difficulty in the final phase, which asks: use for
or while
for n times (n equivalent to the amount of products informed). Within the repetition structure, I must call the function “verificar_product”, allowing the user to be able to register all products and check whether or not there would be any limit left to buy them.
Could someone help me to structure this phase?
def obter_limite (salario, idade, limite):
print('Irei fazer uma análise de crédito para você, para isso preciso apenas de alguns de seus dados. \n')
salario = float(input('Qual seu salário? '))
ano_nascimento = int(input('Qual seu ano de nascimento? \n'))
import datetime
agora = datetime.datetime.now()
idade = agora.year - int(ano_nascimento)
print('Sua idade é: ', idade)
limite = float(salario * idade / 1.000) + 100
print('\nJá analisei seu crédito! Você poderá gastar na loja: R${:.2f}'.format(limite))
return limite
limite = obter_limite(salario, idade, limite)
def verificar_produto (limite):
produto = input('Informe o nome do produto que deseja comprar: ')
preço = float(input('Informe o valor: '))
porcentagem = preço*100/limite
if porcentagem <= 60:
print('\nLiberado')
elif porcentagem <= 90:
print('\nLiberado ao parcelar em até 2 vezes')
elif porcentagem <= 100:
print('\nLiberado ao parcelar em 3 ou mais vezes')
else:
print('\nBloqueado')
print('Escolha outro produto com valor inferior ao seu limite de crédito')
desconto = float(7)
if preço >= 23 and preço <= idade:
print('Você ganhou um desconto, o valor do produto ficará: R${:.2f}'.format(preço - 7))
return limite, preço, desconto
limite, preço, desconto = verificar_produto (limite)
#Quantidade #laço repetição de produto soma valores e verificação do limite
n = int(input('\nQuantos produtos deseja cadastrar? '))
for n (verificar_produto)
while preço <= limite
print(verificar_produto)
Answer:
To repeat something n
times, you can use a for
along with range
:
for _ in range(n):
# faz algo
range(n)
generates a sequence of numbers from 0
to n - 1
(which in practice will make the loop iterate n times).
The _
variable is a Python convention that says I don't care about the value of the number (since I'm not going to use that value in this case, I'm just using the range
to execute something multiple times).
Another detail is that it doesn't make sense for the function obter_limite
receive as parameters the age, salary and limit, since this information will be overwritten inside the function. Also, verificar_produto
you are accessing the idade
, but this variable only exists within obter_limite
and you can not access it outside this function.
Anyway, from what I understand of the program's operation, it would look like this:
import datetime
def obter_limite():
print('Irei fazer uma análise de crédito para você, para isso preciso apenas de alguns de seus dados. \n')
salario = float(input('Qual seu salário? '))
ano_nascimento = int(input('Qual seu ano de nascimento? \n'))
agora = datetime.datetime.now()
idade = agora.year - int(ano_nascimento)
print('Sua idade é: ', idade)
limite = float(salario * idade / 1.000) + 100
print('\nJá analisei seu crédito! Você poderá gastar na loja: R${:.2f}'.format(limite))
# retorna o limite e a idade, que serão usados depois
return limite, idade
def verificar_produto(limite, idade):
produto = input('Informe o nome do produto que deseja comprar: ')
preço = float(input('Informe o valor: '))
porcentagem = preço * 100 / limite
if porcentagem <= 60:
print('\nLiberado')
elif porcentagem <= 90:
print('\nLiberado ao parcelar em até 2 vezes')
elif porcentagem <= 100:
print('\nLiberado ao parcelar em 3 ou mais vezes')
else:
print('\nBloqueado')
print('Escolha outro produto com valor inferior ao seu limite de crédito')
desconto = float(7)
if preço >= 23 and preço <= idade:
preço -= 7
print('Você ganhou um desconto, o valor do produto ficará: R${:.2f}'.format(preço))
# desconta o preço do limite e retorna o novo limite atualizado
return limite - preço, preço
limite, idade = obter_limite()
n = int(input('\nQuantos produtos deseja cadastrar? '))
for _ in range(n):
limite, preço = verificar_produto(limite, idade)
Note that the function verificar_produto
receives the current limit and returns the new date limit (already discounted the price of the product you just bought).
Of course there are other details to fix (if the product is blocked, shouldn't you ask to type in another product or close? the age calculation is not accurate, as it only takes into account the year, etc.), but then it would run away a little from the scope of the question, which was how to loop .