I am self learning python and I was doing an exercise, the solution to which was posted in this thread. Could anyone translate into english what this piece of code means? When I learned if statements I never came across this syntax.
consonants = 'bcdfghjklmnpqrstvwxz'
return ''.join(l + 'o' + l if l in consonants else l for l in s)
Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn’t yet been bound into a function. Though code objects represent some piece of executable code, they are not, by themselves, directly callable.
Conditional Statements Exception Handling Dictionaries Modules Taking Input From The User Download and Install Python Python is a interpreted language which means that the code is translated (interpreted) to binary code while the program runs. That is different from compiled languages (C++ etc.) where the code is first compiled to binary code.
Taking Input From The User Download and Install Python Python is a interpreted language which means that the code is translated (interpreted) to binary code while the program runs. That is different from compiled languages (C++ etc.) where the code is first compiled to binary code. To run Python code you need to have a Python interpreter.
List comprehensions in Python are super helpful and powerful. They reduce the code length to a great length and make it more readable. In the following code, we can see that we are checking multiples of 6, and then multiples of 2 and 3 using the if-else conditions inside the list, which reduced the code to a great extent.
It's a longer piece of code, written as a generator. Here is what it would look like, more drawn out.
consonants = 'bcdfghjklmnpqrstvwxz'
ls = []
for l in s:
if l in consonants:
ls.append(l + 'o' + l)
else:
ls.append(l)
return ''.join(ls)
It loops through s
and checks if l
is in the string consonants
. If it is, it pushes l + 'o' + l
to the list, and if not, it simply pushes l
.
The result is then joined into a string, using ''.join
, and returned.
More accurately (as a generator):
consonants = 'bcdfghjklmnpqrstvwxz'
def gencons(s):
for l in s:
if l in consonants:
yield l + 'o' + l
else:
yield l
return ''.join(gencons(s))
Where gencons
is just a arbitrary name I gave the generator function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With