Python – branching structures (if else, if, ifelif statements)

The if statement (if) is used to set conditions (if so, then…), for example:

cat_say = ‘mew’

if cat_say = ‘mew’ of cat_say = ‘myavki’:

….print(‘Dear, cat! Here’s your food!’)

Important: when using if conditions, you need to write double equals and put a colon at the end of the expression to show the end of the condition; before the rest of the code related to the condition, and print is indented with a tab (or 4 spaces).

Читать

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

Читать

Python: базовые операторы ввода и вывода текста

Самые первые операции с текстом и базовые сведения о Python, которые помогают тут же начать программировать:

  1. # Comments
  2. Ограничители '' или "" и экранирование символов ' и "
  3. print('Hello world') – переход на новую строку
  4. end='...' – следующий print склеится
  5. escape-последовательности:

    a – системный динамик

    n – переход на новую строку (пустая строка)

    t – отступ типа tab
  6. + сцепление строк без разделителя
  7. * повторение строк без разделителя
  8. продолжение строки кода на следующей строке
  9. input('Press Entr to exit')
  10. Базовые математические операторы (+,-,*,/,//,%).
  11. Составные операторы присвоения
  12. Строковые методы (применяются к строке с текстом): 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: 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

Читать

Программирование: считать с нуля или с единицы…

За основу берем цифру, равную трём

(С трёх удобней всего начинать),

Приплюсуем сперва восемьсот сорок два

И умножим на семьдесят пять.

Льюис Кэрролл «Охота на Снарка»,

Почему программисты считаю с нуля:

Это система, которая пришла из языка C, который долгое время оставался самым популярным языком и стал предком многих ЯП (языков программирования).

Также на западе принято считать с нуля многие вещи, например, этажи в зданиях. Читать

Ошибка Python: inconsistent use of tabs and spaces in indentation

При запуске кода возникает ошибка синтаксиса— inconsistent use of tabs and spaces in indentation. Что это означает и как решить эту проблему? Дело в том, что python следит за соблюдением единообразия в использовании пробелов, которые показывают отступы частей кода. Если вы используете tab, то могут возникнуть сложности, так как часть табов может неверно интерпретироваться в пробелы. В итоге, вы видите ошибку синтаксиса, которую бывает трудно исправить. Читать