Python Programming Guide
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability.
Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes
code readability and simplicity, making it an ideal choice for beginners and experienced developers
alike.
Installing Python
Python can be installed from the official website (https://www.python.org/). Here are the steps for
installation:
For Windows:
1. Download the Python installer from the official website.
2. Run the installer and follow the instructions.
3. Add Python to PATH during the installation process.
For macOS:
1. Install Homebrew if not already installed (/bin/bash -c "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)").
2. Use Homebrew to install Python: brew install python.
For Linux:
1. Open the terminal.
Python Programming Guide
2. Use the package manager to install Python. For example, on Ubuntu, use sudo apt-get install
python3.
Basic Syntax and Variables
Hello World in Python:
```python
print("Hello, World!")
```
Variables:
```python
x = 10
y = "Hello"
z = 3.14
```
Control Structures
If-Else Statement:
```python
if x > 5:
print("x is greater than 5")
else:
Python Programming Guide
print("x is 5 or less")
```
For Loop:
```python
for i in range(5):
print(i)
```
While Loop:
```python
while x > 0:
print(x)
x -= 1
```
Functions
Defining and Calling Functions:
```python
def greet(name):
return f"Hello, {name}"
print(greet("Alice"))
```
Python Programming Guide
Modules and Packages
Importing Modules:
```python
import math
print(math.sqrt(16))
```
Creating a Module:
Create a file named mymodule.py:
```python
def add(a, b):
return a + b
```
Using the Module:
```python
import mymodule
print(mymodule.add(2, 3))
```
File Handling
Python Programming Guide
Reading a File:
```python
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
Writing to a File:
```python
with open('example.txt', 'w') as file:
file.write("Hello, World!")
```
Error and Exception Handling
Try-Except Block:
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
```
Object-Oriented Programming
Python Programming Guide
Defining a Class:
```python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} is barking"
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
```
Libraries and Frameworks
Popular Python Libraries:
- NumPy: Used for numerical computations.
- Pandas: Used for data manipulation and analysis.
- Matplotlib: Used for plotting graphs and charts.
- Django: A web framework for building web applications.
- Flask: A lightweight web framework.