Python is a high-level, interpreted, general-purpose programming language.
Created
by Guido van Rossum and first released in 1991, Python's design philosophy
emphasizes code readability with its notable use of significant indentation. It is
dynamically typed and garbage-collected, supporting multiple programming paradigms,
including structured (particularly procedural), object-oriented, and functional
programming.
Key features of Python include:
* **Simplicity and Readability:** Python's syntax is designed to be clear and
intuitive, making it easy to learn and read.
* **Versatility:** It's used for web development, data analysis, artificial
intelligence, machine learning, scientific computing, automation, and more.
* **Large Standard Library:** Python comes with a vast collection of modules and
packages, providing ready-to-use functionalities for various tasks.
* **Cross-platform Compatibility:** Python code can run on various operating
systems like Windows, macOS, and Linux without modification.
* **Interpreted Language:** Python code is executed line by line, which can
simplify debugging.
* **Dynamic Typing:** You don't need to declare the type of a variable; Python
determines it at runtime.
* **Extensible:** Python can be extended with modules written in C or C++.
This tutorial will guide you through the fundamentals of Python programming.
### 1. Setting Up Python
To start coding in Python, you need to install it on your system.
**A. Download the Installer:**
Visit the official Python website
([[Link] and
download the latest stable version for your operating system.
**B. Installation Steps:**
* **Windows:**
1. Download the executable installer (`.exe` file).
2. Run the installer. **Crucially, ensure you check the box that says "Add
Python X.X to PATH"** during installation. This will make it easier to run Python
from the command line.
3. Follow the on-screen instructions to complete the installation.
* **macOS:**
1. Download the macOS installer (`.pkg` file).
2. Open the downloaded file and follow the installation prompts.
3. Python is often pre-installed on macOS, but it's usually an older version.
Installing from the official website provides the latest version.
* **Linux:**
1. Python is typically pre-installed on most Linux distributions. You can
check its version by typing `python3 --version` in your terminal.
2. If you need a newer version or it's not installed, you can usually install
it using your distribution's package manager (e.g., `sudo apt-get install python3`
on Debian/Ubuntu, `sudo yum install python3` on Fedora/RHEL).
**C. Verify Installation:**
Open a command prompt or terminal and type `python --version` or `python3 --
version`. You should see the installed Python version displayed.
### 2. Your First Python Program: "Hello, World!"
Let's write a classic "Hello, World!" program.
1. Create a new file named `[Link]`.
2. Add the following code:
```python
print("Hello, World!")
```
3. Open your terminal or command prompt, navigate to the directory where you saved
`[Link]`, and run:
```bash
python [Link]
```
You should see `Hello, World!` printed to the console.
**Explanation:**
* `print()`: This is a built-in Python function used to display output to the
console.
* `"Hello, World!"`: This is a string literal, which is a sequence of characters
enclosed in double quotes.
### 3. Variables and Data Types
Variables are used to store data in a program. Python is dynamically typed, meaning
you don't need to declare the variable's type explicitly; it's inferred at runtime.
**A. Declaring Variables:**
You declare a variable by assigning a value to it.
```python
name = "Alice" # A string variable
age = 30 # An integer variable
height = 1.75 # A float variable
is_student = True # A boolean variable
```
**B. Basic Data Types:**
* **Numbers:**
* **Integers (`int`):** Whole numbers (e.g., `5`, `-100`, `0`).
* **Floating-point numbers (`float`):** Numbers with decimal points (e.g.,
`3.14`, `-0.5`, `2.0`).
* **Complex numbers (`complex`):** Numbers with a real and imaginary part
(e.g., `1 + 2j`).
* **Strings (`str`):** Sequences of characters, enclosed in single or double
quotes (e.g., `'hello'`, `"Python"`).
* **Booleans (`bool`):** Represents truth values, either `True` or `False`.
* **Lists (`list`):** Ordered, mutable (changeable) collections of items.
Enclosed in square brackets `[]`.
```python
fruits = ["apple", "banana", "cherry"]
```
* **Tuples (`tuple`):** Ordered, immutable (unchangeable) collections of items.
Enclosed in parentheses `()`.
```python
coordinates = (10, 20)
```
* **Dictionaries (`dict`):** Unordered, mutable collections of key-value pairs.
Enclosed in curly braces `{}`.
```python
person = {"name": "Bob", "age": 25}
```
* **Sets (`set`):** Unordered collections of unique items. Enclosed in curly
braces `{}`.
```python
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
```
### 4. Operators
Operators are symbols that perform operations on values and variables.
* **Arithmetic Operators:** `+`, `-`, `*`, `/` (division), `%` (modulo), `**`
(exponentiation), `//` (floor division).
* **Comparison Operators:** `==` (equal to), `!=` (not equal to), `>` (greater
than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal
to).
* **Logical Operators:** `and`, `or`, `not`.
* **Assignment Operators:** `=`, `+=`, `-=`, `*=`, `/=`, etc.
* **Identity Operators:** `is`, `is not` (check if two variables refer to the
same object in memory).
* **Membership Operators:** `in`, `not in` (check if a value is present in a
sequence).
### 5. Control Structures
Control structures dictate the flow of your program's execution. Python uses
indentation to define code blocks.
**A. If-Elif-Else Statements:**
```python
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
else:
print("Grade F")
```
**B. For Loops:**
Used for iterating over a sequence (like a list, tuple, string, or range).
```python
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating using range()
for i in range(5): # Generates numbers from 0 to 4
print(i)
# Iterating over a dictionary
person = {"name": "Bob", "age": 25}
for key, value in [Link]():
print(f"{key}: {value}")
```
**C. While Loops:**
Executes a block of code repeatedly as long as a condition is true.
```python
count = 0
while count < 5:
print(count)
count += 1 # Increment count
```
**D. `break` and `continue`:**
* `break`: Terminates the loop entirely.
* `continue`: Skips the rest of the current iteration and proceeds to the next.
```python
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Exit loop at 7
print(i) # Output: 0, 1, 2, 4, 5, 6
```
### 6. Functions
Functions are reusable blocks of code that perform a specific task.
**A. Defining a Function:**
Functions are defined using the `def` keyword.
```python
# A simple function with no parameters and no return value
def greet():
print("Hello from a function!")
# A function that takes parameters
def add(a, b):
return a + b # Returns the sum of a and b
# A function with default parameter values
def say_hello(name="Guest"):
print(f"Hello, {name}!")
# Calling functions
greet() # Output: Hello from a function!
sum_result = add(5, 3)
print("Sum:", sum_result) # Output: Sum: 8
say_hello("Alice") # Output: Hello, Alice!
say_hello() # Output: Hello, Guest!
```
* The `return` statement is used to send a value back from the function. If no
`return` statement is present, the function implicitly returns `None`.
### 7. Modules and Packages
* **Modules:** A module is a file containing Python definitions and statements.
The filename is the module name with the `.py` extension. You can use modules to
organize your code and reuse it across different files.
* **Packages:** A package is a way of organizing related modules into a directory
hierarchy. A package directory must contain an `__init__.py` file (even if empty)
to be recognized as a package.
**A. Importing Modules:**
```python
import math # Imports the built-in math module
print([Link](16)) # Output: 4.0
print([Link]) # Output: 3.141592653589793
from datetime import date # Imports only the 'date' object from the 'datetime'
module
today = [Link]()
print("Today's date:", today)
```
**B. Creating Your Own Module:**
1. Create a file named `my_module.py`:
```python
# my_module.py
def custom_greet(name):
return f"Greetings, {name} from my custom module!"
my_variable = 123
```
2. In another Python file (in the same directory or a directory included in
`PYTHONPATH`):
```python
import my_module
message = my_module.custom_greet("World")
print(message) # Output: Greetings, World from my custom module!
print(my_module.my_variable) # Output: 123
```
### 8. Object-Oriented Programming (OOP) Basics
Python supports object-oriented programming, allowing you to create classes and
objects.
* **Class:** A blueprint for creating objects. It defines a set of attributes
(data) and methods (functions) that the objects will have.
* **Object:** An instance of a class.
```python
class Dog:
# Class attribute
species = "Canis familiaris"
# Constructor method (initializer)
def __init__(self, name, age):
[Link] = name # Instance attribute
[Link] = age # Instance attribute
# Instance method
def bark(self):
return f"{[Link]} says Woof!"
# Another instance method
def get_age(self):
return [Link]
# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", 3)
your_dog = Dog("Lucy", 5)
print(my_dog.name) # Output: Buddy
print(my_dog.species) # Output: Canis familiaris
print(my_dog.bark()) # Output: Buddy says Woof!
print(your_dog.get_age()) # Output: 5
```
### 9. Error Handling
Python uses `try`, `except`, and `finally` blocks to handle errors (exceptions)
gracefully.
```python
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Invalid input types. Please provide numbers.")
return None
else: # This block executes if no exception occurs
print("Division successful!")
return result
finally: # This block always executes, regardless of an exception
print("Division attempt finished.")
print(divide(10, 2))
# Output:
# Division successful!
# Division attempt finished.
# 5.0
print(divide(10, 0))
# Output:
# Error: Cannot divide by zero!
# Division attempt finished.
# None
print(divide(10, "a"))
# Output:
# Error: Invalid input types. Please provide numbers.
# Division attempt finished.
# None
```
This tutorial provides a foundational understanding of Python. To further your
learning, explore topics like file I/O, advanced data structures, virtual
environments, popular libraries (e.g., NumPy, Pandas, Matplotlib, Flask, Django),
and more in-depth OOP concepts.