• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 2. Conditions

Difficulty level:

Task«Park of attractions»

imagine that you work as a programmer in the amusement park "Funny World". Your task & mdash; Write a program that helps the cashier determine which age zone to send the visitor.

rn

in the park are the following distribution rules for zones:

rn
    rn
  • from 0 to 12 years (inclusive) & mdash; & nbsp; children's zone
  • rn
  • from 13 to 17 years old (inclusive) & mdash; & nbsp; teenage zone rn
  • from 18 to 64 years old (inclusive) & mdash; & nbsp; adult zone rn
  • 65 years and older & mdash; & nbsp; zone for the elderly
  • rn
rn

the program must request its age from the user, and then display the name of the corresponding zone.

Input format

The age of the visitor (a whole positive number).

Output format

The name of the area of ​​the amusement park (line).

Example

Input

15

Output

Teenage zone

Hint

Conditions in Python

Conditions in Python allow a program to make decisions based on checking the truth of logical expressions. Imagine that your program has reached a fork in the road: depending on where you need to go, it will choose one of the paths. This is one of the fundamental elements of programming, which allows you to execute different parts of the code depending on different circumstances. In Python, the if, elif and else operators are used to create such "forks".

Syntax

Conditions in Python are defined using the keywords if, elif and else. These operators allow code blocks to be executed depending on whether the expression being checked is true or false.

IMPORTANT! After the condition itself (if condition: or elif condition:) and else is always followed by a colon (:).

if condition:
    # a block of code that will be executed if the condition is true
else:
    # another block of code that will be executed if the condition is false

Indentation in Python is not just a beauty, it's part of the syntax! Unlike many other languages where curly braces {} are used to group code, Python uses indentation (usually 4 spaces) for this purpose. It is the indentation that shows which lines of code belong to if and which to else. All lines within the same block must have the same indentation.

A useful tip: The most common mistake of beginners is mixing spaces and tabs to create indents. This may result in the IndentationError error. Set up your code editor so that it automatically replaces tabs with 4 spaces.

x = 10
if x > 5:
    print("x is greater than 5")  # This code is inside the if block, it will be executed.
    y = x - 5 # And this line is also inside the if block.
    # Nested condition: validation within validation
    if y < 3:
        # This line has even more indentation, it belongs to the nested if.
        print("y is less than 3")
else:
    # This code will be executed only if the condition 'x > 5' is false.
    print("x is not more than 5") 

Basic condition operators

  1. if: Executes a block of code if its condition is true (True). This is the "main" check.
  2. elif: (short for "else if") Checks its condition only if all previous checks if and elif turned out to be false.
  3. else: Executes its code block if all the previous conditions (if and all elif) are false. The else block is optional.

Let's look at some examples.

x = 10
if x > 5: # Condition 10 ;gt; 5 is True.
    print("x is greater than 5") # This code will be executed.

Now the bundle is with else. Only one of the blocks is executed: either if or else.

x = 3
if x > 5: # Condition 3 ;gt; 5 is False.
    print("x is greater than 5") # This block will be skipped.
else:
print("x is not more than 5") # The program will go here and execute this code.

The elif operator allows you to check several conditions in a row. There can be any number of elif blocks. As soon as one of them turns out to be true, the whole construction will be completed.

x = 5
if x > 5: # Condition 5 > 5 is False.
    print("x is greater than 5")
elif x == 5: # Condition 5 == 5 is true.
    print("x is 5") # This block will be completed and the check will end.
else: # The program won't even look here, since the condition in elif has already been fulfilled.
    print("x is less than 5")

A useful tip: The order of the elif matters! Python checks them from top to bottom. Place more specific and rigorous checks above, and more general checks below.

Comparison operators

Comparison operators are used inside conditions to compare two values. The result of their operation is always a boolean value: True (true) or False (false).

  • == Equal to
  • != Not equal to
  • More
  • Less
  • >= Greater than or equal to
  • <= Less than or equal to

A useful tip: Do not confuse the comparison operator == with the assignment operator =! One of the most common mistakes. x = 5 is "putting the value 5 in the variable x". x == 5 is "to ask if the value in x is equal to five?".

x = 10
b = 17
c = 0
print(x > 9)    # True
print(b <= 17)  # True
print(c != 1)   # True
print(x < 110)  # True
print(b == 17)  # True
print(c >= -10) # True

Checking for range membership (comparison chains)

If you need to check whether a number falls within a certain range, Python allows you to do this very gracefully using "comparison chains".

a = 17
# Check that 'a' is in the range from 10 to 100 inclusive.
print(10 <= a <= 100) # True

This is a more readable and pythonic entry than a > = 10 and a <= 100.

# You can build more complex chains.
# This entry verifies that 200 is gt; 17 and 17 is lt; 100.
print(200 > a < 100) # True

Logical operators: and, or, not

It is often necessary to check not one, but several conditions at once. Logical operators are used for this purpose.

  • and (boolean "And"): Returns True only if both conditions are true.
  • or (boolean "OR"): Returns True if at least one of the conditions is true.
  • not (logical "NOT"): Inverts a boolean value (changes True to False and vice versa).
age = 25
has_license = True

# To drive a car, you must be over 18 and have a license.
if age >= 18 and has_license == True:
print("You can drive")

temperature = -5
is_weekend = True

# Let's go for a walk if it's warm outside OR it's a day off.
if temperature > 0 or is_weekend == True:
print("Great day for a walk!")
main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Запрашиваем возраст у пользователя. input() всегда возвращает строку.
age_str = input()

# Преобразуем полученную строку в целое число, чтобы с ним можно было проводить математические сравнения.
age = int(age_str)

# Проверяем, входит ли возраст в диапазон детской зоны (от 0 до 12 лет).
if age >= 0 and age <= 12:
    # Если условие истинно, выводим название соответствующей зоны.
    print("Детская зона")
# Если первое условие ложно, проверяем, входит ли возраст в диапазон подростковой зоны (от 13 до 17 лет).
elif age >= 13 and age <= 17:
    # Если это условие истинно, выводим название этой зоны.
    print("Подростковая зона")
# Если и предыдущие условия ложны, проверяем диапазон взрослой зоны (от 18 до 64 лет).
elif age >= 18 and age <= 64:
    # Если это условие истинно, выводим название взрослой зоны.
    print("Взрослая зона")
# Если ни одно из вышеперечисленных условий не выполнилось, значит, возраст 65 лет или больше.
else:
    # Выводим название последней возможной зоны.
    print("Зона для пожилых")

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!