In [1]:
name = "Malcolm"
age = 11
In [2]:
if name == 'Malcolm':
    print("Hi Malcolm")

print("Done")
Hi Malcolm
Done

The expression in an if statement is called a condition. If the expression evaluates to true, the execution enters the indented code that follows. If the condition is false, the execution skips the indented code.

The indented code is called a block. A block is made of lines of code that are indented at a same level. The indentation is what tells python what part is inside the block and what isn't. A block begins when the indentation increases and ends when the indentation returns to it's previous level. Blank lines are ignored.

Blocks are also called as clauses

New blocks begin only after the statements that end with a colon (:).

In [3]:
if name == "Hal":
    print("Hi Hal")

else:
    print("Hello stranger")
Hello stranger
In [4]:
if name == "Hal":
    print("Hi Hal")

elif name == "Malcolm":
    print("Hi Malcolm")

elif age < 13:
    print("Go home kiddo")

else:
    print("Hello stranger")
Hi Malcolm

Only the first elif gets executed, even if the next ones are True.

In [5]:
if name == "Hal":
    print("Hi Hal")

elif age < 13:
    print("Go home kiddo")

else:
    print("Hello stranger")
Go home kiddo
In [6]:
print("Enter a name")
name = input()

if name:
    print("Thank you for entering a name")
else:
    print("You did not enter a name")
Enter a name
Malcolm
Thank you for entering a name
In [7]:
print("Enter a name")
name = input()

if name:
    print("Thank you for entering a name")
else:
    print("You did not enter a name")
Enter a name

You did not enter a name

input() returns a string value, not a boolean True or False value. The reason above code works is because conditions can use Truthy or Falsy values

For strings, a blank string is Falsy value. All other non blank strings are truthy
For integers - 0 is falsy, all other are truthy
For floating points - 0.0 is falsy, all other are truthy

It is better to write the above code in the following way.

In [8]:
print("Enter a name")
name = input()

if name != '':
    print("Thank you for entering a name")
else:
    print("You did not enter a name")
Enter a name

You did not enter a name
In [9]:
print("Enter a name")
name = input()

if name != '':    #if name does not equal the blank string
    print("Thank you for entering a name")
else:
    print("You did not enter a name")
Enter a name
 Malcolm
Thank you for entering a name

bool() function can be used to return equivalent boolean value of whatever is passed inside it

In [10]:
bool(0)
Out[10]:
False
In [11]:
bool(-1)
Out[11]:
True
In [12]:
bool('')
Out[12]:
False
In [13]:
bool('something')
Out[13]:
True
In [14]:
bool()
Out[14]:
False
In [15]:
bool(0.0)
Out[15]:
False
In [16]:
bool(0.2)
Out[16]:
True
In [17]:
bool(232.5352)
Out[17]:
True