if….else statement | Python Flow Control
Flow control is one of the important aspects of any programming language. In this article, we will learn to make decisions in a Python program using different forms of if….else statement. When we want to execute our code block if and only if a certain condition is matched, we use decision-making statements.
Python if Statement Flowchart
Python if Statement syntax
if test expression:
statement(s)
Here, the program evaluates test expression
True
if
Example:
name = "Pumpkin" if name != "": print("Hello "+ name);
Output:
Hello Pumpkin
Python if…else Statement flowchart
Python if….else statement syntax
if test expression:
Body of if
else:
Body of else
Here, the program evaluates test expression
True
Example:
def greet(): if name != "": print("Hello "+ name) else: print("Hello world!!") name = "Pumpkin" greet() name = "" greet()
Output:
Hello Pumpkin
Hello world!!
Python if…elif….else Statement flowchart
Python if…elif….else Statement Syntax
if test expression:
Body of ifelif test expression1:
Body of elif
else:
Body of else
Here, the program evaluates the test expression
and will execute Body of if only if the text expression is True
test expression
test expression1
test expression1
True
Example:
def greet(): if name != "" and name != "Dipen": print("Hello "+ name) elif name == "Dipen": print("Hey dude!!!") else: print("Hello world!!") name = "Pumpkin" greet() name = "Dipen" greet() name = "" greet()
Output:
Hello Pumpkin
Hey dude!!!
Hello world!!
We can also have if….elif….else statement inside another if….elif….else statement. We can have any number of nesting of these statements.
That's it for if, if…else, if….elif….else statements in python. In the next article, we will see for loop in python.
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate â‚ą42 per Tree.
About the Author
Tags: python, Python Flow Control
Comments and Queries
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.