Python Basics
Python Basics
python
Copy code
5. Lists
# Addition
sum = x + y Lists are ordered collections of items.
# Subtraction python
difference = x - y Copy code
fruits = ["apple", "banana", "cherry"]
# Multiplication
product = x * y # Accessing elements
print(fruits[0]) # apple
# Division
quotient = x / y # Adding elements
fruits.append("date")
# Exponentiation
power = x ** 2 # Removing elements
fruits.remove("banana")
# Modulus (remainder)
remainder = x % 2 # Slicing
print(fruits[1:3]) # ['cherry', 'date']
3. Control Structures
6. Dictionaries
Conditional Statements allow you to execute
certain code based on conditions. Dictionaries are collections of key-value pairs.
python python
Copy code Copy code
if x > 0: person = {"name": "Alice", "age": 25,
print("x is positive") "city": "New York"}
1|Page
Variables are used to store information that can be
# Accessing values
referenced and manipulated in a program.
print(person["name"]) # Alice
3. Control Structures
Python Basics
Conditional Statements
1. Variables and Data Types
Control the flow of execution based on conditions.
Variables
python
Copy code
if x > 0:
2|Page
print("x is positive") Dictionaries are collections of key-value pairs.
elif x == 0:
print("x is zero")
python
else:
Copy code
print("x is negative")
person = {"name": "Alice", "age": 25,
"city": "New York"}
Loops
# Accessing values
print(person["name"]) # Alice
Repeat a block of code multiple times.
# Adding key-value pairs
For Loop person["email"] = "[email protected]"
python
6. Dictionaries Copy code
3|Page
add = lambda a, b: a + b Creating a package:
print(add(2, 3)) # 5
markdown
3. Error Handling Copy code
mypackage/
__init__.py
Handle exceptions to make your program more module1.py
robust. module2.py
4|Page
# Connect to a database (or create one if
it doesn't exist) # Pandas DataFrame
conn = sqlite3.connect('example.db') data = {'Name': ['Alice', 'Bob'], 'Age':
[25, 30]}
# Create a cursor object df = pd.DataFrame(data)
cur = conn.cursor()
# Plotting with Matplotlib
# Create a table plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
cur.execute('''CREATE TABLE IF NOT EXISTS plt.xlabel('X axis')
users (id INTEGER PRIMARY KEY, name TEXT, plt.ylabel('Y axis')
age INTEGER)''') plt.title('Simple Plot')
plt.show()
# Insert a row of data
cur.execute("INSERT INTO users (name, age)
VALUES ('Alice', 25)")
These notes cover the basics and some advanced
# Commit the changes topics in Python. Let me know if you need more
conn.commit() details on any specific area!
# Query the database
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
print(row)
9. Web Development
Flask Example:
python
Copy code
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
python
Copy code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# NumPy array
arr = np.array([1, 2, 3, 4, 5])
5|Page