Одновременное выполнение условий питон

Команда if и функция input в Python

В Python существует три команды выбора, которые исполняют код в зависимости от установленных условий, значений которых может быть истинным (True) либо ложным (False).

1. Проверка условий в Python.

Проверка равенств.

Регулярно в программах переменные сравниваются с другими переменными или значениями. Самое простое условия, это проверить равно ли значение переменной конкретному значению.

>>> car = ‘audi’
>>> car == ‘audi’
True

Присвоим переменной car значение ‘audi’. Во второй строке проверим равно ли значение переменной car. Двойной знак равно ( == ) используется для проверки равенства. В итоге Python возвращает значение True , означающий что значения равны. В случае неравенства значений, возвращается False .

>>> car = ‘audi’
>>> car == ‘bmw’
False

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

>>> car = ‘audi’
>>> car == ‘Audi’
False

Проверка неравенства.

Проверка неравенства происходит с помощью восклицательного знака и знака равно ( != ). Восклицательный знак представляет отрицание, как и во многих языках программирования.

>>> car = ‘audi’
>>> car != ‘bmw’
True

1.2. Проверка нескольких условий.

Использование and для проверки нескольких условий.

Для проверки нескольких условий одновременно, используйте ключевое слово and . Чтобы выражение было истинно (True) оба условия должны быть истинны. В примере проверим возраст людей, чтобы был младше или в возрасте 30 лет.

>>> age_1 = 29
>>> age_2 = 20
>>> age_1 True

Если оба условия выполнены, то возвращается True.

Использование or для проверки нескольких условий.

При использовании ключевого слова or , проверка будет истинна если выполнено хотя бы одно условие в выражение. Проверим теперь чтобы хотя бы один из людей был младше 25 лет.

>>> age_1 = 29
>>> age_2 = 20
>>> age_1 < 25 or age_2 < 25
True

2. Функция input() .

  • Функция input() запрашивает данные у пользователя и получает их. Получив данные, сохраняет их в переменной и в последующем вы можете работать с этой переменной.

>>> name = input (‘Как вас зовут? ‘)
Как вас зовут? Ян # вводит пользователь
>>> print(name)
Ян

  • Функция input() всегда возвращает строку. Если мы захотим сложить два числа, то получим не верный ответ. Пример:

>>> a = input (‘Введите число: ‘)
Введите число: 5
>>> b = input (‘Введите число: ‘)
Введите число: 10
>>> a + b
‘510’

Вместо того чтобы сложить 5 и 10 и в итоге получить 15, Python складывает строковое значения ‘5’ и ‘10′, и в итоге получает строку ‘510’. Это операция называется конкатенация строк. В результате создается новая строка из левого операнда, за которым следует правый.

  • Если вам требуется получить целое число, то преобразуйте строку в число с помощью функцииint () :

>>> a = int( input (‘Введите число: ‘))
Введите число: 5
>>> b = int( input (‘Введите число: ‘))
Введите число: 10
>>> a + b
15

Читайте также:  Javascript закомментировать несколько строк

>>> a = float( input (‘Введите число: ‘))
Введите число: 12.5
>>> b = float( input (‘Введите число: ‘))
Введите число: 7.3
>>> a + b
19.8

3.1. Команда if .

Самая простая команда if состоит из одного условия и одного действия.

дествие # отступ в 4 пробела

Приведем пример программы, которая определяет платный ли вход в кинотеатр:

>>> age = 25
>>> if age >= 18 :
. print(‘Вход в кинотеатр для вас платный’)
. print(‘Приобретите билет в кассе’)
.
Вход в кинотеатр для вас платный
Приобретите билет в кассе

В первой строке команды if мы размещаем условия, а во второй строке кода с отступом — практически любое действие. В случае выполнения условия выполняется действие, если условие не выполнено, ничего не происходит.

3.2. Команда if-else .

В случае если необходимо выполнить другое действие если условие ложно, можно воспользоваться командой if-else . Блок if записывается так же, как и раньше, а после него записывается блок else с набором действий в случае невыполнения команды if .

>>> age = 17
>>> if age >= 18 :
. print(‘Вход в кинотеатр для вас платный’)
. print(‘Приобретите билет в кассе’)
. else:
. print(‘Для вас вход бесплатный’)
.
Для вас вход бесплатный

Блок else записывается на уровне блока If , без 4 пробелов.

3.3. Команда if-elif-else .

Команда if-elif-else позволяет проверить сразу несколько условий. Предположим, стоимость билетов кинотеатр изменяется в зависимости от возврата посетителя.

>>> age = 35
>>> if age . print(‘Для вас вход бесплатный’)
. elif age < 18 :
. print(‘Стоимость билета 500 руб’)
. elif age . print(‘Стоимость билета 1000 руб’)
. else:
. print(‘Для вас вход бесплатный’)
.
Стоимость билета 1000 руб

Код выполняется последовательно, программа вначале проверяет соответствие возраста меньше или равно 7 лет, затем < 18 и т.д. Как только условия выполняются, Python выводит результат и действие программы прекращается. Важно ставить правильную последовательность условий. К примеру, если мы поставим условие младше или равно 60 в начало, то возраст меньше 7 и 18 не будет работать и программа сразу выдаст результат максимальной стоимости билета.

Наличие секции else в команде if-elif-else необязательно. Ее присутствие позволяет обработать результат, не удовлетворяющий никаким условиям.

4. Команда if со списками.

С помощью команды if , например при переборе списка, возможно использовать каждый элемент на свое усмотрение.

>>> cars = [ ‘ford’, ‘opel’, ‘audi’, ‘land rover’, ‘bmw’ ]
>>> for brand in cars:
. if brand == ‘audi’ :
. print(f»Гарантия на автомобиль 2 года»)
. elif brand == ‘bmw’ :
. print(f»Гарантия на автомобиль 3 года»)
. else:
. print(f»Гарантия на автомобиль 5 лет»)
.
Гарантия на автомобиль Ford 5 лет
Гарантия на автомобиль Opel 5 лет
Гарантия на автомобиль Audi 2 года
Гарантия на автомобиль Land Rover 5 лет
Гарантия на автомобиль Bmw 3 года

В данном примере с помощью команды for мы перебираем весь список автомобилей. Если марка автомобиля соответствует условия if-elif , то выводится для этих марок свое сообщение по условиям гарантии. В случае не совпадения условий, выдается общее сообщение для всех остальных марок.

Источник

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.

Читайте также:  Php form password check

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.

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.

Источник

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