Python Basics
Python Syntax
Learn the core syntax rules of Python including indentation, statements, and Python philosophy.
Python Indentation
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.
Python will give you an error if you skip the indentation.
The number of spaces is up to you as a programmer, the most common use is four spaces, but it has to be at least one.
Python Statements
Python typically has one statement per line, but you can put multiple statements on one line using a semicolon (though this is not recommended).
Python Comments
Python uses the # character to start a comment. Everything after # on the same line is a comment.
Multi-line comments (docstrings) use triple quotes: """..."""
Python is Case Sensitive
Python is case sensitive, which means name and Name are two different variables.
The Zen of Python
Run import this in Python to see the guiding principles of Python's design (PEP 20).
Example
# Indentation defines code blocks
def greet(name):
if name:
message = f"Hello, {name}!"
print(message)
else:
print("Hello, World!")
greet("DevForge") # Output: Hello, DevForge!
greet("") # Output: Hello, World!
# Case sensitive variables
myVar = "Python"
myvar = "JavaScript"
print(myVar) # Python
print(myvar) # JavaScript
# Multi-line docstring
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Args:
width: The width of the rectangle
height: The height of the rectangle
Returns:
The area as a number
"""
return width * height
print(calculate_area(5, 3)) # 15