🎉 تهانينا! 🎉
لقد حللت المهمة ببراعة! كان صعبًا لكنك وجدت الحل الصحيح. أنت خطوة أقرب إلى الاحتراف! استمر، كل مرحلة تجعلك أقوى.
ProgerLib Python للجميع
تغيير السمة
تخيل أنك تعمل كمبرمج في مدينة الملاهي "Funny World". مهمتك — كتابة برنامج يساعد أمين الصندوق في تحديد المنطقة العمرية التي يجب إرسال الزائر إليها.
في المدينة، توجد قواعد التوزيع التالية للمناطق:
يجب على البرنامج أن يطلب من المستخدم عمره، ثم يعرض اسم المنطقة المناسبة.
عمر الزائر (رقم صحيح موجب).
اسم منطقة مدينة الملاهي (السطر).
١٥
منطقة المراهقين
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".
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")
True). This is the "main" check.if and elif turned out to be false.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 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 toA 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
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
and, or, notIt is often necessary to check not one, but several conditions at once. Logical operators are used for this purpose.
True only if both conditions are true.True if at least one of the conditions is true.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!")
# Запрашиваем возраст у пользователя. 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("Зона для пожилых")
🎉 تهانينا! 🎉
لقد حللت المهمة ببراعة! كان صعبًا لكنك وجدت الحل الصحيح. أنت خطوة أقرب إلى الاحتراف! استمر، كل مرحلة تجعلك أقوى.
AD
إعلان
جارٍ تشغيل الكود...