Python Syntax Overview
Python syntax is simple and easy to read, making it one of the most beginner-friendly programming languages. It follows a clean structure that resembles natural language, allowing developers to write concise and readable code. Below is an overview of Python’s basic syntax.
1. Writing and Executing Python Code
Python code can be written in an interactive shell or saved as a script file (.py) and executed. The Python interpreter reads and executes the code line by line.
Example:
print("Hello, Python!")
Output:
Hello, Python!
Python files are typically saved with the .py extension and executed using:
python filename.py
2. Case Sensitivity
Python is case-sensitive, meaning that variable, Variable, and VARIABLE are treated as different identifiers.
Example:
name = "Alice"
Name = "Bob"
print(name) # Alice
print(Name) # Bob
3. Statements and Expressions
- A statement is a complete instruction in Python.
- An expression is a combination of values and operators that evaluate to a single value.
Example:
x = 5 # Statement
y = x + 10 # Expression
print(y) # 15
4. Comments in Python
Comments are used to annotate code and are ignored by the Python interpreter.
Single-line comment: Uses #
# This is a comment
print("Hello, World!") # This prints a message
Multi-line comment: Uses triple quotes (''' or """)
"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Python is easy to learn!")
5. Line Breaks and Continuation
Python automatically detects the end of a statement when a new line starts. However, if a statement is too long, you can use \ for line continuation.
Example:
total = 5 + 10 + 15 + \
20 + 25
print(total) # 75
For better readability, you can also enclose expressions in parentheses:
total = (5 + 10 + 15 +
20 + 25)
print(total) # 75
6. Quotes in Strings
Python supports single ('), double ("), and triple (''' or """) quotes for string literals.
Example:
print('Hello')
print("Hello")
print('''Hello''')
print("""Hello""")
7. Escape Characters
Escape characters are used to include special characters in a string.
Example:
print("This is a new line\nThis is another line") # \n for newline
print("He said, \"Python is great!\"") # \" to include quotes
Output:
This is a new line
This is another line
He said, "Python is great!"
8. Importing Modules
Python allows importing built-in or custom modules using the import keyword.
Example:
import math
print(math.sqrt(25)) # 5.0
To import specific functions:
from math import sqrt
print(sqrt(25)) # 5.0