The Origins of Python
Python was created by Guido van Rossum in late 1989 as a personal project to occupy his time during the holiday season. Designed as a successor to the ABC programming language, Python has evolved into a powerhouse in modern software development, consistently ranking among the top programming languages globally.
Why Python?
Python's popularity stems from its extensive standard library and concise syntax. While languages like C are compiled directly into machine code for hardware execution, Python utilizes an interpreter and bytecode architecture. Although Python may execute slower than lower-level languages like C, it significantly reduces development time by requiring far fewer lines of code to implement complex logic.
Python Implementations
Several implementations of Python exist to cater to different environments:
- CPython: The reference implementasion written in C, which compiles code into
.pycbytecode for the Python Virtual Machine. - Jython: Compiles Python code into Java bytecode to run on the Java Virtual Machine (JVM).
- IronPython: Designed for integration with the .NET framework, running on the Common Language Runtime (CLR).
- PyPy: A high-performance implementation that uses Just-In-Time (JIT) compilation to convert bytecode into machine code.
Writing and Executing Python
You can execute a Python script by invoking the interpreter directly:
python script_name.py
Alternatively, you can make a script executable by adding a "shebang" line at the top of your file:
#!/usr/bin/env python3
print("Hello, World!")
Handling Character Encoding
By default, Python source files are treated as ASCII. To use special characters or non-Latin scripts (like Chinese), you must specify the file encoding at the top of your script:
# -*- coding: utf-8 -*-
Variables and Input
Python uses dynamic typing for variables. You can assign values simply:
user_name = "developer"
To capture user input, use the input() function. For sensitive information like passwords, the getpass module is recommended:
import getpass
secret = getpass.getpass("Enter password: ")
Basic Data Types
- Numeric: Includes
int,float, andcomplexnumbers. - Strings: Sequences of characters. String interpolation is handled via format specifiers:
print("User: %s" % user_name). - Lists: Ordered, mutable collections, e.g.,
items = ['a', 'b', 'c']. - Tuples: Immutable ordered sequences, e.g.,
coordinates = (10, 20). - Dictionaries: Unordered key-value pairs, e.g.,
data = {'key': 'value'}.
File I/O
Python provides a built-in open() function to handle files. It is best practice to iterate through files line-by-line to manage memory usage efficiently:
with open("log.txt", "r") as file_handle:
for line in file_handle:
print(line.strip())