Doubt in PA code in Python

Asked

Viewed 300 times

-1

Was Doubtful in an exercise resolution in Python.

       pri_termo = int(input('Digite o primeiro Termo: '))
       razao = int(input('Digite a Razão da PA: '))
       termo = pri_termo
       cont = 1
    while cont <= 10:
       print('{} --> '.format(termo), end='')
       termo += razao
       cont += 1

My real doubt is that the 'term' corresponds to the 'pri_term', where the two would have the same value? Thank you in advance.

  • Well, that’s a very specific question and I think it’s outside the scope of the site. But note that this occurred only because the name used within the loop is termo. It would be possible to use only the name pri_termo, but to do so would need to change the name of the variable within the loop

  • It makes sense if, for whatever reason, you want to preserve the value of pri_termo. If there is no such need then you can use only one variable.

2 answers

0

No need to create the term variable. Follow the code a little changed:

pri_termo = int(input('Digite o primeiro Termo: '))
razao = int(input('Digite a Razão da PA: '))
cont = 1
while cont <= 10:
    if cont < 10:
        print('{} --> '.format(pri_termo), end='')
    elif cont == 10:
        print('{}'.format(pri_termo), end='')
    pri_termo += razao
    cont += 1
  • Now if you want to preserve somehow the value of the variable pri_term, it makes sense to create another variable, but for the case of a PA, I think it doesn’t make much sense to create.

0

For the code to work it is not necessary to create and assign a new variable called termo the value of pri_termo, but he did it so that the value of the first term was not changed.

You see, if somewhere else in your code you needed to get the value of the first term, how would you do that since the variable pri_termo would be added with razao ? It would be much better, then, to preserve pri_termo and create another variable to change.

If you want, you can even make several improvements to this resolution code. In the example below, the code works without needing a new variable and without changing the value of pri_termo:

pri_termo = int(input('Digite o primeiro Termo: '))
razao = int(input('Digite a Razão da PA: '))
limit = 10

for n in range(limit):
    print('{} --> '.format(pri_termo + (n * razao)), end = '')

Browser other questions tagged

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