How to change the value of variables every time you repeat the def function?

Asked

Viewed 599 times

-3

My algorithm solves the following problem: Create an algorithm that reads 4 typed values and indicates if any pair of numbers sums 8 or a number greater than 8.

    s = [int(input()) for c in range(4)]
while sum(s) < 8:
    print('Error 01: Erro: A soma de todos os 4 números resulta num número menor que 8, digite outros números.')
    s = [int(input()) for c in range(4)]
    if sum(s) > 8:
        break
x = 0
y = 0
z = 1
s = sum(s[y] + s[z])
while x < 6 or s < 8:
    def funcao(x = 0, y = 0, z = 1):
        if s == 8:
            print(f'Os números {s[y]} e  {s[z]} somados dão 8. ')
        elif s > 8:
            print(f'Os números {s[y]} e  {s[z]} somados resultam num número maior que 8. ')
        else:
            if x == 3 and s < 8:
                funcao(x+1,y+1,z+1)
  • What would be exactly the doubt and what you have below the comment "#here the function would repeat again, only adding 1 to the initial value of variables x, y and z."?

  • My code ends exactly at this point, because below that would enter the def function that starts in the first comment and ends before the second, but for that I need to know how to add 1 in the value of the variables x, y and z each time the function repeats, and so be able to test if there are any pairs of numbers that add up to 8.

  • My question is: How to create a def function, so that it adds 1 to the value of the variables x, y and z every time the function repeats.

1 answer

3

 def funcao (x=0, y=0, z=1):

    while x < 3:
        s = sum(s[y] + s[z])
        z += 1
        x += 1
        if s == 8:
            print(f'Os números {s[y]} e  {s[z]} somados dão 8. ')
        elif s > 8:
            print(f'Os números {s[y]} e  {s[z]} somados resultam num número maior que 8. ')
        elif x == 3 and s < 8:
            funcao(x+1,y+1,z+1)

This confused way of understanding what you want because I feel that the code is incomplete, after all not even the def.

When starting def function if you do not declare values it will start at x = 0, y = 0 and z = 1, just like you put at the beginning of the function. And at the end of it, he’ll take the values he already has of x,y,z and put +1 on them.

  • Yeah, that’s what I was looking for. I made some changes to the code, but now the error occurs because of using integer variables to represent the position of the string, there is another way to do this without using integers?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.