• 1
    Entrée et sortie
    • Tâches
  • 2
    Conditions
    • Tâches
  • 3
    Boucle for
    • Tâches
  • 4
    Chaînes
    • Tâches
  • 5
    Boucle while
    • Tâches
  • 6
    Listes
    • Tâches
  • 7
    Tableaux 2D
    • Tâches
  • 8
    Dictionnaires
    • Tâches
  • 9
    Ensembles
    • Tâches
  • 10
    Fonctions et récursion
    • Tâches
  • к

Leçon 2. Conditions

Difficulté :

Exercice«Ferme virtuelle»

💻 Python

Le fermier Fyodor a décidé de compter sa ferme et de placer tous les animaux dans trois nouveaux enclos spacieux. La capacité de chaque enclos — Exactement 10 animaux.

Écrivez un programme qui aidera Fedor à déterminer rapidement s'il y a assez de place pour tout le monde. Le programme doit demander au fermier le nombre de vaches, de moutons et de poulets, puis l'informer s'ils peuvent être placés dans les trois enclos. S'il y a de la place, le programme doit également calculer combien de places libres resteront. S'il n'y a pas assez de place, il faut indiquer combien d'animaux n'ont pas eu de place.

Format d entrée

Trois entiers, chacun est saisi sur une nouvelle ligne après l'invitation correspondante.
Premier nombre : le nombre de vaches (entier).

Deuxième nombre : le nombre de moutons (entier).
Troisième nombre : le nombre de poulets (entier).

Format de sortie

deux lignes de texte.
Première ligne : la réponse à la question de savoir s'il est possible de placer des animaux (ligne). Deuxième ligne : le nombre de places libres restantes ou manquantes (ligne).

Exemple

Entrée

5
8
10

Sortie

Oui, tous les animaux peuvent être placés.
Il y aura des places libres : 7

Indice

Nested conditions

You can nest some conditional statements (if) into others to create more complex and multi-level checks. This is useful when the next action depends on several consecutive conditions.

The key point here is the correct indentation (usually 4 spaces), which shows Python which block of code belongs to which condition.

Example:

x = 10

if x > 5:
    print("First check passed: x is greater than 5.")
if x < 20:
        print("Second check passed: x is also less than 20.")
else:
print("Second check failed: x is at least 20.")
else:
print("First check failed: x is less than or equal to 5.")

A useful tip: Try not to create too many nesting levels (3 or more). Deeply embedded code becomes difficult to read and understand. Often, complex nesting can be simplified by using logical operators.

Logical operators

Logical operators in Python are used to combine two or more conditions. They allow you to build complex logic without putting conditions into each other. The main logical operators are and, or and not.

The Name Description
or logical "OR" Returns True if at least one condition is true.
and logical "And" Returns True only if both conditions are true.
not logical "NOT" (negation) Inverts the result: True becomes False and vice versa.

Examples:

a = 5
b = 7

# and: both conditions must be true
s1 = a > 3 and b < 10  # True and True -> True

# or: at least one condition must be true
s2 = a != 5 or b >= 7  # False or True -> True

# not: inverts the result
s3 = not (a < b)       # not (True) -> False

When using and, the result will be true only if both operands are true. When using or, it is sufficient for at least one of the operands to be true. The not operator turns a lie into the truth and vice versa.

Analysis of a complex example:

a, b, c = 7, 10, 11
# Original expression:
print(not(a > 7 and b <= 10) or c != 17)

# Let's take it step by step:
# 1. a > 7  ->  7 > 7  -> False
# 2. b <= 10 -> 10 <= 10 -> True
# 3. (False and True) -> False
# 4. not(False) -> True
# 5. c != 17 -> 11 != 17 -> True
# 6. True or True -> True
# Result: True

A useful tip: To improve readability and avoid errors in complex expressions, always use parentheses () to explicitly specify the order of calculations, even if you remember the precedence of operators (not has the highest priority, then and, then or).

The ternary operator

The ternary operator is a compact way to write a simple if-else condition that returns a value. It allows you to assign a variable a value depending on the condition, and all this in one line.

Syntax: [value if true] if [condition] else [value if false]

Examples:

x = 10
# If x > 5, result will be 100, otherwise 200
result = 100 if x > 5 else 200
print(result) # Will output: 100

y = 20
# Assign the larger of the two values to the variable z
z = x if x > y else y
print(z) # Outputs: 20

# Assign a text value
result_text = "positive" if x > 0 else "non-positive"
print(result_text) # Outputs: positive

A useful tip: The ternary operator is great for simple assignments. However, if the logic becomes more complicated or if, depending on the condition, you need to perform different actions (rather than just return a value), it is better to use a full-fledged if-else construct to preserve the readability of the code.

One-line conditions

If the condition body (if, elif, or else) consists of only one instruction, Python allows you to write it in the same line after the colon.

Example:

x = 10
if x > 5: print("x is greater than 5")

Important style note: Although this notation is syntactically correct, it is often not recommended by the Python Code Style Guide (PEP 8). Placing instructions on a separate line with indentation improves readability and is a generally accepted standard. Use a one-line entry with care, mostly for very simple and obvious actions.

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Solution du développeur
# Запрашиваем у пользователя количество животных каждого вида.
# Функция int() преобразует введенный текст в целое число.
cows = int(input())
sheep = int(input())
chickens = int(input())

# Рассчитываем общее количество животных путем сложения.
total_animals = cows + sheep + chickens

# Определяем общую вместимость всех загонов (3 загона * 10 мест).
total_capacity = 30

# Используем условие if/else для проверки, поместятся ли все животные.
if total_animals <= total_capacity:
    # Этот блок кода выполняется, если общее количество животных меньше или равно вместимости.
    free_space = total_capacity - total_animals # Вычисляем количество свободных мест.
    print("Да, всех животных можно разместить.")
    print("Останется свободных мест:", free_space)
else:
    # Этот блок кода выполняется, если животных больше, чем мест.
    shortage = total_animals - total_capacity # Вычисляем, скольких мест не хватает.
    print("Нет, всех животных разместить нельзя.")
    print("Не хватает мест:", shortage)

🎉 Félicitations ! 🎉

Tu as brillamment résolu la tâche ! C était difficile, mais tu as trouvé la bonne solution. Tu es encore plus proche de maîtriser la programmation ! Continue ainsi.

AD

Publicité

red-snake blue-snake green-snake

Exécution de votre code...

Assistant IA

Bonjour ! Je suis ton assistant de programmation. Pose moi toutes tes questions sur Python — je peux t expliquer les fonctions, les méthodes et t aider avec la tâche en cours !