When running the code, a syntax error occurs – inconsistent use of tabs and spaces in indentation. What does this mean and how to solve this problem? The fact is that python enforces uniformity in the use of spaces, which show the indentation of parts of the code. If you use tab, it can get tricky because some of the tabs can be misinterpreted as spaces. As a result, you see a syntax error that can be difficult to fix. Читать
Архив метки: Python
Python: for loops, constants, slices, tuples, sequences len, range, in, choice
We continue to learn the programming language. Let’s move on to chapter 4 of the book: Michael Dawson “Python Programming”, 2014 (Michael Dawson “Python Programming for the Absolute Beginner”, 3rd Edition), where we will study loops with the for () operator, introducing constants into code, slices and tuples, working with sequences on the example of strings with the operators len(), range(), in, jumble(), etc.
Summary of chapter 4 with examples of programs I wrote:
Содержание:
Cycles (loops) for
We already know loops with the while statement, and have even done a lot of tasks. Remember, there is a control variable introduced before the loop, which is then used in the condition, which in turn is tested for truth every round of the loop. So with the for loop, things are a little different. Читать
Python: Basic Text Input and Output Operators
The very first text operations and basic information about Python that helps you start programming right away:
# Comments
Delimiters ” or “” and escaping characters ’ and ”
print(‘Hello world’) – newline
end=’…’ – next print will be glued
escape sequences:
a – system speaker
n – newline (empty line)
t – tab type indent
+ string concatenation without delimiter
* repeat lines without delimiter
continuation of a line of code on the next line
input(‘Press Enter to exit’)
Basic mathematical operators (+,-,*,/,//,%).
Compound assignment statements
String methods (applied to a string with text): I am cat
.upper() I Am CAT
.lower() i am cat
.title() I Am Cat
.replace(old,new,max number of replacements) replaces the old text with the new one
.swapcase() reverse case i Am Cat
.capitalize() the first letter is capital, the rest are lowercase I am cat
.strip() string without intervals Iamcat
Python: базовые операторы ввода и вывода текста
Самые первые операции с текстом и базовые сведения о Python, которые помогают тут же начать программировать:
# Comments- Ограничители
''или""и экранирование символов'и" - p
rint('Hello world')– переход на новую строку end='...'– следующий print склеитсяescape-последовательности:
a– системный динамик
n– переход на новую строку (пустая строка)
t– отступ типа tab+сцепление строк без разделителя*повторение строк без разделителяпродолжение строки кода на следующей строкеinput('Press Entr to exit')- Базовые математические операторы (
+,-,*,/,//,%). - Составные операторы присвоения
- Строковые методы (применяются к строке с текстом): I am cat
.upper()I Am CAT
.lower()i am cat
.title()I Am Cat
.replace(old,new,max число замен)заменяет старый текст на новый
.swapcase()меняет регистры наоборот i Am Cat
.capitalize()первая буква большая, остальные строчные I am cat
.strip()строка без интервалов Iamcat
Python – Boolean Operators and Conditions
Basic conditions in Python:
< (one less than the other)
> (one more than the other)
<= (one is less than or equal to the other)
>= (one is greater than or equal to the other)
!= (one is not equal to the other)
== (one is equal to the other)
Examples of using conditions:
print(5 > 4)
True #result
print(‘cat’==’dog’)
False #result
Программирование: считать с нуля или с единицы…
За основу берем цифру, равную трём
(С трёх удобней всего начинать),
Приплюсуем сперва восемьсот сорок два
И умножим на семьдесят пять.
Льюис Кэрролл «Охота на Снарка»,
Почему программисты считаю с нуля:
Это система, которая пришла из языка C, который долгое время оставался самым популярным языком и стал предком многих ЯП (языков программирования).
Также на западе принято считать с нуля многие вещи, например, этажи в зданиях. Читать