Python Notes
Introduction to Python
Python is a high-level, interpreted programming language that is easy to read and write.
It is widely used in web development, data analysis, artificial intelligence, and automation.
Data Types
Common data types in Python are:
- int: Integer numbers (e.g., 5, -10)
- float: Decimal numbers (e.g., 3.14, -2.5)
- str: Strings or text (e.g., "Hello")
- list: Ordered, mutable collection (e.g., [1, 2, 3])
- tuple: Ordered, immutable collection (e.g., (1, 2, 3))
- dict: Key-value pairs (e.g., {"name": "John", "age": 25})
- set: Unordered collection of unique items (e.g., {1, 2, 3})
Operators
Python operators include:
- Arithmetic: +, -, *, /, %, **, //
- Comparison: ==, !=, >, <, >=, <=
- Logical: and, or, not
- Assignment: =, +=, -=, *=, /=
- Membership: in, not in
- Identity: is, is not
Conditional Statements
Used to make decisions in code:
if condition:
# code
elif another_condition:
# code
else:
# code
Loops
Two main loops:
- for loop: Iterates over a sequence
Example: for i in range(5): print(i)
- while loop: Runs until a condition is False
Example: while x < 10: print(x); x+=1
Functions
Functions group code for reuse.
def greet(name):
return "Hello " + name
print(greet("Naadi"))
File Handling
Open, read, and write files.
with open("file.txt", "r") as f:
data = f.read()
with open("file.txt", "w") as f:
f.write("Hello World")
NumPy and Pandas
- NumPy: Library for numerical computations, arrays, and matrices.
Example:
import numpy as np
arr = np.array([1,2,3])
- Pandas: Library for data analysis using DataFrames.
import pandas as pd
df = pd.DataFrame({"Name":["A","B"], "Age":[20,21]})
print(df)