This was originally published in qubrica.com
Writing Python is easy, but writing clean Python takes practice. In this guide, we’ll break down the essential syntax rules and commenting habits that separate beginners from pros. Let’s clean up your code in less than 5 minutes.
What is Python Syntax?
Syntax defines the rules that determine how Python code must be written. If you break the rules, Python will throw errors.
Python Indentation
Indentation in Python refers to the whitespace (spaces or tabs) used at the beginning of a statement to define the structure and scope of code blocks.
It is mandatory and unique to Python, serving the role that curly braces ({}) serve in other programming languages. Using improper indentation will give an IndentationError.
Indentation is used to define:
The body of a function (def)
The body of a loop (for, while)
The body of a conditional statement (if, elif, else)
The body of a class (class)
The standard convention is to use four spaces for each level of indentation. Consider the example program below which demonstrates the indentation for the code.
def check_number(num):
if num > 0:
# The line below is the body of the if block
print("Positive number found!")
for i in range(num):
# The line below is the body of the for loop
print(f"Loop count: {i + 1}")
else:
print("Number is not positive.")
Python is Case Sensitive for the Variables we Use
In Python variable names, function names and keywords are all case-sensitive.
Consider the example below.
Name = "Jack" # Capital N
name = "John" # Small n
print(Name) # Jack
print(name) # John
Keywords like (if, else, def, class) and names that start with a digit (like 10 or 2a) cannot be used as variables. However built-in functions (like len(), sort()) and Python-defined methods can be used as variable names but doing so is strongly discouraged as it overwrites their original functionality.
Declaring a Variable
x = 10 # integer
y = 3.14 # float
text = "Hello" # string
In Python we don’t need to specify the data type while declaring a variable as it automatically detects the data type.
Python Statements
In python we don’t use semicolons at the end of the statement. Semicolons can be used to write multiple statements in the same line.
print("Hello World") # Hello World
a = 5; b = 10; print(a + b) # 15
Python Comments
Comments are mainly used to explain what the code you write does. It is ignored by the Python interpreter but loved by developers as they are useful to help explain their code. The ‘ # ‘ symbol is used to write a comment.
There are two types of comments in Python.
Single Line Comment: They use the ‘ # ‘ symbol and used to write comments in a single line.
Multi-Line Comments: Multi-line comments are written by using triple quotes.
# This is a single-line comment
print("Hello Python!")
for more information, code tutorials and FAQs you can visit qubrica syntax and comments tutorial
Top comments (1)
Be open to give your feedback or doubts.