Learn Python Fundamental in 30 Days — Day 8(if-else statement)
if Statements
To understand if statement,let see one example
name = "Prashant"
if name == "Prashant":
print ("Hello " + name)Hello Prashant
Here as you can see, if statement starts with a condition, if the condition evaluates to true the indented code block is executed else it just skip the statement.
Indentation is just a Python way to tell which code block is inside if statement and which is not.
So if statement can be used to conditionally execute code depending on whether or not the if statement’s condition is True or False
Now if we change the code, in this case as the condition evaluates to False, it just skips the print block.
name = "Prashant1"
if name == "Prashant":
print ("Hello " + name)
Let’s take a look at if-else statement
name = "Prashant1"
if name == "Prashant":
print("Hello " + name)
else:
print("Hello "+ name)Hello Prashant1
As you can see, if statement is not True so else block is executed. Remember only one block is going to be executed.
Let’s add elif to this list which provides many blocks to be executed. In the case of elif order of elif statement matter as the execution enter the block which is True , it just going to skip rest of the conditions.
An else statement comes at the end. It’s block is executed if all of the previous conditions have been false
name = "Prashant1"
if name == "Prashant":
print("Hello " + name)
elif name == "Lak":
print("Hello "+ name)
else:
print("Hello "+ name)Hello Prashant1
Let’s take a look at one more code
print("Please enter your name")
name = input()
if name:
print("Welcome Back")
else:
print("Who are you")
This is something weird and the reason it will work because of Truthy/Falsey value.Blank string means falsey and others are truthy.
So if we don’t enter anything
Please enter your nameWho are you
In case if I enter value(Prashant)
Please enter your name
Prashant
Welcome Back
In case of integers
- 0 is falsey and all others are truthy
- 0.0 is falsey, all others are truthy
To check this lets pass value to bool() function.
>>> bool(0)False>>> bool(42)True
So this end of Day8, In case if you are facing any issue, this is the link to Python Slack channel https://devops-myworld.slack.com
Please send me your details
* First name
* Last name
* Email address
to devops.everyday.challenge@gmail.com, so that I will add you to this slack channel