🎉 恭喜! 🎉
你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。
老海盗约翰·西尔弗偶然发现了一个被遗弃的箱子,里面放着三件奇异的宝物:一个旧指南针、一张海盗地图和一枚金橡果。海盗想按照价值将它们摆放在船舱的架子上——从最便宜到最昂贵。但他不擅长数学,因此向你求助。
编写一个程序,输入三个整数——三件宝物的价格。程序应确定它们的升序顺序,并将排序后的价格输出到屏幕上。
三个宝藏的价格(整数)。每个数字从新的一行输入。
已排序的宝藏成本(整数)。这些数字按递增顺序在一行中显示,并用空格分隔。
150
25
70
25 70 150
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 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 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.
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.
# Получаем стоимость первого сокровища от пользователя и преобразуем в целое число
treasure1 = int(input())
# Получаем стоимость второго сокровища от пользователя и преобразуем в целое число
treasure2 = int(input())
# Получаем стоимость третьего сокровища от пользователя и преобразуем в целое число
treasure3 = int(input())
# Основной блок условий для определения наименьшего из трёх чисел
# Проверяем, является ли первое сокровище самым дешёвым (или одним из самых дешёвых)
if treasure1 <= treasure2 and treasure1 <= treasure3:
# Если первое сокровище самое дешёвое, сравниваем оставшиеся два
if treasure2 <= treasure3:
# Если второе дешевле третьего, выводим в порядке 1, 2, 3
print(treasure1, treasure2, treasure3)
else:
# Иначе второе дороже третьего, выводим в порядке 1, 3, 2
print(treasure1, treasure3, treasure2)
# Если первое сокровище не самое дешёвое, проверяем, может быть, второе самое дешёвое
elif treasure2 <= treasure1 and treasure2 <= treasure3:
# Если второе сокровище самое дешёвое, сравниваем оставшиеся (первое и третье)
if treasure1 <= treasure3:
# Если первое дешевле третьего, выводим в порядке 2, 1, 3
print(treasure2, treasure1, treasure3)
else:
# Иначе первое дороже третьего, выводим в порядке 2, 3, 1
print(treasure2, treasure3, treasure1)
# Если ни первое, ни второе сокровища не являются самыми дешёвыми, значит, самое дешёвое - третье
else:
# Если третье сокровище самое дешёвое, сравниваем оставшиеся (первое и второе)
if treasure1 <= treasure2:
# Если первое дешевле второго, выводим в порядке 3, 1, 2
print(treasure3, treasure1, treasure2)
else:
# Иначе первое дороже второго, выводим в порядке 3, 2, 1
print(treasure3, treasure2, treasure1)
🎉 恭喜! 🎉
你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。
AD
广告
正在运行代码...