Python if condition true false

Lesson 3
Условия: if-then-else

Все программы первого урока выполнялись последовательно, строка за строкой. Никакая строка не может быть пропущена.

Рассмотрим следующую задачу: для данного целого X определим ее абсолютное значение. Если X> 0, то программа должна печатать значение X, иначе оно должно печатать -X. Такое поведение невозможно достичь с помощью последовательной программы. Программа должна условно выбрать следующий шаг. Вот где помогают условия:

x = int(input()) if x > 0: print(x) else: print(-x)

Эта программа использует условный оператор if . После того if мы положим условие (x > 0) следующее двоеточием. После этого мы помещаем блок инструкций, который будет выполняться только в том случае, если условие истинно (т.е. имеет значение True ). За этим блоком может следовать слово else , двоеточие и другой блок инструкций, который будет выполняться только в том случае, если условие является ложным (т.е. имеет значение False ). В приведенном выше случае условие ложно, поэтому выполняется блок «else». Каждый блок должен иметь отступы, используя пробелы.

Подводя итог, условный оператор в Python имеет следующий синтаксис:

if condition : true-block several instructions that are executed if the condition evaluates to True else: false-block several instructions that are executed if the condition evaluates to False 

Ключевое слово else с блоком «false» может быть опущено в случае, если ничего не должно быть сделано, если условие ложно. Например, мы можем заменить переменную x своим абсолютным значением следующим образом:

Отступ является общим способом в Python для разделения блоков кода. Все инструкции в одном и том же блоке должны быть отступом одинаково, т. Е. Они должны иметь одинаковое количество пробелов в начале строки. Для отступов рекомендуется использовать 4 пробела.

Отступ — это то, что делает Python отличным от большинства других языков, в которых фигурные скобки < и >используются для формирования блоков.

Кстати, встроенная функция для абсолютного значения в Python:

Источник

How to Check Multiple Conditions in a Python if statement

Conditional statements are commands for handling decisions, which makes them a fundamental programming concept. They help you selectively execute certain parts of your program if some condition is met. In this article, we’ll tell you all you need to know about using multiple conditional statements in Python. And we’ll show you plenty of examples to demonstrate the mechanics of how it all works.

Читайте также:  Javascript document write asp

Python has a simple and clear syntax, meaning the code is easy to read and interpret. This is especially true for conditional statements, which can almost be read like an English sentence. This makes Python a great language to learn for beginners. For those of you who are new to Python, consider taking our Python Basics course; it will kickstart your programming journey and give you solid foundational skills in Python.

Python if Statement

The starting point for handling conditions is a single if statement, which checks if a condition is true. If so, the indented block of code directly under the if statement is executed. The condition must evaluate either True or False . If you’d like to learn the details of Python’s if statements, you’ll find more in this article on Python terms for beginners. Part 2 of Python Terms for Beginners is also a worthwhile read when you’re just getting started with programming.

The if statement in Python takes the following form:

>>> if condition == True: . print('Condition is True')

Before we go further, let’s take a look at the comparison operators. In Python, there are six possibilities:

Note that the equals comparison operator ( == ) is different from the assignment operator ( = ).

Now let’s try evaluating an example condition:

>>> temperature = 35 >>> temperature > 25 True

Here, we set the variable temperature = 35 . In the next line, we test if this value is greater than 25, which returns the Boolean value True . Now let’s put this in an if statement:

>>> temperature = 35 >>> if temperature > 25: . print('Warm') Warm

The condition evaluates to true, which then executes the indented block ( print(‘Warm’) ). This example is equivalent to writing “If the temperature is greater than 25, print the word “Warm”. As you can see from the code, it’s quite like the written sentence!

Logical Operators

If we want to join two or more conditions in the same if statement, we need a logical operator. There are three possible logical operators in Python:

  • and – Returns True if both statements are true.
  • or – Returns True if at least one of the statements is true.
  • not – Reverses the Boolean value; returns False if the statement is true, and True if the statement is false.
Читайте также:  Parse json php script

To implement these, we need a second condition to test. So, let’s create another variable and test if it’s above a threshold:

>>> temperature = 35 >>> humidity = 90 >>> if temperature > 30 and humidity > 85: . print('Hot and humid') Hot and humid

The or operator requires only one condition to be True . To show this, we’ll reduce the temperature and use the or comparison operator:

>>> temperature = 20 >>> humidity = 90 >>> if temperature > 30 or humidity > 85: . print('Hot, humid, or both') Hot, humid, or both

Notice that or only requires one condition to evaluate to True . If both conditions evaluate to True , the indented block of code directly below will still be executed.

The not operator can seem a little confusing at first, but it just reverses the truth value of a condition. For example:

>>> not True False >>> not False True

We can use it to test if the temperature is colder (i.e. not hotter) that a threshold:

>>> temperature = 15 >>> if not temperature > 20: . print('Cool') Cool

Using these as building blocks, you can start to put together more complicated tests:

>>> temperature = 25 >>> humidity = 55 >>> rain = 0 >>> if temperature > 30 or humidity < 70 and not rain >0: . print('Dry conditions') Dry conditions

This if statement is equivalent to “If temperature is greater than 30 (i.e. evaluates false) OR humidity is less than 70 (evaluates to true) and it’s not raining (evaluates to true) , then write …”. In code, it might look like this:

>>> if False or True and True: . print('Dry conditions') Dry conditions

Python’s if-elif-else Statements

So, what happens when the condition in the if statement evaluates to False? Then we can check multiple conditions by simply adding an else-if statement, which is shortened to elif in Python. Here’s an example using elif to define different temperature categories:

>>> temperature = 25 >>> if temperature > 30: . print('Hot') >>> elif temperature > 20 and temperature 
>>> temperature = 25 >>> if temperature > 30: . print('Hot') >>> elif temperature > 20 and temperature >> else: . print('Cool') Warm

The final else statement handles anything else that does not fall within the other statements. In this case, temperature

If you wanted to make more categories, you could add more elif statements. The elif and else statements are optional. But it’s always good form to finish with an else statement, to make sure anything unexpected is still captured. This can be useful for debugging more complicated conditional statements. For example, if we’re quantifying the amount of rain in millimeters per hour, we could do something like this:

>>> rain = -10 >>> if rain > 0 and rain >> elif rain > 3 and rain >> elif rain > 8: . print('Heavy rain') >>> else: . print('Something unexpected happened!') Something unexpected happened!

Having the final else statement here will alert you if there is an unexpected error somewhere, e.g. a negative value.

Now That You Know Multiple Conditions in Python …

Now you should have all you need to know to start implementing multiple conditional statements in Python. These examples were designed to show you the basics of how these statements work, so take the next step and extend what you’ve learnt here. For example, try combining if-elif-else statements in a loop. Define a list of values, loop through them, and test their values. If you need some background material on for loops in Python, check out How to Write a For Loop in Python.

If you’re interested in learning more about data structures in Python, we’ve got you covered. In Arrays vs. Lists in Python, we explain the difference between those two structures. We also have an article that goes into detail on lists, tuples and sets and another that explains the dictionary data structure in Python. With a bit of practice, you’ll soon master Python’s conditions, loops, and data structures.

Источник

Оцените статью