Is there any way to use methods within other python methods?

Asked

Viewed 60 times

0

I wonder if in Python it is possible to create a loop for within a format()?

Example

#Considerando:

z=(1,2,3,4)

print(f'''os números pares  foram {
    for i%2==0 in z:
        print(i,end='são números pares')
}''')

I can’t tell if I’m doing this the right way or if I just can’t do it.

2 answers

1


If you want to print everything at once, you can use join along with a Generator Expression:

z = (1,2,3,4)
print(f'os números pares foram: {", ".join(str(i) for i in z if i % 2 == 0)} são números pares')

In the case, the join will use the string ", " to separate the numbers (i.e., they will be written with a comma and space between them). I had to use str to turn numbers into strings, otherwise join makes a mistake.

The result is a string with even numbers, separated by comma and space. This prints:

even numbers were: 2, 4 are even numbers


Of course, depending on the size of the expression, it can get confusing to put everything at once inside the f-string. So it might get less confusing if you do it this way:

z = (1,2,3,4)
pares = ", ".join(str(i) for i in z if i % 2 == 0)
print(f'os números pares foram: {pares} são números pares')

You may have an extra line, but code with fewer lines is not always "best".


Another option is to create a list, like this:

print(f'os números pares foram: {[i for i in z if i % 2 == 0]} são números pares')

Notice the brackets around the for. This will create a list of even numbers, and this list will be printed. The difference is that in this case the output will be:

even numbers were: [2, 4] are even numbers

When printing the list directly, the elements are shown in square brackets. It is still an option, but using join (or any other method that mounts the string before it is printed) you have more control over the desired format.

  • Sorry for not giving any contribution to your answer despite having helped a lot I still don’t have enough reputation :P

  • @Joãogustavo In fact, if the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

  • Interesting guy! Vlw by the link, so taking advantage that the answer was very pertinent I’ll accept now. But on the most general question of methods, can you tell me if it is pertinent or possible?

  • @Joãogustavo To count how many times a number occurs, there is the Counter (if I understand what you’re trying to do). Anyway, it’s like I said, if you have another question, please ask another question - not forgetting to search before, because you already have several questions about Counter on site :-) (unless your doubt is another, of course, I didn’t quite understand if the problem is the count or something else).

  • @Joãogustavo I tell you to ask another question (after researching and making sure there is no such question on the site) to make the site more organized (a question by specific doubt), and also because new questions are visible to everyone on the main page, which increases the chances of having an answer (already here in the comments only I will see)

  • In fact are really different problems that I put on the agenda so I brought the first discussion, but really the chances of being solved is more if I restructure them as different issues on the main page. I’ll do it, thanks there :D.

  • There is also the possibility of using recursive functions. The method is created within a function, where the function can perform itself

  • @Yoyo In the case of this question, I don’t think it makes sense to use recursion...

Show 3 more comments

0

Our guy I used these new ways and it worked really well for me! Thanks too much, by the way I’d also like to know if I could, what would be the cleanest and least cumbersome way to use the code:

(to tell the truth I’m starting and do not know the best ways to write the resolution, so another way to answer my question may be indicating some material on the subject)

1º Using a loop already needed to nest an if and perform the task of extracting even numbers.

c3=p3=c9=0

par=('')

n1=int(input('Digite aqui o 1º valor: '))
n2=int(input('Agora o 2º: '))
n3=int(input('O 3º: '))
n4=int(input('E o 4º: '))

z=(n1,n2,n3,n4)

print(f'você digitou os valores {z}')


for nx in z:

    if (nx/9)==1:
        c9+=1
    
    if (nx/3)==1:
        p3=z.index(3)+1
        c3+=1

    else:
        pass

    if nx%2==0:
        par+=' '+str(nx)+' '

b=par

print(f'o nove apareceu {c9} vezes na tupla')


if p3>1:
    print(f'o número 3 apareceu {p3} vezes na tupla e pela primeira vez no {p3}º espaço na tupla')

elif p3==0:
    print('o valor 3 não apareceu em nenhuma posição')

else:
    print(f'o número 3 apareceu {1} vez na tupla na {p3}º posição')


print(f'os números pares  foram: {b}')

2nd Create a new loop inside my print avoiding another loop above but creating a new loop below.

c3=p3=c9=0

par=('')

n1=int(input('Digite aqui o 1º valor: '))
n2=int(input('Agora o 2º: '))
n3=int(input('O 3º: '))
n4=int(input('E o 4º: '))

z=(n1,n2,n3,n4)

print(f'você digitou os valores {z}')


for nx in z:

    if (nx/9)==1:
        c9+=1
    
    if (nx/3)==1:
        p3=z.index(3)+1
        c3+=1

    else:
        pass


print(f'o nove apareceu {c9} vezes na tupla')


if p3>1:
    print(f'o número 3 apareceu {p3} vezes na tupla e pela primeira vez no {p3}º espaço na tupla')

elif p3==0:
    print('o valor 3 não apareceu em nenhuma posição')

else:
    print(f'o número 3 apareceu {1} vez na tupla na {p3}º posição')


print(f'os números pares  foram: {[nx for nx in z if nx%2==0]}')
  • João, the idea of the site is to have a specific question/problem per question, and that this space be used only for answers (i.e., for solutions to your initial question). If you have any other questions, please ask another question

  • One way to simplify it would be: https://ideone.com/oNC1Fl

  • liked it a lot, gave a simplified in the solution!

Browser other questions tagged

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