This is the sixth of Python Tutorials for Beginners. You can see the other Python tutorials in this blog here. This Python beginner tutorial explains the if statement in Python with multiple examples. You can use the if statement to run a block of code depending on a condition. You can write a Python condition using Python comparison operators or Python logical operators. Please view the Python video tutorial 6 or read on...
In Python programming language, the block of code is formed by indenting it by a few spaces, typically 4 spaces. The if statements in Python programming have three formats, the if statement, the if else statement and the if elif else statement. Now let us see these formats with Python examples.
Note : the formats are followed by Python samples
In the first format, the condition is evaluated. If the condition is True, then the code block is run by Python. If the condition is False, nothing happens.
if condition:
code block
# Python code example
# input function request a string from the user
name = input('Enter a name : ')
# len function returns the length of the string, name
if len(name) > 5:
print(name, ' has the length', len(name))
Note : the formats are followed by Python samples
In the first format, the condition is evaluated. If the condition is True, then the code block is run by Python. If the condition is False, nothing happens.
if condition:
code block
# Python code example
# input function request a string from the user
name = input('Enter a name : ')
# len function returns the length of the string, name
if len(name) > 5:
print(name, ' has the length', len(name))