Python is a high-level, interpreted programming language developed by Guido van Rossum in the late 1980s. It is known for its simplicity and versatility, making it an excellent choice for both beginners and experienced programmers. This tutorial will guide you through the basics of Python, from installation to writing your first program.
Why Python?
Ease of Use
- Dynamic Typing: Types are associated with objects, not variables. A variable can be assigned a value of any type.
- High-Level Abstraction: Python operates at a higher level of abstraction, making it easier to write complex programs with fewer lines of code.
- Simple Syntax: Python’s syntax is straightforward, allowing beginners to pick it up quickly while providing depth for experienced developers.
Rapid Application Development
Python allows for rapid application development, often requiring only a fifth of the time compared to other languages.
Readability
Python code is indented to define blocks, which enhances readability. This is in contrast to languages like Perl, where block structures can be less clear.
Expressive Language
Python can express concepts in fewer lines of code compared to languages like Java or C++. For instance, swapping two variables can be done in a single line in Python:
var1, var2 = var2, var1
Extensive Standard Library
Python comes with a comprehensive standard library that supports many common programming tasks, such as connecting to web servers, searching text with regular expressions, and reading and modifying files.
Cross-Platform
Python is cross-platform and runs on Windows, Linux, Unix, and macOS. Versions of Python also run on Java (Jython) and .NET (IronPython).
Supported by Major Companies
Major companies like Google, Rackspace, Industrial Light & Magic, and Honeywell use Python, underscoring its reliability and performance.
When Python Might Not Be the Best Choice
- Execution Speed: Python is not the fastest language because it is interpreted. However, it can be extended with C or C++ modules for performance-critical sections.
- Library Size: While Python has an extensive standard library, it may not be as vast as those of languages like C or Java.
Installing Python
Windows
Python uses an installer. Download it from python.org and follow the installation instructions.
macOS
Python typically comes pre-installed on macOS. To check your version, open the Terminal and type:
python3 --version
Linux
Most Linux distributions come with Python pre-installed. To check your version, open a terminal and type:
python3 --version
Multiple Versions
You can have multiple versions of Python installed on your system. Use virtual environments to manage them effectively.
Running Python Code
Interactive Mode
You can start Python in interactive mode by typing python3
in your terminal or command prompt. This mode is useful for quick tests and experiments.
Script Mode
Write your Python code in a file with a .py
extension, e.g., first.py
, and run it using:
python3 first.py
Integrated Development Environments (IDEs)
IDEs like IDLE, PyCharm, and VSCode provide a more robust environment for writing and debugging Python code.
Basic Syntax and Data Types
Variables
Variables in Python are dynamically typed and can change types. Example:
x = "2"
print(x) # Output: '2'
x = int(x)
print(x) # Output: 2
Data Types
- Integers:
1, -3, 888
- Floats:
3.0, 31e12, -6e-4
- Complex Numbers:
-3 + 2j, -4-2j
- Booleans:
True, False
Lists
Lists are mutable and can contain elements of different types:
x = [1, "two", 3.0, [4, 5]]
print(x[0]) # Output: 1
print(x[-1]) # Output: [4, 5]
Tuples
Tuples are immutable:
y = (1, "two", 3.0)
print(y[0]) # Output: 1
Strings
Strings can be defined using single, double, triple single, or triple double quotes:
s = "Hello, World!"
print(s) # Output: Hello, World!
Dictionaries
Dictionaries provide key-value pair storage:
d = {"key1": "value1", "key2": "value2"}
print(d["key1"]) # Output: value1
Sets
Sets are collections of unique elements:
s = set([1, 2, 3, 1, 3, 5])
print(s) # Output: {1, 2, 3, 5}
Control Flow Structures
If Statements
x = 5
if x < 5:
y = -1
elif x > 5:
y = 1
else:
y = 0
print(y) # Output: 0
While Loops
x = 10
while x > 0:
print(x)
x -= 1
For Loops
for i in range(5):
print(i)
Functions
Functions are defined using the def
keyword:
def add(a, b):
return a + b
print(add(2, 3)) # Output: 5
Exception Handling
Exceptions are handled using try-except
blocks:
try:
x = 1 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
Object-Oriented Programming (OOP)
Python supports OOP:
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
class Circle(Shape):
def __init__(self, x, y, radius):
super().__init__(x, y)
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
c = Circle(0, 0, 5)
print(c.area()) # Output: 78.53975
Modules and Packages
Modules are Python files that contain related code. Packages are directories of modules:
# mymodule.py
def greet(name):
print(f"Hello, {name}")
# main.py
import mymodule
mymodule.greet("World") # Output: Hello, World
Conclusion
Python is a powerful and versatile language that is easy to learn and fun to use. Whether you’re developing web applications, performing data analysis, or automating tasks, Python has the tools you need. Start exploring Python today and see how it can help you achieve your programming goals.