name = "Malcolm"
age = 11
if name == 'Malcolm':
print("Hi Malcolm")
print("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 (:).
if name == "Hal":
print("Hi Hal")
else:
print("Hello stranger")
if name == "Hal":
print("Hi Hal")
elif name == "Malcolm":
print("Hi Malcolm")
elif age < 13:
print("Go home kiddo")
else:
print("Hello stranger")
Only the first elif gets executed, even if the next ones are True.
if name == "Hal":
print("Hi Hal")
elif age < 13:
print("Go home kiddo")
else:
print("Hello stranger")
print("Enter a name")
name = input()
if name:
print("Thank you for entering a name")
else:
print("You did not enter a name")
print("Enter a name")
name = input()
if name:
print("Thank you for entering a name")
else:
print("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.
print("Enter a name")
name = input()
if name != '':
print("Thank you for entering a name")
else:
print("You did not enter a name")
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")
bool() function can be used to return equivalent boolean value of whatever is passed inside it
bool(0)
bool(-1)
bool('')
bool('something')
bool()
bool(0.0)
bool(0.2)
bool(232.5352)