Архив рубрики: Публикации

Python – тернарный условный оператор (if, or, else)

Тернарный оператор (Ternary operator) – используется в строчку для задания условий в присваивании значения переменной. Легче это понять на примерах.

cat_say = “Mew”

me_say = “Hi,cat” if cat_say == “Mew” or cat_say == “Myavki” else “Who are you?”

print(me_say)

Hi,cat #результат

Тернарный оператор по сути включает в себя имя переменной, которой мы присваиваем значение и внутри этой же строки задаем условия, описываемые операторами if/or/else. Не обязательно использовать все три if/or/else оператора, в условии может использоваться просто if/else.

Важно: тернарный условный оператор в Python может использоваться как со строками, так и с числами.

Все уроки по Python


Python – ternary conditional statement (if, or, else)

Ternary operator (Ternary operator) – used in line to set conditions in assigning a value to a variable. It is easier to understand this with examples.

cat_say = “Mew”

me_say = “Hi,cat” if cat_say == “Mew” or cat_say == “Myavki” else “Who are you?”

print(me_say)

Hi,cat #result

The ternary operator essentially includes the name of the variable to which we assign a value and inside the same line we set the conditions described by the if / or / else statements. It is not necessary to use all three if/or/else statements, just if/else can be used in the condition.

Important: The ternary conditional operator in Python can be used with both strings and numbers.


Python: типы данных и функция input()

В языке программирования Python есть несколько типов данных, например:

  • целые числа int(x), например, 1-2-3-4;
  • дробные числа float(x), например, 1.0-2.0-3.5;
  • строки str(x), в которых может быть текст и другие символы.

Функция input() уже обсуждалась ранее, эта функция дает возможность пользователю вводить данные в программу, эти данные могут дальше использоваться. Читать

Python: циклы for, константы, срезы, кортежи, последовательности len, range, in, choice

Продолжаем учить язык программирования. Переходим к изучению 4 главы по книге: Майкл Доусон “Программируем на Python”, 2014 (Michael Dawson “Python Programming for the Absolute Beginner”, 3rd Edition), где мы изучим циклы с оператором for(), введение констант в код, срезы и кортежи, работу с последовательностями на примере строк с операторами len(), range(), in, jumble() и т.д.

Конспект 4 главы с примерами написанных мной программ:

Циклы for

Мы уже знаем циклы с оператором while, и даже сделали много задач. Помните, там вводится перед циклом управляющая переменная, которая затем используется в условии, которое в свою очередь проверяется на истинность каждый круг цикла. Так вот с циклом for все немного иначе. Читать

Python – programming environment and additional programs

When you have installed Python, the question arises – how to start learning this language? Should I write commands through the console or do I need to install something else on the computer? There are many programming environments and solutions for Python, but for a beginner, it is preferable to choose from two:

  • if you are learning Python for scientific purposes, then download Anaconda from www.continuum.io/downloads – this environment already includes Python, as well as such useful programs for programming and analytics as Spyder, Jupyter, IPython, R and others.
  • you are learning Python for general development, then install the cool Sublime Text code editor from sublimetext.com; in this case, you will need to manually configure the Python interpreter to run the program written in this editor.

Читать

Python – show result to user

When we write any program in any programming language, sooner or later we want the result of our programming to be shown to the user. For this we use the command:

print(…) must be lowercase

Читать