• 1
    डेटा I/O
    • कार्य
  • 2
    शर्तें
    • कार्य
  • 3
    for लूप
    • कार्य
  • 4
    स्ट्रिंग
    • कार्य
  • 5
    while लूप
    • कार्य
  • 6
    सूचियां
    • कार्य
  • 7
    2D मैट्रिक्स
    • कार्य
  • 8
    डिक्शनरी
    • कार्य
  • 9
    सेट
    • कार्य
  • 10
    फ़ंक्शन
    • कार्य
  • к

पाठ 2. Conditions

कठिनाई:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

कार्य«इंटरनेट खरीदारी»

💻 Python

आप कॉसमॉस ऑनलाइन स्टोर के कैश डेस्क के लिए एक प्रोग्राम बनाते हैं। स्टोर में खरीदारों के लिए विशेष ऑफ़र हैं।

rn

ऑफ़र के नियम:

rn
  • यदि खरीद राशि 5,000 रूबल से सख्ती से अधिक है, तो खरीदार को पूरी राशि पर 15% की छूट मिलती है।
  • rn
  • यदि खरीदारी छुट्टी के दिन (शनिवार या रविवार) की जाती है, तो खरीदार के लिए डिलीवरी मुफ्त हो जाती है। कार्यदिवसों पर, डिलीवरी का भुगतान किया जाता है।
  • rn rn

    आपका कार्य & mdash; एक प्रोग्राम लिखना जो उपयोगकर्ता से खरीद राशि और सप्ताह का दिन मांगे। प्रोग्राम को संभावित छूट को ध्यान में रखते हुए अंतिम लागत की गणना करनी चाहिए और यह निर्धारित करना चाहिए कि डिलीवरी का भुगतान किया जाएगा या मुफ्त होगी।

    इनपुट फॉर्मेट

    पहली पंक्ति: खरीद राशि (सामग्री संख्या)।
    दूसरी पंक्ति: सप्ताह का दिन (पंक्ति)।

    आउटपुट फॉर्मेट

    पहली पंक्ति: छूट को ध्यान में रखते हुए अंतिम राशि (पंक्ति)।
    दूसरी पंक्ति: डिलीवरी की जानकारी।

    उदाहरण

    इनपुट

    6000
    शनिवार

    आउटपुट

    अंतिम राशि: 5100.00 रूबल
    डिलीवरी: मुफ्त

    संकेत

    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
    परीक्षण 1
    परीक्षण 2
    परीक्षण 3
    परीक्षण 4
    परीक्षण 5
    परीक्षण 6
    परीक्षण 7
    परीक्षण 8
    परीक्षण 9
    परीक्षण 10
    डेवलपर का समाधान
    # Запрашиваем у пользователя сумму покупки и преобразуем ее в вещественное число
    purchase_amount = float(input())
    
    # Запрашиваем у пользователя день недели и приводим его к нижнему регистру для удобства сравнения
    day_of_week = input().lower()
    
    # Создаем переменную для итоговой суммы, изначально она равна сумме покупки
    final_amount = purchase_amount
    
    # Проверяем первое условие: сумма покупки больше 5000
    if purchase_amount > 5000:
        # Если условие истинно, рассчитываем скидку 15% и вычитаем ее из итоговой суммы
        final_amount = purchase_amount * 0.85 # 100% - 15% = 85%
    
    # Проверяем второе условие: день недели - суббота или воскресенье
    if day_of_week == "суббота" or day_of_week == "воскресенье":
        # Если условие истинно, доставка бесплатная
        delivery_info = "Доставка: бесплатно"
    else:
        # Если условие ложно (любой другой день), доставка платная
        delivery_info = "Доставка: платная"
    
    # Выводим итоговую сумму, отформатированную до двух знаков после запятой
    print(f"Итоговая сумма: {final_amount:.2f} руб.")
    
    # Выводим информацию о доставке
    print(delivery_info)

    🎉 बधाई! 🎉

    आपने कार्य को शानदार ढंग से हल किया! यह कठिन था, लेकिन आपने सही उत्तर खोजा। आप प्रोग्रामिंग में महारत के करीब हैं! ऐसे ही जारी रखें।

    AD

    विज्ञापन

    red-snake blue-snake green-snake

    कोड चल रहा है...

    AI सहायक

    नमस्ते! मैं आपका प्रोग्रामिंग सहायक हूँ। Python के बारे में कोई भी सवाल पूछें — मैं functions, methods समझा सकता हूँ और मौजूदा task में मदद कर सकता हूँ!