Python: The call chain
In this lesson, we'll look at how to combine different approaches when writing code, and we'll also look at common beginner mistakes.
We have the following code:
name = 'Tirion'
print(name.upper().lower()) # => `tirion`He typed `tirion' on the screen.
This is the first time we have seen the syntax of several consecutive dots, but all the operations we encounter here are familiar. This code combines known features of the language.
This happens a lot in programming. If you don't know the syntax, you can still try combining different approaches, and chances are they will work.
To understand how this code works, you need to break down the chain into separate operations:
name = 'Tirion'
upper_name = name.upper() # 'TIRION'
print(upper_name.lower()) # 'tirion'The first and second examples are equivalent. We can perform operations sequentially with intermediate creation of variables, or we can build a continuous chain of attributes and methods. In chains, calculations always go from left to right.
One more example to reinforce:
name = 'Tirion'
print(name.replace('Ti', 'Ki').lower()) # => ?This code needs a lot of thought. .lower() applies to the result of the method call, which is on the left. And the replace() method returns a string. Newbies often make mistakes in method chains and forget to place a call:
name = 'Tirion'
# This code will not work correctly!
print(name.upper.lower())It is also possible to build infinitely long and useless chains that include slices:
# What is the result of such a call?
print(name[1:5].upper().find('I'))This will not work with functions, since they are usually nested inside each other - f(f(f()))). This makes the analysis much worse. But that doesn't mean it can't be done nicely. In other languages, this is implemented through a composition of functions or a pipelining operator.
Instructions
С помощью среза строк получите часть предложения, записанного в переменную text, с 5 по 15 символы включительно. Полученную подстроку обработайте методом .strip() и выведите на экран длину итоговой подстроки. Выполните эти операции подряд в цепочке без создания промежуточных переменных.
Подсказки
- Индексы в срезе начинаются с 0. То есть например 4 символ будет идти под индексом
3. - Первый индекс среза не включается. Например,
text[4:6]вернет, 5 и 6 символы.
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
import importlib
def test(capsys):
expected = "7"
expect_output(capsys, expected)
def expect_output(capsys, expected):
importlib.import_module('solution')
out, _err = capsys.readouterr()
actual = out.strip('\n')
with capsys.disabled():
print('\n')
print(out)
assert actual == expectedTeacher's solution will be available in:
20:00
