Python if • Tutorial if else, if elif else (2024)

Video anzeigen

Hier geht's zum Video „Python For-Loop“

Python if einfach erklärt

im Videozur Stelle im Video springen

(00:16)

Mit einem if-Statement in Python gibst du an, was das Programm unter einer bestimmten Bedingung (engl. condition) tun soll. Hierzu verwendest du das Keyword if:

x = 3
if x < 5:
print("x ist kleiner als 5")

Ausgabe:

x ist kleiner als 5

In diesem Beispielüberprüfst du, ob die Variable x kleiner als 5 ist. Falls („if“) das richtig ist, wird „x ist kleiner als 5“ ausgegeben. Ansonsten macht das Programm nichts. Weil 3 kleiner als 5 ist, wird im Beispiel „x ist kleiner als 5“ ausgegeben.

Wichtig! Vergiss bei if in Python nicht den Doppelpunkt nach der if-Bedingung. Außerdem musst du die Zeile danach immer mit der Tab-Taste einrücken, sonst bekommst du eine Fehlermeldung.

Python if elif

Mit elif gibst du eine weitere Bedingung an. Sie wird geprüft, falls die if-Bedingung falsch ist. elifsteht dabei für „else if“.

x = 8
if x < 5:
print("x ist kleiner als 5")
elif x > 5:
print("x ist größer als 5")

Ausgabe:

x ist größer als 5

Im Beispiel ist x = 8. Das ist nicht kleiner als 5. Die if-Bedingung (x < 5) ist also falsch. Deshalb geht das Programm weiter zur elif-Bedingung (x > 5). Die ist richtig. Dein Programm gibt dir also „x ist größer als 5“ aus.

Python if else

Mit else legst du fest, was das Programm tut, falls alle Bedingungen davor falsch sind.

x = 5
if x < 5:
print("x ist kleiner als 5")
elif x > 5:
print("x ist größer als 5")
else:
print("x ist gleich 5")

Ausgabe:

x ist gleich 5

Hier ist x gleich 5. Die if-Bedingung und die elif-Bedingung sind also beide falsch. Deshalb wird das ausgeführt, was unter dem else steht. Du siehst als Ausgabe „x ist gleich 5“.

Du kannst if else in Python auch ohne elif verwenden:

x = 5
if x < 5:
print("x ist kleiner als 5")
else:
print("x ist nicht kleiner als 5")

Ausgabe:

x ist nicht kleiner als 5

Verschiedene Vergleichsoperatoren

Du kannst in if-Bedingungen nicht nur < und > verwenden. Schau dir die wichtigsten Vergleichsoperatoren an:

VergleichsoperatorErklärung
a == bIst a das Gleiche wie b?
a != bIst a nicht das Gleiche wie b?
a < bIst a kleiner als b?
a <= bIst a kleiner oder gleich b?
a > bIst a größer als b?
a >= bIst a größer oder gleich b?

Mit == oder != kannst du nicht nur Zahlen vergleichen, sondern zum Beispiel auch Wörter. Die Aussage „hello“ == „hello“ist zum Beispiel richtig, die Aussage „hello“ == „hallo“ ist falsch.

Achtung! Verwechsle nicht „==“ mit „=“. Das „=“ verwendest du zum Definieren von Variablen. Das „==“ drückt hingegen eine Gleichheit aus.

Python if not

im Videozur Stelle im Video springen

(02:03)

Du kannst auch verneinte Bedingungen verwenden. Schreibe einfach not direkt vor deine Bedingung. Der Code unter dem ifwird dann aufgeführt, wenn die if-Bedingung falsch ist.

x = 8
if not x < 5:
print("x ist nicht kleiner als 5")

Ausgabe:

x ist nicht kleiner als 5

Hier ist x = 8. Das ist offensichtlich nicht kleiner als 5. Die if-Bedingung (x < 5) ist also falsch. Deshalb wird „x ist nicht kleiner als 5“ ausgegeben.

Python if and

im Videozur Stelle im Video springen

(02:16)

Falls dein Programm mehrere Bedingungen erfüllen muss, kannst du das mit dem Befehl if ... and in Python lösen. Der Code unter dem if wird nur ausgeführt, wenn beide Bedingungen richtig sind.

x = 8
if x > 5 and x < 10:
print("x liegt zwischen 5 und 10")

Ausgabe:

x liegt zwischen 5 und 10

Python if or

im Videozur Stelle im Video springen

(02:25)

Beim if ... or in Python wird der Code unter dem if ausgeführt, wenn mindestens eine der Bedingungen richtig ist.

x = 8
if x < 0 or x > 5:
print("x liegt nicht zwischen 0 und 5")

Ausgabe:

x liegt nicht zwischen 0 und 5

Hier ist die erste Bedingung (x < 0) falsch, weil 8 nicht kleiner als 0 ist. Die zweite Bedingung (x > 5) ist aber richtig. Es ist also mindestens eine Bedingung richtig und die Ausgabe ist „x liegt nicht zwischen 0 und 5“.

Python inline if

Du kannst in einem normalen if-Statement in Python auch mehrere Befehleausführen:

x = 3
if x < 5:
print("x ist kleiner als 5")
print("x ist eine einstellige Zahl")

Ausgabe:

x ist kleiner als 5
x ist eine einstellige Zahl

Falls du nur einen einzigen Befehl ausführen möchtest , kannst du die Kurzschreibweise (engl. short hand) benutzen. Hier steht das ganze if-statement in einer Zeile.

x = 3
if x < 5: print("x ist kleiner als 5")

Das funktioniert auch, wennelse dazukommt — allerdings nur, wenn jeweils nur eine Aktion ausgeführt wird. Hier schreibst du das if aber nicht an den Anfang:

x = 3
print("x ist kleiner als 5") if x < 5 else print("x ist nicht kleiner als 5")

Du kannst sogar mehrere if-Statements in eine Zeile schreiben:

x = 3
print("x ist kleiner als 5") if x < 5 else print("x ist größer als 5") if x > 5else print("x ist gleich 5")

Verschachtelte if-Statements

Es ist auch möglich, mehrere if-Statements ineinander zu verwenden (engl. nested if):

x = 3
if x > 0:
print("x ist eine positive Zahl")
if x > 5:
print("x ist größer als 5")
else:
print("x ist nicht größer als 5")

Ausgabe:

x ist eine positive Zahl
x ist nicht größer als 5

Weil x = 3 ist, ist die erste if-Bedingung (x > 0) richtig. Deshalb wird die Aussage „x ist eine positive Zahl“ ausgegeben und die verschachtelte if-Bedingung (x > 5) geprüft. Sie ist falsch. Das Programm geht also weiter zu else und zeigt „x ist nicht größer als 5“.

Python if — häufigste Fragen

  • Was bedeutet elifin Python?
    Elif verwendest du so ähnlich wie if. Der Code unter einer elif-Bedingung wird aber nur abgerufen, wenn die if-Bedingung davor falsch war.
  • Was bedeutet if else in Python?
    Der Befehl if else in Python (deutsch: wenn sonst) ist eine sogenannte konditionelle Verzweigung. Je nachdem, welche Bedingung zu einer bestimmten Laufzeit erfüllt ist, werden unterschiedliche Code-Pfade ausgeführt. If else stellt damit eine grundlegende Kontrollstuktur dar.

for-Schleife

Prima, jetzt hast du die if-Anweisung verstanden! Besonders nützlich können if-Statements sein, wenn du sie mit einem for-Loop kombinierst. Schau dir gleich mal unser Video dazu an!

zur Videoseite: Python If

Beliebte Inhalte aus dem BereichPython

  • Python For-LoopDauer:04:03
  • Python range()Dauer:03:12
  • Python ListeDauer:03:29

zur Videoseite: Python If

Weitere Inhalte:Python

Python Grundlagen

Python IfDauer:04:06
Python For-LoopDauer:04:03
Python range()Dauer:03:12
Python ListeDauer:03:29
Python DictionaryDauer:03:50
Python if • Tutorial if else, if elif else (2024)

FAQs

How do you use Elif if and else in Python? ›

The elif clause in Python

In case else is not specified, and all the statements are false , none of the blocks would be executed. Here's an example: if 51<5: print("False, statement skipped") elif 0<5: print("true, block executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")

What is the difference between if-else and if-elif-else statement? ›

Use if-else statements when the alternatives are mutually exclusive. This means that if one alternative is true, the other alternatives must be false. Use if-elif-else statements when the alternatives are not mutually exclusive. This means that it is possible for more than one alternative to be true simultaneously.

Can we use else if instead of Elif in Python? ›

In Python programming, the “else if” statement, often called “elif,” is a conditional statement that allows you to specify multiple conditions to be evaluated sequentially. It provides a way to execute different code blocks based on various conditions.

Can we use if and elif without else in Python? ›

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

What is the difference between multiple if and if elif in Python? ›

The advantage of an if followed by elif as opposed to two if statements is that the elif (and any subsequent else code blocks) are only executed if the first if condition evaluates as FALSE . Logically the elif can assume the previous if (and previous elif ) statements have evaluated falsely.

Can you use multiple if statements in Python? ›

Yes, you can use multiple if statements sequentially. This is often used to check a series of independent conditions.

What is an example of an if-else statement in Python? ›

Here's a simple example of an if-else statement: age = 18 if age >= 18: print('You are eligible to vote. ') else: print('You are not eligible to vote. ') # Output: # 'You are eligible to vote.

What can I use instead of if-else in Python? ›

There's no need to have the if/else statements. Instead, we can use the boolean values. In Python, True is equal to one , and False is equal to zero .

When to use else if vs if? ›

"else if" statements are meant to be used as an extension of the initial "if" statement. They provide additional conditions to be checked if the initial condition is not met.

When to use nested if-else, and elif statements? ›

We can have multiple "elif" statements after one "if" statement to check multiple conditions. "Nested if" is like having a little "if" inside a bigger "if". We can put one "if" statement inside another "if" statement. The inner "if" statement only runs if the outer "if" statement is TRUE.

What is the difference between if-else and nested if-else? ›

'if' and 'else' statements are required when you need to make a decision based on the result of the condition you are evaluating within an 'if' statement. You can use nested 'if' statements when you want to check for a condition only when a previous dependent condition is true or false.

What are the if-else rules in Python? ›

The Python If-else statement is used to execute both the true and false parts of a condition. If the condition is true, the code within the “If” block is executed. If the condition is false, the code within the “Else” block is executed.

What does == mean in Python? ›

The “==” operator is known as the equality operator. The operator will return “true” if both the operands are equal. However, it should not be confused with the “=” operator or the “is” operator. “=” works as an assignment operator. It assigns values to the variables.

How do you combine if and else in Python? ›

The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed.

What is an example of if-else in Python? ›

Here's a simple example of an if-else statement: age = 18 if age >= 18: print('You are eligible to vote. ') else: print('You are not eligible to vote. ') # Output: # 'You are eligible to vote.

How do you do if and else in one line in Python? ›

The ternary operator is a concise way to write an if-else statement in one line. It has the form `value_if_true if condition else value_if_false`. For example, we can write `result = “pass” if score >= 60 else “fail”` to assign the value “pass” to the variable result if the score is 60 or higher, and “fail” otherwise.

References

Top Articles
The one thing Kamala Harris must not do is embrace the memes
Bernie's Redbird Review: As The Younger Cardinals Take Over, We're Seeing A Team That's Having A Lot More Fun. - Scoops Sports Network
Victor Spizzirri Linkedin
Why Are Fuel Leaks A Problem Aceable
123Movies Encanto
Uhauldealer.com Login Page
122242843 Routing Number BANK OF THE WEST CA - Wise
Repentance (2 Corinthians 7:10) – West Palm Beach church of Christ
Practical Magic 123Movies
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
The Potter Enterprise from Coudersport, Pennsylvania
Sissy Transformation Guide | Venus Sissy Training
Gw2 Legendary Amulet
What's New on Hulu in October 2023
Crime Scene Photos West Memphis Three
Legacy First National Bank
Cvs Devoted Catalog
Mephisto Summoners War
D10 Wrestling Facebook
The Superhuman Guide to Twitter Advanced Search: 23 Hidden Ways to Use Advanced Search for Marketing and Sales
Define Percosivism
Vistatech Quadcopter Drone With Camera Reviews
Joann Ally Employee Portal
SN100C, An Australia Trademark of Nihon Superior Co., Ltd.. Application Number: 2480607 :: Trademark Elite Trademarks
Gilchrist Verband - Lumedis - Ihre Schulterspezialisten
Tokyo Spa Memphis Reviews
Account Now Login In
Enduring Word John 15
Dhs Clio Rd Flint Mi Phone Number
1636 Pokemon Fire Red U Squirrels Download
Summoners War Update Notes
La Qua Brothers Funeral Home
Was heißt AMK? » Bedeutung und Herkunft des Ausdrucks
Play 1v1 LOL 66 EZ → UNBLOCKED on 66games.io
Tamilrockers Movies 2023 Download
Ark Unlock All Skins Command
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
Games R Us Dallas
Raisya Crow on LinkedIn: Breckie Hill Shower Video viral Cucumber Leaks VIDEO Click to watch full…
9781644854013
Claim loopt uit op pr-drama voor Hohenzollern
Fapello.clm
Wordle Feb 27 Mashable
Martha's Vineyard – Travel guide at Wikivoyage
Craigslist/Nashville
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Dying Light Mother's Day Roof
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Haunted Mansion Showtimes Near Millstone 14
Wera13X
Philasd Zimbra
Cognitive Function Test Potomac Falls
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6441

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.