THEORY AND PRACTICE
-
Input and Output Data
- Tasks
-
Conditions
- Tasks
-
For Loop
- Tasks
-
Strings
- Tasks
-
While Loop
- Tasks
-
Lists
- Tasks
-
Two-Dimensional Arrays
- Tasks
-
Dictionaries
- Tasks
-
Sets
- Tasks
-
Functions and Recursion
- Tasks
Lesson 2. if elif else Structure in python
1. Python conditional operators: basics of operation
Imagine that the program is your assistant who can make decisions. But in order for him to accept them, you must give him clear instructions and conditions. "If it rains, take an umbrella." "If you're hungry, prepare a meal." Conditional operators are the way to teach a program to make such decisions.
Condition in Python: logic and comparison
Any decision is based on a question that can be answered with "Yes" (True) or "No" (False).
In programming, this is called a boolean expression or a condition. The computer
constantly calculates such conditions. For example, 5> 3 is true (True), and 10 == 1 is false (False). The whole work of conditional operators is based on verifying the truth of such expressions.
Syntax of the if statement: conditions in Python
The most important and simplest conditional operator is if (translated as "if"). Its structure is very
simple and logical.
Syntax:
if [condition] : [a block of code that will be executed if the condition is true]
The key points here are the colon (:) after the condition and the mandatory indentation for the code block below it (usually 4 spaces). The indentation shows Python exactly which lines of code relate to
this condition.
2. If operator: Python conditional operator
Let's go deeper into the work if. This operator is the starting point for any branching logic in your
code.
Python condition: working with logic
The condition that you set after if should eventually give either True or False.
This can be the result of comparing numbers, checking a string, or the value of a boolean variable.
is_raining = True
if is_raining:
print("Don't forget to bring an umbrella!")
Examples of using if
Let's take a simple example. Let's check if the number is positive.
temperature = 15
# Check that the temperature is above zero
if temperature > 0:
print("It's a plus on the street.")
# This code will be executed anyway, as it has no indentation
print("Temperature check completed.")
3. The else operator in Python: conditionals
What should I do if the if condition turns out to be false? To do this, there is an operator else (translated as "otherwise").
else assignment in python
The else operator is executed only if the condition in the preceding if was false (False).
He creates a second branch of code execution: "if the condition is true, do this, and in all other cases, do that."
Syntax:
if [condition] : [code block for True]
else: [code block for False]
Examples with else in python
Let's complete our example with temperature.
temperature = -5
if temperature > 0:
print("There's a plus on the street.")
else:
print("It's freezing or zero degrees outside.")
4. if-elif operator: a logical condition
What if we have not two, but three or more scenarios? For example, the temperature can be positive, negative, or zero.
It is inconvenient to use a lot of if. There is an elif for this.
Multiple conditions in Python
elif is short for "else if" ("otherwise if"). It allows you to check several conditions one at a time.
Python checks if, if it is false, it checks the first elif, if it is false, the next elif,
and so on. As soon as one of the conditions turns out to be true, its code block is executed, and all the other elif and else in this chain are ignored. Also, if there is only one line in the condition body, then you can
write it immediately after the colon.
Examples with elif
temperature = 0
if temperature > 0:
print("It's a plus on the street.")
elif temperature < 0:
print("It's freezing outside.")
else:
print("It's exactly zero degrees outside.")
temperature = 14
if temperature > 0:print("It's a plus on the street.")
elif temperature < 0:print("It's freezing outside.")
else:print("It's exactly zero degrees outside.")
5. Python nested conditions: complex constructions
Sometimes, to make a decision, you need to check one condition inside another. This is called nesting.
Python nested conditions: construction and logic
You can put one if/elif/else statement inside another. The main thing is to observe the margins correctly.
Each new level of nesting requires additional indentation.
# Imagine that we have a username and the age of the user
login = "admin"
age = 20
if login == "admin":
print("Welcome, Administrator!")
# Nested age verification
if age >= 18:
print("Access to the control panel is allowed.")
else:
print("Attention! The administrator is too young, access is limited.")
else:
print(f"Welcome, {login}!")
Examples of nested conditions
Let's take an example of a purchase. The discount is given only to VIP clients and only if the purchase amount is more than 1000.
is_vip_client = True
purchase_amount = 1200
if is_vip_client:
print("The client has VIP status. Checking the purchase amount...")
if purchase_amount > 1000:
print("Amount > 1000. Discount applied!")
else:
print("The amount is insufficient for the VIP discount.")
else:
print("The customer is not a VIP. The discount does not apply.")
6. Logical operators in
conditions, the logical operators and, or and not are used to create more complex
and flexible conditions.
Operator and (logical "And")
The and operator returns True only if both conditions on its sides are
true.
age = 25
has_license = True
# To drive a car, you must be over 18 and have a license
if age >= 18 and has_license:
print("You can drive a car.")
else:
print("You can't drive a car.")
Operator or (logical "OR")
The or operator returns True if at least one of the conditions is true.
has_coupon = False
is_sale_day = True
# Discount will be given if there is a coupon OR today is the day of sales
if has_coupon or is_sale_day:
print("You get a discount!")
else:
print("There are no discounts today.")
The not operator (logical "NOT")
The not operator inverts the boolean value: True becomes False, and False becomes True.
is_raining = False
if not is_raining:
print("It's not raining, you can go for a walk without an umbrella.")
Examples of combined conditions
Operators can be combined to create very complex rules.
# Admins are allowed to access the secret file
# or editors, but only if the file is not locked
user_role = "editor"
is_file_locked = False
if user_role == "admin" or (user_role == "editor" and not is_file_locked):
print("Access to the file is allowed.")
else:
print("Access is denied.")
Pay attention to the brackets: they work the same way as in mathematics, defining the order of operations.
7. Comparison operators in Python: comparing values
These are the basic tools for creating conditions.
Equality: ==
Checks whether two values are equal. It is important not to confuse with = (assignment).
Inequality: !=
Checks that two values are not equal.
More: >
Checks that the value on the left is greater than the value on the right.
Less than:
Checks that the value on the left is less than the value on the right.
Is greater than or equal to: >=
Checks that the value on the left is greater than or equal to the value on the right.
Is less than or equal to: <
Checks that the value on the left is less than or equal to the value on the right.
Examples of comparisons
a = 10
b = 5
print(f"a == b: {a == b}") # False
print(f"a != b: {a != b}") # True
print(f"a > b: {a > b}") # True
print(f"a < b: {a < b}") # False
print(f"a >= 10: {a >= 10}") # True
print(f"b <= 5: {b <= 5}") # True
8. Ternary operator (conditional expression)
This is a special, very short way to write a simple if-else construction.
Syntax of the ternary operator
It is used to assign a value to a variable depending on a condition.
Syntax: [Value if any] if [condition] else [value if_false]
Usage examples
Compare two records.
Regular entry:
age = 22
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status)
Using the ternary operator:
age = 22
status = "Adult" if age>= 18 else "Minor"
print(status)
The result is the same, but the notation is much shorter and more elegant for simple cases.
9. Features and errors when working with conditions
Beginners often encounter the same mistakes. Let's take them apart.
Indentation errors (IndentationError)
Python is very strict about indentation. If you forget the indentation after if: or make it incorrect,
you will receive the error IndentationError.
Wrong:
if True:
print("Error!") # There is no indentation
Correct:
if True:
print("That's right!")
Logical errors
This is the most insidious type of error. The code works, it doesn't throw exceptions, but the result is incorrect.
For example, you have confused and >=. The program won't break, but it won't work correctly
for a borderline age (for example, 18 years old). Always check your logic carefully.
Data type errors (TypeError)
Incompatible types, such as string and number, cannot be directly compared.
age = input("Enter your age:") # input() always returns a string
if age > 18: # TypeError: '>' not supported between 'str' and 'int'
print("Error!")
To fix this, you need to explicitly convert the data type using the int(), float(), str() functions.
Correct:
age_str = input("Enter your age:")
age_int = int(age_str) # Converting the string to an integer
if age_int >= 18:
print("Access allowed.")
else:
print("Access denied.")
10. Practical examples
The best way to consolidate knowledge is practice. Here are some classic tasks.
Checking a number for parity
An even number is divisible by 2 without remainder. In Python, the % operator is used to get the remainder
of a division.
number =int(input("Enter an integer:"))
if number % 2 == 0:
print(f"Number {number} is even.")
else:
print(f"Number {number} is odd.")
Determining scores
is an ideal task for if-elif-else.
score =int(input("Enter your score (from 0 to 100):"))
if score == 90:
grade = "A (Excellent)"
elif score == 75:
grade = "B (Good)"
elif score == 60:
grade = "C (Satisfactory)"
elif score == 40:
grade = "D (For retake)"
else:
grade = "F (Unsatisfactory)"
print(f"Your grade: {grade}")
Calculator with operation selection
num1 = float(input("Enter the first number:"))
op = input("Enter the operation (+, -, *, /): ")
num2 = float(input("Enter the second number: "))
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Error: division by zero!"
else:
result = "Incorrect operation!"
print(f"Result: {result}")
Login and password verification
This is a simplified imitation of logging in.
# Passwords are never stored in clear text in real systems!
correct_login = "user123"
correct_password = "password12345"
login = input("Enter login: ")
password = input("Enter password:")
if login == correct_login and password == correct_password:
print("Login completed successfully!")
elif login == correct_login:
print("Invalid password.")
else:
print("User with this username was not found.")