logo

Условни изрази в Python

Условните изрази на Python извършват различни изчисления или операции в зависимост от това дали определено булево условие се оценява като вярно или невярно. В Python изразите IF се занимават с условни изрази.

Ще научим как да използваме условни изрази в Python в този урок.

Какво е оператор If на Python?

За да вземате решения, използвайте оператора if в Python. Той има набор от инструкции, които се изпълняват само когато е изпълнено условието на оператора if. Допълнителният оператор else, който включва някои инструкции за оператора else, се изпълнява, ако условието if е невярно.

Изявлението if-else на Python се използва, когато искате да удовлетворите едно изявление, докато другото е невярно.

Синтаксис на Python на израза if:

 if Statement else Statement 

Код

 # Python program to execute if statement a, b = 6, 5 # Initializing the if condition if a > b: code = 'a is greater than b' print(code) 

Изход:

 a is greater than b 

Как да използвам условието else?

Условието „друго“ обикновено се използва, когато се преценява едно твърдение въз основа на друго. Ако условието, споменато в кодовия блок if, е грешно, тогава интерпретаторът ще изпълни кодовия блок else.

Код

 # Python program to execute if-else statement a, b = 6, 5 # Initializing the if-else condition if a <b: code="a is less than b" print(code) else: print('a is greater than b') < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>When the else Statement does not Work</h2> <p>There could be a lot of situations where your &apos;otherwise condition&apos; doesn&apos;t produce the desired outcome. Due to a flaw in the program&apos;s logic, it will print the incorrect result. This typically occurs when there are more than two statements or conditions in a program.</p> <p>An illustration will make this notion easier for you to grasp.</p> <p>Since both variables, in this case, are identical (9, 9), the program&apos;s output that &apos;x is greater than y&apos; is FALSE. This is because it evaluates the first condition, or the if expression in Python, then prints the next condition (the else statement) by default if the first condition fails. The following step will examine how to fix this mistake.</p> <p> <strong>Code</strong> </p> <pre> # Python program when else condition does not work a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>How to use the elif Condition?</h2> <p>We can employ the &apos;elif&apos; clause to fix the issue caused by the &apos;else condition&apos; made earlier. You can instruct the software to print the third condition or alternative when the first two conditions fail or are erroneous by using the &apos;elif&apos; condition.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:></pre></b:></pre></b:>

Когато операторът else не работи

Възможно е да има много ситуации, в които вашето „състояние на противното“ не води до желания резултат. Поради грешка в логиката на програмата, тя ще отпечата неправилния резултат. Това обикновено се случва, когато има повече от два израза или условия в една програма.

Една илюстрация ще улесни възприемането на това понятие.

Тъй като и двете променливи в този случай са идентични (9, 9), изходът на програмата, че „x е по-голямо от y“ е FALSE. Това е така, защото той оценява първото условие или израза if в Python, след което отпечатва следващото условие (инструкцията else) по подразбиране, ако първото условие е неуспешно. Следващата стъпка ще разгледа как да поправите тази грешка.

Код

 # Python program when else condition does not work a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is greater than b </pre> <h2>How to use the elif Condition?</h2> <p>We can employ the &apos;elif&apos; clause to fix the issue caused by the &apos;else condition&apos; made earlier. You can instruct the software to print the third condition or alternative when the first two conditions fail or are erroneous by using the &apos;elif&apos; condition.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:></pre></b:>

Как да използвате условието elif?

Можем да използваме клаузата „elif“, за да коригираме проблема, причинен от „условието else“, направено по-рано. Можете да инструктирате софтуера да отпечата третото условие или алтернатива, когато първите две условия са неуспешни или са грешни, като използвате условието „elif“.

Код

 # Python program to show how to use elif condition a, b = 9, 9 # Initializing the if-else condition if a <b: code="a is less than b" elif a="=" b: else: print(code) < pre> <p> <strong>Output:</strong> </p> <pre> a is equal to b </pre> <h2>Python Nested if Statement</h2> <p>The following example demonstrates nested if Statement Python</p> <p> <strong>Code</strong> </p> <pre> # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> C is the largest number </pre> <hr></b:>

Вложен оператор if на Python

Следващият пример демонстрира вложен if Statement Python

Код

javascript печат
 # Python program to show the nested if-else conditions A = 100 B = 200 C = 300 # Initializing the if-else conditions if B &gt; A: if B &gt; C: print(&apos;B is the largest number&apos;) else: if A &gt; B: if A &gt; C: print(&apos;A is the largest number&apos;) elif C &gt; A: if C &gt; B: print(&apos;C is the largest number&apos;) else: print(&apos;All numbers are equal&apos;) if B % C == 0: if A % C == 0: print(&apos;C is a common factor of A and B&apos;) 

Изход:

 C is the largest number