• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 2. Conditions

难度:

任务«驾车旅行»

💻 Python

阿列克谢是一位热爱自驾旅行的车迷。他正在计划下一次长途旅行,并希望确保自己能够在不中途加油的情况下到达第一个大城市。

出发前,他需要弄清楚油箱里的汽油是否足够。请帮助阿列克谢编写一个程序。

已知数据:

  • 他的汽车油耗为每100公里正好 10升 。
  • 为了安全起见,阿列克谢总是在油箱里保留至少 5升 作为备用油量。
  • 编写一个程序,向用户请求两个数值:当前油箱中的油量(升)和到目的地的距离(公里)。程序应分析这些数据,并输出以下两条信息之一:"油量充足,可以出发!" 或 "需要加油..."。

    输入格式

    第一行:油箱当前燃油量(实数,单位:升)。
    第二行:距目的地的距离(单位:公里)。

    输出格式

    一条关于燃料充足性(线路)的消息。

    示例

    输入

    50.0
    400.0

    输出

    燃料充足,你可以出发了!

    提示

    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
    开发者解答
    # Получаем от пользователя текущее количество топлива в литрах и преобразуем в число
    current_fuel = float(input())
    
    # Получаем от пользователя расстояние до цели в километрах и преобразуем в число
    distance = float(input())
    
    # Рассчитываем, сколько литров топлива потребуется на всю дистанцию
    # Расход 10л/100км - это то же самое, что расстояние / 10
    fuel_needed = distance / 10
    
    # Проверяем условие: хватит ли топлива с учетом запаса в 5 литров.
    # То есть, текущее топливо должно быть больше или равно сумме необходимого на поездку и запаса.
    if current_fuel >= fuel_needed + 5:
        # Если топлива достаточно, выводим соответствующее сообщение
        print("Топлива хватит, можно ехать!")
    else:
        # Если топлива недостаточно, выводим другое сообщение
        print("Нужна дозаправка.")

    🎉 恭喜! 🎉

    你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

    AD

    广告

    red-snake blue-snake green-snake

    正在运行代码...

    AI助手

    你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!