diff --git a/Projects/Advanced/DataDashboard/README.md b/Projects/Advanced/DataDashboard/README.md index 868d9a3..afef758 100644 --- a/Projects/Advanced/DataDashboard/README.md +++ b/Projects/Advanced/DataDashboard/README.md @@ -1 +1,618 @@ -# Data Analysis Dashboard Project\n\nBuild an interactive data visualization dashboard to analyze and present data insights.\n\n## Project Overview\n\n**What you'll build**: A data dashboard that loads datasets, performs analysis, creates visualizations, and presents insights through an interactive interface.\n\n**What you'll learn**:\n- Data manipulation with pandas\n- Data visualization with matplotlib and plotly\n- Statistical analysis and insights\n- Dashboard creation with Streamlit or Dash\n- Data cleaning and preprocessing\n- Interactive plotting and filtering\n\n## Project Features\n\n### Core Features\n- Load data from CSV, JSON, and Excel files\n- Basic data exploration and statistics\n- Create charts and graphs\n- Filter and sort data\n- Export visualizations\n- Simple dashboard layout\n\n### Advanced Features\n- Real-time data updates\n- Interactive filtering and drilling down\n- Multiple data source integration\n- Advanced statistical analysis\n- Custom visualization types\n- Dashboard sharing and deployment\n\n## Implementation Guide\n\n### Phase 1: Data Loading and Exploration\n**Time**: 3-4 hours\n\nStart with basic data operations:\n- Load and display datasets\n- Basic statistics and summaries\n- Data cleaning and preprocessing\n- Simple matplotlib charts\n\n**Key concepts**: pandas basics, data exploration, basic plotting\n\n### Phase 2: Interactive Visualizations\n**Time**: 4-5 hours\n\nCreate dynamic charts:\n- Interactive plots with plotly\n- Multiple chart types\n- Data filtering and selection\n- Chart customization\n\n**Key concepts**: Interactive plotting, data filtering, visualization design\n\n### Phase 3: Dashboard Interface\n**Time**: 4-5 hours\n\nBuild dashboard framework:\n- Streamlit or Dash setup\n- Layout design and organization\n- User controls and widgets\n- Multi-page navigation\n\n**Key concepts**: Dashboard frameworks, UI components, layout design\n\n### Phase 4: Advanced Analytics\n**Time**: 5-6 hours\n\nAdd sophisticated analysis:\n- Trend analysis and forecasting\n- Correlation and regression analysis\n- Statistical significance testing\n- Machine learning insights\n\n**Key concepts**: Statistical analysis, machine learning, advanced visualization\n\n## Getting Started\n\n### Required Libraries\n```bash\npip install pandas matplotlib plotly streamlit seaborn scikit-learn numpy\n```\n\n### Basic Setup\n```python\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport streamlit as st\nimport seaborn as sns\nimport numpy as np\nfrom datetime import datetime, timedelta\n\nclass DataDashboard:\n def __init__(self):\n self.data = None\n self.charts = {}\n self.filters = {}\n \n def load_data(self, file_path):\n # Load data from various file formats\n pass\n \n def create_chart(self, chart_type, x_col, y_col, **kwargs):\n # Generate different types of charts\n pass\n```\n\n## Data Loading and Processing\n\n### Data Loader Class\n```python\nclass DataLoader:\n @staticmethod\n def load_csv(file_path, **kwargs):\n try:\n return pd.read_csv(file_path, **kwargs)\n except Exception as e:\n st.error(f\"Error loading CSV: {e}\")\n return None\n \n @staticmethod\n def load_excel(file_path, **kwargs):\n try:\n return pd.read_excel(file_path, **kwargs)\n except Exception as e:\n st.error(f\"Error loading Excel: {e}\")\n return None\n \n @staticmethod\n def load_json(file_path, **kwargs):\n try:\n return pd.read_json(file_path, **kwargs)\n except Exception as e:\n st.error(f\"Error loading JSON: {e}\")\n return None\n\nclass DataProcessor:\n @staticmethod\n def clean_data(df):\n # Remove duplicates\n df = df.drop_duplicates()\n \n # Handle missing values\n numeric_columns = df.select_dtypes(include=[np.number]).columns\n df[numeric_columns] = df[numeric_columns].fillna(df[numeric_columns].median())\n \n # Handle categorical missing values\n categorical_columns = df.select_dtypes(include=['object']).columns\n df[categorical_columns] = df[categorical_columns].fillna('Unknown')\n \n return df\n \n @staticmethod\n def detect_data_types(df):\n type_info = {}\n for column in df.columns:\n if pd.api.types.is_numeric_dtype(df[column]):\n type_info[column] = 'numeric'\n elif pd.api.types.is_datetime64_any_dtype(df[column]):\n type_info[column] = 'datetime'\n else:\n type_info[column] = 'categorical'\n return type_info\n```\n\n## Visualization Components\n\n### Chart Generator\n```python\nclass ChartGenerator:\n def __init__(self, data):\n self.data = data\n \n def create_line_chart(self, x_col, y_col, color_col=None, title=None):\n fig = px.line(\n self.data, \n x=x_col, \n y=y_col, \n color=color_col,\n title=title or f'{y_col} over {x_col}'\n )\n return fig\n \n def create_bar_chart(self, x_col, y_col, color_col=None, title=None):\n fig = px.bar(\n self.data,\n x=x_col,\n y=y_col,\n color=color_col,\n title=title or f'{y_col} by {x_col}'\n )\n return fig\n \n def create_scatter_plot(self, x_col, y_col, size_col=None, color_col=None, title=None):\n fig = px.scatter(\n self.data,\n x=x_col,\n y=y_col,\n size=size_col,\n color=color_col,\n title=title or f'{y_col} vs {x_col}'\n )\n return fig\n \n def create_histogram(self, column, bins=30, title=None):\n fig = px.histogram(\n self.data,\n x=column,\n nbins=bins,\n title=title or f'Distribution of {column}'\n )\n return fig\n \n def create_box_plot(self, x_col, y_col, title=None):\n fig = px.box(\n self.data,\n x=x_col,\n y=y_col,\n title=title or f'{y_col} distribution by {x_col}'\n )\n return fig\n \n def create_correlation_heatmap(self, columns=None):\n if columns:\n correlation_data = self.data[columns].corr()\n else:\n numeric_data = self.data.select_dtypes(include=[np.number])\n correlation_data = numeric_data.corr()\n \n fig = px.imshow(\n correlation_data,\n title='Correlation Heatmap',\n color_continuous_scale='RdBu',\n aspect='auto'\n )\n return fig\n```\n\n## Streamlit Dashboard\n\n### Main Dashboard App\n```python\ndef main():\n st.set_page_config(\n page_title=\"Data Analysis Dashboard\",\n page_icon=\"šŸ“Š\",\n layout=\"wide\"\n )\n \n st.title(\"šŸ“Š Data Analysis Dashboard\")\n st.sidebar.title(\"Navigation\")\n \n # Sidebar navigation\n page = st.sidebar.selectbox(\n \"Choose a page\",\n [\"Data Upload\", \"Data Overview\", \"Visualizations\", \"Analysis\", \"Export\"]\n )\n \n # Initialize session state\n if 'data' not in st.session_state:\n st.session_state.data = None\n \n if page == \"Data Upload\":\n data_upload_page()\n elif page == \"Data Overview\":\n data_overview_page()\n elif page == \"Visualizations\":\n visualizations_page()\n elif page == \"Analysis\":\n analysis_page()\n elif page == \"Export\":\n export_page()\n\ndef data_upload_page():\n st.header(\"šŸ“ Data Upload\")\n \n upload_method = st.radio(\n \"Choose upload method:\",\n [\"File Upload\", \"Sample Datasets\"]\n )\n \n if upload_method == \"File Upload\":\n uploaded_file = st.file_uploader(\n \"Choose a file\",\n type=['csv', 'xlsx', 'json']\n )\n \n if uploaded_file is not None:\n try:\n if uploaded_file.name.endswith('.csv'):\n df = pd.read_csv(uploaded_file)\n elif uploaded_file.name.endswith('.xlsx'):\n df = pd.read_excel(uploaded_file)\n elif uploaded_file.name.endswith('.json'):\n df = pd.read_json(uploaded_file)\n \n st.session_state.data = df\n st.success(f\"Successfully loaded {df.shape[0]} rows and {df.shape[1]} columns\")\n \n # Show preview\n st.subheader(\"Data Preview\")\n st.dataframe(df.head())\n \n except Exception as e:\n st.error(f\"Error loading file: {e}\")\n \n else:\n # Sample datasets\n dataset_choice = st.selectbox(\n \"Choose a sample dataset:\",\n [\"Sales Data\", \"Stock Prices\", \"Weather Data\"]\n )\n \n if st.button(\"Load Sample Data\"):\n df = load_sample_data(dataset_choice)\n st.session_state.data = df\n st.success(f\"Loaded sample dataset: {dataset_choice}\")\n st.dataframe(df.head())\n\ndef data_overview_page():\n st.header(\"šŸ“‹ Data Overview\")\n \n if st.session_state.data is None:\n st.warning(\"Please upload data first!\")\n return\n \n df = st.session_state.data\n \n # Basic info\n col1, col2, col3, col4 = st.columns(4)\n \n with col1:\n st.metric(\"Rows\", df.shape[0])\n with col2:\n st.metric(\"Columns\", df.shape[1])\n with col3:\n st.metric(\"Memory Usage\", f\"{df.memory_usage(deep=True).sum() / 1024:.1f} KB\")\n with col4:\n st.metric(\"Missing Values\", df.isnull().sum().sum())\n \n # Data types\n st.subheader(\"Column Information\")\n col_info = pd.DataFrame({\n 'Column': df.columns,\n 'Data Type': df.dtypes,\n 'Non-Null Count': df.count(),\n 'Null Count': df.isnull().sum()\n })\n st.dataframe(col_info)\n \n # Statistical summary\n st.subheader(\"Statistical Summary\")\n st.dataframe(df.describe())\n \n # Data quality issues\n st.subheader(\"Data Quality Check\")\n duplicates = df.duplicated().sum()\n if duplicates > 0:\n st.warning(f\"Found {duplicates} duplicate rows\")\n else:\n st.success(\"No duplicate rows found\")\n\ndef visualizations_page():\n st.header(\"šŸ“ˆ Visualizations\")\n \n if st.session_state.data is None:\n st.warning(\"Please upload data first!\")\n return\n \n df = st.session_state.data\n chart_gen = ChartGenerator(df)\n \n # Chart type selection\n chart_type = st.selectbox(\n \"Select Chart Type\",\n [\"Line Chart\", \"Bar Chart\", \"Scatter Plot\", \"Histogram\", \"Box Plot\", \"Correlation Heatmap\"]\n )\n \n if chart_type == \"Line Chart\":\n col1, col2 = st.columns(2)\n with col1:\n x_col = st.selectbox(\"X-axis\", df.columns)\n with col2:\n y_col = st.selectbox(\"Y-axis\", df.select_dtypes(include=[np.number]).columns)\n \n if st.button(\"Generate Chart\"):\n fig = chart_gen.create_line_chart(x_col, y_col)\n st.plotly_chart(fig, use_container_width=True)\n \n elif chart_type == \"Bar Chart\":\n col1, col2 = st.columns(2)\n with col1:\n x_col = st.selectbox(\"X-axis\", df.columns)\n with col2:\n y_col = st.selectbox(\"Y-axis\", df.select_dtypes(include=[np.number]).columns)\n \n if st.button(\"Generate Chart\"):\n fig = chart_gen.create_bar_chart(x_col, y_col)\n st.plotly_chart(fig, use_container_width=True)\n \n elif chart_type == \"Correlation Heatmap\":\n numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()\n selected_cols = st.multiselect(\"Select columns for correlation\", numeric_cols, default=numeric_cols[:5])\n \n if st.button(\"Generate Heatmap\") and selected_cols:\n fig = chart_gen.create_correlation_heatmap(selected_cols)\n st.plotly_chart(fig, use_container_width=True)\n```\n\n## Advanced Analytics\n\n### Statistical Analysis\n```python\nclass StatisticalAnalysis:\n def __init__(self, data):\n self.data = data\n \n def trend_analysis(self, date_col, value_col):\n # Simple trend analysis using linear regression\n from scipy import stats\n \n df_sorted = self.data.sort_values(date_col)\n x = np.arange(len(df_sorted))\n y = df_sorted[value_col]\n \n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\n \n return {\n 'slope': slope,\n 'r_squared': r_value**2,\n 'p_value': p_value,\n 'trend': 'increasing' if slope > 0 else 'decreasing'\n }\n \n def correlation_analysis(self, columns=None):\n if columns:\n data_subset = self.data[columns]\n else:\n data_subset = self.data.select_dtypes(include=[np.number])\n \n correlation_matrix = data_subset.corr()\n \n # Find strongest correlations\n strong_correlations = []\n for i in range(len(correlation_matrix.columns)):\n for j in range(i+1, len(correlation_matrix.columns)):\n corr_value = correlation_matrix.iloc[i, j]\n if abs(corr_value) > 0.5: # Threshold for strong correlation\n strong_correlations.append({\n 'var1': correlation_matrix.columns[i],\n 'var2': correlation_matrix.columns[j],\n 'correlation': corr_value\n })\n \n return strong_correlations\n \n def outlier_detection(self, column):\n Q1 = self.data[column].quantile(0.25)\n Q3 = self.data[column].quantile(0.75)\n IQR = Q3 - Q1\n \n lower_bound = Q1 - 1.5 * IQR\n upper_bound = Q3 + 1.5 * IQR\n \n outliers = self.data[\n (self.data[column] < lower_bound) | \n (self.data[column] > upper_bound)\n ]\n \n return outliers\n```\n\n## Sample Data Generators\n\n### Generate Sample Datasets\n```python\ndef load_sample_data(dataset_type):\n if dataset_type == \"Sales Data\":\n dates = pd.date_range('2023-01-01', '2023-12-31', freq='D')\n np.random.seed(42)\n \n return pd.DataFrame({\n 'date': dates,\n 'sales': np.random.normal(1000, 200, len(dates)) + \n 50 * np.sin(np.arange(len(dates)) * 2 * np.pi / 365),\n 'region': np.random.choice(['North', 'South', 'East', 'West'], len(dates)),\n 'product': np.random.choice(['A', 'B', 'C'], len(dates)),\n 'customer_satisfaction': np.random.uniform(1, 5, len(dates))\n })\n \n elif dataset_type == \"Stock Prices\":\n dates = pd.date_range('2023-01-01', '2023-12-31', freq='D')\n price = 100\n prices = []\n \n for _ in dates:\n price += np.random.normal(0, 2)\n prices.append(max(price, 10)) # Ensure positive prices\n \n return pd.DataFrame({\n 'date': dates,\n 'price': prices,\n 'volume': np.random.normal(1000000, 200000, len(dates)),\n 'company': np.random.choice(['AAPL', 'GOOGL', 'MSFT'], len(dates))\n })\n \n elif dataset_type == \"Weather Data\":\n dates = pd.date_range('2023-01-01', '2023-12-31', freq='D')\n \n return pd.DataFrame({\n 'date': dates,\n 'temperature': 20 + 10 * np.sin(np.arange(len(dates)) * 2 * np.pi / 365) + \n np.random.normal(0, 3, len(dates)),\n 'humidity': np.random.uniform(30, 90, len(dates)),\n 'rainfall': np.random.exponential(2, len(dates)),\n 'city': np.random.choice(['New York', 'London', 'Tokyo'], len(dates))\n })\n```\n\n## Dashboard Deployment\n\n### Running the Dashboard\n```bash\n# Save your main code as dashboard.py\nstreamlit run dashboard.py\n\n# The dashboard will be available at http://localhost:8501\n```\n\n### Configuration File\n```toml\n# .streamlit/config.toml\n[theme]\nbase = \"light\"\nprimaryColor = \"#1f77b4\"\nbackgroundColor = \"#ffffff\"\nsecondaryBackgroundColor = \"#f0f2f6\"\ntextColor = \"#262730\"\n\n[server]\nport = 8501\nmaxUploadSize = 200\n```\n\n## Testing Your Dashboard\n\n### Test Scenarios\n- Upload different file formats and sizes\n- Test with missing or corrupted data\n- Verify chart generation with various data types\n- Test filtering and interactive features\n- Check performance with large datasets\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Add more chart types (pie charts, area charts)\n- Implement data filtering widgets\n- Add export functionality for charts\n- Create data summary reports\n\n### Intermediate Extensions\n- Real-time data streaming\n- Machine learning model integration\n- Advanced statistical tests\n- Custom color themes and styling\n\n### Advanced Extensions\n- Multi-user authentication and sharing\n- Database integration for large datasets\n- Advanced forecasting and prediction models\n- Integration with BI tools and APIs\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- Data manipulation and analysis with pandas\n- Data visualization principles and techniques\n- Interactive dashboard development\n- Statistical analysis and interpretation\n- User interface design for data applications\n- Data storytelling and presentation\n\n## File Structure\n\n```\ndata_dashboard/\nā”œā”€ā”€ dashboard.py # Main Streamlit app\nā”œā”€ā”€ components/\n│ ā”œā”€ā”€ data_loader.py # Data loading utilities\n│ ā”œā”€ā”€ chart_generator.py # Visualization components\n│ └── analytics.py # Statistical analysis\nā”œā”€ā”€ sample_data/\n│ ā”œā”€ā”€ sales.csv # Sample datasets\n│ ā”œā”€ā”€ stocks.csv\n│ └── weather.csv\nā”œā”€ā”€ .streamlit/\n│ └── config.toml # Streamlit configuration\nā”œā”€ā”€ requirements.txt # Dependencies\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your data dashboard:\n1. Deploy it to Streamlit Cloud or Heroku\n2. Add your own datasets and create custom analyses\n3. Share with colleagues and get feedback\n4. Explore advanced machine learning integrations\n5. Consider building specialized dashboards for specific domains\n\nFantastic work on building a comprehensive data analysis tool! \ No newline at end of file +# Data Analysis Dashboard Project + +Build an interactive data visualization dashboard to analyze and present data insights. + +## Project Overview + +**What you'll build**: A data dashboard that loads datasets, performs analysis, creates visualizations, and presents insights through an interactive interface. + +**What you'll learn**: +- Data manipulation with pandas +- Data visualization with matplotlib and plotly +- Statistical analysis and insights +- Dashboard creation with Streamlit or Dash +- Data cleaning and preprocessing +- Interactive plotting and filtering + +## Project Features + +### Core Features +- Load data from CSV, JSON, and Excel files +- Basic data exploration and statistics +- Create charts and graphs +- Filter and sort data +- Export visualizations +- Simple dashboard layout + +### Advanced Features +- Real-time data updates +- Interactive filtering and drilling down +- Multiple data source integration +- Advanced statistical analysis +- Custom visualization types +- Dashboard sharing and deployment + +## Implementation Guide + +### Phase 1: Data Loading and Exploration +**Time**: 3-4 hours + +Start with basic data operations: +- Load and display datasets +- Basic statistics and summaries +- Data cleaning and preprocessing +- Simple matplotlib charts + +**Key concepts**: pandas basics, data exploration, basic plotting + +### Phase 2: Interactive Visualizations +**Time**: 4-5 hours + +Create dynamic charts: +- Interactive plots with plotly +- Multiple chart types +- Data filtering and selection +- Chart customization + +**Key concepts**: Interactive plotting, data filtering, visualization design + +### Phase 3: Dashboard Interface +**Time**: 4-5 hours + +Build dashboard framework: +- Streamlit or Dash setup +- Layout design and organization +- User controls and widgets +- Multi-page navigation + +**Key concepts**: Dashboard frameworks, UI components, layout design + +### Phase 4: Advanced Analytics +**Time**: 5-6 hours + +Add sophisticated analysis: +- Trend analysis and forecasting +- Correlation and regression analysis +- Statistical significance testing +- Machine learning insights + +**Key concepts**: Statistical analysis, machine learning, advanced visualization + +## Getting Started + +### Required Libraries +```bash +pip install pandas matplotlib plotly streamlit seaborn scikit-learn numpy +``` + +### Basic Setup +```python +import pandas as pd +import matplotlib.pyplot as plt +import plotly.express as px +import plotly.graph_objects as go +import streamlit as st +import seaborn as sns +import numpy as np +from datetime import datetime, timedelta + +class DataDashboard: + def __init__(self): + self.data = None + self.charts = {} + self.filters = {} + + def load_data(self, file_path): + # Load data from various file formats + pass + + def create_chart(self, chart_type, x_col, y_col, **kwargs): + # Generate different types of charts + pass +``` + +## Data Loading and Processing + +### Data Loader Class +```python +class DataLoader: + @staticmethod + def load_csv(file_path, **kwargs): + try: + return pd.read_csv(file_path, **kwargs) + except Exception as e: + st.error(f"Error loading CSV: {e}") + return None + + @staticmethod + def load_excel(file_path, **kwargs): + try: + return pd.read_excel(file_path, **kwargs) + except Exception as e: + st.error(f"Error loading Excel: {e}") + return None + + @staticmethod + def load_json(file_path, **kwargs): + try: + return pd.read_json(file_path, **kwargs) + except Exception as e: + st.error(f"Error loading JSON: {e}") + return None + +class DataProcessor: + @staticmethod + def clean_data(df): + # Remove duplicates + df = df.drop_duplicates() + + # Handle missing values + numeric_columns = df.select_dtypes(include=[np.number]).columns + df[numeric_columns] = df[numeric_columns].fillna(df[numeric_columns].median()) + + # Handle categorical missing values + categorical_columns = df.select_dtypes(include=['object']).columns + df[categorical_columns] = df[categorical_columns].fillna('Unknown') + + return df + + @staticmethod + def detect_data_types(df): + type_info = {} + for column in df.columns: + if pd.api.types.is_numeric_dtype(df[column]): + type_info[column] = 'numeric' + elif pd.api.types.is_datetime64_any_dtype(df[column]): + type_info[column] = 'datetime' + else: + type_info[column] = 'categorical' + return type_info +``` + +## Visualization Components + +### Chart Generator +```python +class ChartGenerator: + def __init__(self, data): + self.data = data + + def create_line_chart(self, x_col, y_col, color_col=None, title=None): + fig = px.line( + self.data, + x=x_col, + y=y_col, + color=color_col, + title=title or f'{y_col} over {x_col}' + ) + return fig + + def create_bar_chart(self, x_col, y_col, color_col=None, title=None): + fig = px.bar( + self.data, + x=x_col, + y=y_col, + color=color_col, + title=title or f'{y_col} by {x_col}' + ) + return fig + + def create_scatter_plot(self, x_col, y_col, size_col=None, color_col=None, title=None): + fig = px.scatter( + self.data, + x=x_col, + y=y_col, + size=size_col, + color=color_col, + title=title or f'{y_col} vs {x_col}' + ) + return fig + + def create_histogram(self, column, bins=30, title=None): + fig = px.histogram( + self.data, + x=column, + nbins=bins, + title=title or f'Distribution of {column}' + ) + return fig + + def create_box_plot(self, x_col, y_col, title=None): + fig = px.box( + self.data, + x=x_col, + y=y_col, + title=title or f'{y_col} distribution by {x_col}' + ) + return fig + + def create_correlation_heatmap(self, columns=None): + if columns: + correlation_data = self.data[columns].corr() + else: + numeric_data = self.data.select_dtypes(include=[np.number]) + correlation_data = numeric_data.corr() + + fig = px.imshow( + correlation_data, + title='Correlation Heatmap', + color_continuous_scale='RdBu', + aspect='auto' + ) + return fig +``` + +## Streamlit Dashboard + +### Main Dashboard App +```python +def main(): + st.set_page_config( + page_title="Data Analysis Dashboard", + page_icon="šŸ“Š", + layout="wide" + ) + + st.title("šŸ“Š Data Analysis Dashboard") + st.sidebar.title("Navigation") + + # Sidebar navigation + page = st.sidebar.selectbox( + "Choose a page", + ["Data Upload", "Data Overview", "Visualizations", "Analysis", "Export"] + ) + + # Initialize session state + if 'data' not in st.session_state: + st.session_state.data = None + + if page == "Data Upload": + data_upload_page() + elif page == "Data Overview": + data_overview_page() + elif page == "Visualizations": + visualizations_page() + elif page == "Analysis": + analysis_page() + elif page == "Export": + export_page() + +def data_upload_page(): + st.header("šŸ“ Data Upload") + + upload_method = st.radio( + "Choose upload method:", + ["File Upload", "Sample Datasets"] + ) + + if upload_method == "File Upload": + uploaded_file = st.file_uploader( + "Choose a file", + type=['csv', 'xlsx', 'json'] + ) + + if uploaded_file is not None: + try: + if uploaded_file.name.endswith('.csv'): + df = pd.read_csv(uploaded_file) + elif uploaded_file.name.endswith('.xlsx'): + df = pd.read_excel(uploaded_file) + elif uploaded_file.name.endswith('.json'): + df = pd.read_json(uploaded_file) + + st.session_state.data = df + st.success(f"Successfully loaded {df.shape[0]} rows and {df.shape[1]} columns") + + # Show preview + st.subheader("Data Preview") + st.dataframe(df.head()) + + except Exception as e: + st.error(f"Error loading file: {e}") + + else: + # Sample datasets + dataset_choice = st.selectbox( + "Choose a sample dataset:", + ["Sales Data", "Stock Prices", "Weather Data"] + ) + + if st.button("Load Sample Data"): + df = load_sample_data(dataset_choice) + st.session_state.data = df + st.success(f"Loaded sample dataset: {dataset_choice}") + st.dataframe(df.head()) + +def data_overview_page(): + st.header("šŸ“‹ Data Overview") + + if st.session_state.data is None: + st.warning("Please upload data first!") + return + + df = st.session_state.data + + # Basic info + col1, col2, col3, col4 = st.columns(4) + + with col1: + st.metric("Rows", df.shape[0]) + with col2: + st.metric("Columns", df.shape[1]) + with col3: + st.metric("Memory Usage", f"{df.memory_usage(deep=True).sum() / 1024:.1f} KB") + with col4: + st.metric("Missing Values", df.isnull().sum().sum()) + + # Data types + st.subheader("Column Information") + col_info = pd.DataFrame({ + 'Column': df.columns, + 'Data Type': df.dtypes, + 'Non-Null Count': df.count(), + 'Null Count': df.isnull().sum() + }) + st.dataframe(col_info) + + # Statistical summary + st.subheader("Statistical Summary") + st.dataframe(df.describe()) + + # Data quality issues + st.subheader("Data Quality Check") + duplicates = df.duplicated().sum() + if duplicates > 0: + st.warning(f"Found {duplicates} duplicate rows") + else: + st.success("No duplicate rows found") + +def visualizations_page(): + st.header("šŸ“ˆ Visualizations") + + if st.session_state.data is None: + st.warning("Please upload data first!") + return + + df = st.session_state.data + chart_gen = ChartGenerator(df) + + # Chart type selection + chart_type = st.selectbox( + "Select Chart Type", + ["Line Chart", "Bar Chart", "Scatter Plot", "Histogram", "Box Plot", "Correlation Heatmap"] + ) + + if chart_type == "Line Chart": + col1, col2 = st.columns(2) + with col1: + x_col = st.selectbox("X-axis", df.columns) + with col2: + y_col = st.selectbox("Y-axis", df.select_dtypes(include=[np.number]).columns) + + if st.button("Generate Chart"): + fig = chart_gen.create_line_chart(x_col, y_col) + st.plotly_chart(fig, use_container_width=True) + + elif chart_type == "Bar Chart": + col1, col2 = st.columns(2) + with col1: + x_col = st.selectbox("X-axis", df.columns) + with col2: + y_col = st.selectbox("Y-axis", df.select_dtypes(include=[np.number]).columns) + + if st.button("Generate Chart"): + fig = chart_gen.create_bar_chart(x_col, y_col) + st.plotly_chart(fig, use_container_width=True) + + elif chart_type == "Correlation Heatmap": + numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist() + selected_cols = st.multiselect("Select columns for correlation", numeric_cols, default=numeric_cols[:5]) + + if st.button("Generate Heatmap") and selected_cols: + fig = chart_gen.create_correlation_heatmap(selected_cols) + st.plotly_chart(fig, use_container_width=True) +``` + +## Advanced Analytics + +### Statistical Analysis +```python +class StatisticalAnalysis: + def __init__(self, data): + self.data = data + + def trend_analysis(self, date_col, value_col): + # Simple trend analysis using linear regression + from scipy import stats + + df_sorted = self.data.sort_values(date_col) + x = np.arange(len(df_sorted)) + y = df_sorted[value_col] + + slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) + + return { + 'slope': slope, + 'r_squared': r_value**2, + 'p_value': p_value, + 'trend': 'increasing' if slope > 0 else 'decreasing' + } + + def correlation_analysis(self, columns=None): + if columns: + data_subset = self.data[columns] + else: + data_subset = self.data.select_dtypes(include=[np.number]) + + correlation_matrix = data_subset.corr() + + # Find strongest correlations + strong_correlations = [] + for i in range(len(correlation_matrix.columns)): + for j in range(i+1, len(correlation_matrix.columns)): + corr_value = correlation_matrix.iloc[i, j] + if abs(corr_value) > 0.5: # Threshold for strong correlation + strong_correlations.append({ + 'var1': correlation_matrix.columns[i], + 'var2': correlation_matrix.columns[j], + 'correlation': corr_value + }) + + return strong_correlations + + def outlier_detection(self, column): + Q1 = self.data[column].quantile(0.25) + Q3 = self.data[column].quantile(0.75) + IQR = Q3 - Q1 + + lower_bound = Q1 - 1.5 * IQR + upper_bound = Q3 + 1.5 * IQR + + outliers = self.data[ + (self.data[column] < lower_bound) | + (self.data[column] > upper_bound) + ] + + return outliers +``` + +## Sample Data Generators + +### Generate Sample Datasets +```python +def load_sample_data(dataset_type): + if dataset_type == "Sales Data": + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + np.random.seed(42) + + return pd.DataFrame({ + 'date': dates, + 'sales': np.random.normal(1000, 200, len(dates)) + + 50 * np.sin(np.arange(len(dates)) * 2 * np.pi / 365), + 'region': np.random.choice(['North', 'South', 'East', 'West'], len(dates)), + 'product': np.random.choice(['A', 'B', 'C'], len(dates)), + 'customer_satisfaction': np.random.uniform(1, 5, len(dates)) + }) + + elif dataset_type == "Stock Prices": + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + price = 100 + prices = [] + + for _ in dates: + price += np.random.normal(0, 2) + prices.append(max(price, 10)) # Ensure positive prices + + return pd.DataFrame({ + 'date': dates, + 'price': prices, + 'volume': np.random.normal(1000000, 200000, len(dates)), + 'company': np.random.choice(['AAPL', 'GOOGL', 'MSFT'], len(dates)) + }) + + elif dataset_type == "Weather Data": + dates = pd.date_range('2023-01-01', '2023-12-31', freq='D') + + return pd.DataFrame({ + 'date': dates, + 'temperature': 20 + 10 * np.sin(np.arange(len(dates)) * 2 * np.pi / 365) + + np.random.normal(0, 3, len(dates)), + 'humidity': np.random.uniform(30, 90, len(dates)), + 'rainfall': np.random.exponential(2, len(dates)), + 'city': np.random.choice(['New York', 'London', 'Tokyo'], len(dates)) + }) +``` + +## Dashboard Deployment + +### Running the Dashboard +```bash +# Save your main code as dashboard.py +streamlit run dashboard.py + +# The dashboard will be available at http://localhost:8501 +``` + +### Configuration File +```toml +# .streamlit/config.toml +[theme] +base = "light" +primaryColor = "#1f77b4" +backgroundColor = "#ffffff" +secondaryBackgroundColor = "#f0f2f6" +textColor = "#262730" + +[server] +port = 8501 +maxUploadSize = 200 +``` + +## Testing Your Dashboard + +### Test Scenarios +- Upload different file formats and sizes +- Test with missing or corrupted data +- Verify chart generation with various data types +- Test filtering and interactive features +- Check performance with large datasets + +## Extensions and Improvements + +### Beginner Extensions +- Add more chart types (pie charts, area charts) +- Implement data filtering widgets +- Add export functionality for charts +- Create data summary reports + +### Intermediate Extensions +- Real-time data streaming +- Machine learning model integration +- Advanced statistical tests +- Custom color themes and styling + +### Advanced Extensions +- Multi-user authentication and sharing +- Database integration for large datasets +- Advanced forecasting and prediction models +- Integration with BI tools and APIs + +## Learning Outcomes + +After completing this project, you'll understand: +- Data manipulation and analysis with pandas +- Data visualization principles and techniques +- Interactive dashboard development +- Statistical analysis and interpretation +- User interface design for data applications +- Data storytelling and presentation + +## File Structure + +``` +data_dashboard/ +ā”œā”€ā”€ dashboard.py # Main Streamlit app +ā”œā”€ā”€ components/ +│ ā”œā”€ā”€ data_loader.py # Data loading utilities +│ ā”œā”€ā”€ chart_generator.py # Visualization components +│ └── analytics.py # Statistical analysis +ā”œā”€ā”€ sample_data/ +│ ā”œā”€ā”€ sales.csv # Sample datasets +│ ā”œā”€ā”€ stocks.csv +│ └── weather.csv +ā”œā”€ā”€ .streamlit/ +│ └── config.toml # Streamlit configuration +ā”œā”€ā”€ requirements.txt # Dependencies +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your data dashboard: +1. Deploy it to Streamlit Cloud or Heroku +2. Add your own datasets and create custom analyses +3. Share with colleagues and get feedback +4. Explore advanced machine learning integrations +5. Consider building specialized dashboards for specific domains + +Fantastic work on building a comprehensive data analysis tool! \ No newline at end of file diff --git a/Projects/Beginners/NumberGuessingGame/README.md b/Projects/Beginners/NumberGuessingGame/README.md index 353cf7e..6e1522e 100644 --- a/Projects/Beginners/NumberGuessingGame/README.md +++ b/Projects/Beginners/NumberGuessingGame/README.md @@ -1,1309 +1,270 @@ -# šŸŽÆ Number Guessing Game +# Number Guessing Game Project -
- Number Guessing Game -

Build an interactive number guessing game with multiple difficulty levels

-
+Build an interactive number guessing game where players try to guess a randomly generated number. ---- -- -## šŸŽÆ Project Overview +## Project Overview -Create a fun and interactive number guessing game where the computer generates a random number and the player tries to guess it. This project will teach you about loops, conditionals, random number generation, and user interaction. +**What you'll build**: A fun guessing game where the computer generates a random number and the player tries to guess it with hints and scoring. -### What You'll Learn +**What you'll learn**: - Random number generation - While loops and loop control -- Conditional statements (if/elif/else) +- Conditional statements and logic - User input validation -- Game logic and state management -- File operations for high scores -- Basic algorithm optimization +- Game state management +- Basic file operations for high scores -### Prerequisites -Before starting this project, you should understand: -- [Control Structures](../../Roadmap/06-control-structures.md) - Loops and conditionals -- [Input/Output](../../Roadmap/05-input-output.md) - Getting user input -- [Data Types](../../Roadmap/03-data-types.md) - Numbers and strings -- [Functions](../../Roadmap/07-functions.md) - Creating reusable code +## Project Features -## šŸ“‹ Project Phases +### Basic Features +- Generate random numbers in a specified range +- Accept user guesses and provide feedback +- Track number of attempts +- Declare winner when correct guess is made +- Play again functionality -### Phase 1: Basic Game (⭐) -**Time**: 1-2 hours | **Concepts**: Random numbers, loops, conditionals +### Advanced Features +- Multiple difficulty levels +- High score tracking +- Hint system based on guesses +- Achievement system +- Statistics tracking across games -Create a simple guessing game with basic functionality. +## Implementation Guide -### Phase 2: Enhanced Game (⭐⭐) -**Time**: 2-3 hours | **Concepts**: Functions, input validation, game statistics +### Phase 1: Basic Game +**Time**: 1-2 hours -Add difficulty levels, input validation, and attempt tracking. +Create a simple guessing game: +- Generate random number between 1-100 +- Accept user guesses +- Provide "too high" or "too low" feedback +- Count attempts and announce winner -### Phase 3: Advanced Features (⭐⭐⭐) -**Time**: 3-4 hours | **Concepts**: File handling, data persistence, advanced features +**Key concepts**: Random numbers, loops, conditionals -Implement high scores, hints, and multiple game modes. +### Phase 2: Enhanced Game +**Time**: 2-3 hours -### Phase 4: GUI Version (⭐⭐⭐⭐) -**Time**: 4-5 hours | **Concepts**: GUI programming, event handling +Add difficulty levels and validation: +- Easy (1-50), Medium (1-100), Hard (1-500) modes +- Input validation for invalid entries +- Limited attempts based on difficulty +- Better user interface and feedback -Create a graphical interface version of the game. +**Key concepts**: Functions, input validation, game logic ---- +### Phase 3: Advanced Features +**Time**: 3-4 hours -## šŸš€ Phase 1: Basic Number Guessing Game +Implement scoring and persistence: +- Score calculation based on attempts and difficulty +- High score tracking with file storage +- Game statistics (games played, win rate) +- Hint system for struggling players -### Learning Objectives -- Use the `random` module to generate random numbers -- Implement while loops for game continuation -- Use conditional statements for game logic -- Handle user input and provide feedback +**Key concepts**: File operations, data persistence, algorithms -### Step-by-Step Implementation +### Phase 4: GUI Version +**Time**: 4-5 hours -#### Step 1: Import required modules and set up the game +Create a graphical interface: +- Number input field and guess button +- Visual feedback and game status +- Difficulty selection and settings +- Statistics display and high scores -```python -# basic_guessing_game.py - -import random +**Key concepts**: GUI programming, event handling -print("Welcome to the Number Guessing Game! šŸŽÆ") -print("I'm thinking of a number between 1 and 100.") -print("Can you guess what it is?") -print("-" * 40) +## Getting Started -# Generate random number -secret_number = random.randint(1, 100) -attempts = 0 -max_attempts = 10 - -print(f"You have {max_attempts} attempts to guess the number.") -print("Let's start!") -``` - -#### Step 2: Implement the main game loop +### Setup +1. Create a new Python file for your game +2. Import the random module +3. Plan your game flow and functions +### Basic Structure ```python -# basic_guessing_game.py (continued) - -while attempts < max_attempts: - try: - # Get user input - guess = int(input(f"\nAttempt {attempts + 1}: Enter your guess (1-100): ")) - attempts += 1 - - # Check if guess is in valid range - if guess < 1 or guess > 100: - print("Please enter a number between 1 and 100!") - continue - - # Check the guess - if guess == secret_number: - print(f"\nšŸŽ‰ Congratulations! You guessed it!") - print(f"The number was {secret_number}") - print(f"You won in {attempts} attempts!") - break - elif guess < secret_number: - print("šŸ“ˆ Too low! Try a higher number.") - else: - print("šŸ“‰ Too high! Try a lower number.") - - # Show remaining attempts - remaining = max_attempts - attempts - if remaining > 0: - print(f"You have {remaining} attempts left.") - - except ValueError: - print("āŒ Please enter a valid number!") - # Don't count invalid input as an attempt - continue +import random -# Game over - check if player won or lost -if attempts >= max_attempts and guess != secret_number: - print(f"\nšŸ’” Game Over! You've used all {max_attempts} attempts.") - print(f"The number was {secret_number}. Better luck next time!") +def generate_number(min_val=1, max_val=100): + return random.randint(min_val, max_val) -print("\nThanks for playing! šŸ‘‹") -``` +def get_user_guess(): + while True: + try: + guess = int(input("Enter your guess: ")) + return guess + except ValueError: + print("Please enter a valid number!") -#### Step 3: Test your basic game +def play_game(): + # Main game logic here + pass -Run the program and test different scenarios: -```bash -python basic_guessing_game.py +if __name__ == "__main__": + play_game() ``` -**Test cases to try:** -- Correct guess on first try -- Guess that's too high -- Guess that's too low -- Invalid input (letters, negative numbers) -- Using all attempts without winning - ---- - -## šŸ”§ Phase 2: Enhanced Number Guessing Game - -### Learning Objectives -- Organize code using functions -- Implement multiple difficulty levels -- Add input validation and error handling -- Track and display game statistics -- Implement play-again functionality - -### Implementation +## Game Logic Implementation +### Main Game Loop ```python -# enhanced_guessing_game.py - -import random -import time - -class NumberGuessingGame: - def __init__(self): - self.difficulties = { - 'easy': {'range': (1, 50), 'attempts': 15, 'name': 'Easy'}, - 'medium': {'range': (1, 100), 'attempts': 10, 'name': 'Medium'}, - 'hard': {'range': (1, 200), 'attempts': 8, 'name': 'Hard'}, - 'expert': {'range': (1, 500), 'attempts': 12, 'name': 'Expert'} - } - self.stats = { - 'games_played': 0, - 'games_won': 0, - 'total_attempts': 0, - 'best_score': {'attempts': float('inf'), 'difficulty': None} - } +def play_game(): + print("Welcome to the Number Guessing Game!") - def display_welcome(self): - """Display welcome message and game rules""" - print("=" * 60) - print("šŸŽÆ ENHANCED NUMBER GUESSING GAME šŸŽÆ".center(60)) - print("=" * 60) - print() - print("How to play:") - print("• I'll think of a number within the chosen range") - print("• You guess the number") - print("• I'll tell you if your guess is too high or too low") - print("• Try to guess in as few attempts as possible!") - print() + # Choose difficulty + difficulty = choose_difficulty() + min_num, max_num, max_attempts = get_difficulty_settings(difficulty) - def choose_difficulty(self): - """Let player choose difficulty level""" - print("Choose your difficulty level:") - print() - - for key, value in self.difficulties.items(): - min_num, max_num = value['range'] - attempts = value['attempts'] - name = value['name'] - print(f"{key[0].upper()}. {name}: {min_num}-{max_num} ({attempts} attempts)") - - while True: - choice = input("\nEnter your choice (e/m/h/x): ").lower() - - if choice == 'e': - return 'easy' - elif choice == 'm': - return 'medium' - elif choice == 'h': - return 'hard' - elif choice == 'x': - return 'expert' - else: - print("āŒ Invalid choice! Please enter e, m, h, or x.") + # Generate secret number + secret_number = random.randint(min_num, max_num) + attempts = 0 - def get_valid_guess(self, min_num, max_num, attempt_num): - """Get a valid guess from the player""" - while True: - try: - prompt = f"\nAttempt {attempt_num}: Guess the number ({min_num}-{max_num}): " - guess = int(input(prompt)) - - if min_num <= guess <= max_num: - return guess - else: - print(f"āŒ Please enter a number between {min_num} and {max_num}!") - - except ValueError: - print("āŒ Please enter a valid number!") + print(f"I'm thinking of a number between {min_num} and {max_num}") + print(f"You have {max_attempts} attempts to guess it!") - def give_hint(self, guess, secret_number, min_num, max_num): - """Provide helpful hints based on the guess""" - difference = abs(guess - secret_number) - range_size = max_num - min_num + while attempts < max_attempts: + guess = get_user_guess() + attempts += 1 - if difference <= range_size * 0.05: # Very close (within 5% of range) - return "šŸ”„ You're burning hot! Very close!" - elif difference <= range_size * 0.15: # Close (within 15% of range) - return "ā™Øļø You're getting warm!" - elif difference <= range_size * 0.30: # Moderate (within 30% of range) - return "šŸŒ”ļø You're getting closer..." + if guess == secret_number: + print(f"Congratulations! You guessed it in {attempts} attempts!") + break + elif guess < secret_number: + print("Too low! Try again.") else: - return "🧊 You're cold. Try a different direction!" - - def calculate_score(self, attempts, max_attempts, difficulty): - """Calculate score based on attempts and difficulty""" - base_score = 1000 - difficulty_multiplier = {'easy': 1, 'medium': 1.5, 'hard': 2, 'expert': 3} - - # Bonus for using fewer attempts - attempt_bonus = (max_attempts - attempts) * 50 - - # Difficulty bonus - diff_bonus = base_score * (difficulty_multiplier[difficulty] - 1) - - return int(base_score + attempt_bonus + diff_bonus) - - def play_round(self): - """Play a single round of the game""" - self.stats['games_played'] += 1 - - # Choose difficulty - difficulty = self.choose_difficulty() - settings = self.difficulties[difficulty] - min_num, max_num = settings['range'] - max_attempts = settings['attempts'] - - print(f"\nšŸŽ® Starting {settings['name']} mode!") - print(f"Number range: {min_num} to {max_num}") - print(f"Maximum attempts: {max_attempts}") - print("-" * 40) - - # Generate secret number - secret_number = random.randint(min_num, max_num) - attempts = 0 - - # Game loop - while attempts < max_attempts: - guess = self.get_valid_guess(min_num, max_num, attempts + 1) - attempts += 1 - - if guess == secret_number: - # Player wins! - print(f"\nšŸŽ‰ CONGRATULATIONS! šŸŽ‰") - print(f"You guessed the number {secret_number} correctly!") - print(f"It took you {attempts} attempts.") - - # Calculate and show score - score = self.calculate_score(attempts, max_attempts, difficulty) - print(f"Your score: {score} points") - - # Update statistics - self.stats['games_won'] += 1 - self.stats['total_attempts'] += attempts - - # Check for best score - if attempts < self.stats['best_score']['attempts']: - self.stats['best_score']['attempts'] = attempts - self.stats['best_score']['difficulty'] = difficulty - print("šŸ† NEW PERSONAL BEST!") - - return True - - else: - # Provide feedback - if guess < secret_number: - print("šŸ“ˆ Too low!") - else: - print("šŸ“‰ Too high!") - - # Give hint (except on last attempt) - remaining = max_attempts - attempts - if remaining > 0: - hint = self.give_hint(guess, secret_number, min_num, max_num) - print(hint) - print(f"Attempts remaining: {remaining}") - - # Player lost - print(f"\nšŸ’” Game Over!") - print(f"You've used all {max_attempts} attempts.") - print(f"The number was {secret_number}.") - print("Better luck next time!") - - self.stats['total_attempts'] += attempts - return False - - def show_statistics(self): - """Display player statistics""" - if self.stats['games_played'] == 0: - print("No games played yet!") - return - - print("\nšŸ“Š YOUR STATISTICS") - print("=" * 30) - print(f"Games played: {self.stats['games_played']}") - print(f"Games won: {self.stats['games_won']}") - - win_rate = (self.stats['games_won'] / self.stats['games_played']) * 100 - print(f"Win rate: {win_rate:.1f}%") - - if self.stats['games_won'] > 0: - avg_attempts = self.stats['total_attempts'] / self.stats['games_won'] - print(f"Average attempts per win: {avg_attempts:.1f}") - - if self.stats['best_score']['attempts'] != float('inf'): - best_attempts = self.stats['best_score']['attempts'] - best_difficulty = self.stats['best_score']['difficulty'] - print(f"Best score: {best_attempts} attempts ({best_difficulty} mode)") + print("Too high! Try again.") - def play_again(self): - """Ask if player wants to play again""" - while True: - choice = input("\nWould you like to play again? (y/n): ").lower() - if choice in ['y', 'yes']: - return True - elif choice in ['n', 'no']: - return False - else: - print("Please enter 'y' for yes or 'n' for no.") - - def run(self): - """Main game loop""" - self.display_welcome() - - while True: - self.play_round() - self.show_statistics() - - if not self.play_again(): - break - - print("\nšŸŽÆ Thanks for playing the Number Guessing Game!") - print("Hope you had fun! šŸ‘‹") - -if __name__ == "__main__": - game = NumberGuessingGame() - game.run() + else: + print(f"Game over! The number was {secret_number}") ``` ---- - -## šŸ’¾ Phase 3: Advanced Features with Persistence - -### Learning Objectives -- Implement file operations for data persistence -- Add high score tracking across sessions -- Create multiple game modes -- Implement achievement system -- Add game replay and analysis features - -### Implementation - +### Difficulty Settings ```python -# advanced_guessing_game.py +def choose_difficulty(): + print("\nChoose difficulty:") + print("1. Easy (1-50, 10 attempts)") + print("2. Medium (1-100, 7 attempts)") + print("3. Hard (1-500, 12 attempts)") + + while True: + choice = input("Enter your choice (1-3): ") + if choice in ['1', '2', '3']: + return int(choice) + print("Please enter 1, 2, or 3") + +def get_difficulty_settings(difficulty): + settings = { + 1: (1, 50, 10), # Easy + 2: (1, 100, 7), # Medium + 3: (1, 500, 12) # Hard + } + return settings[difficulty] +``` -import random -import json -import os -from datetime import datetime -import time +## Score and Statistics -class AdvancedGuessingGame: - def __init__(self): - self.data_file = "game_data.json" - self.difficulties = { - 'easy': {'range': (1, 50), 'attempts': 15, 'name': 'Easy'}, - 'medium': {'range': (1, 100), 'attempts': 10, 'name': 'Medium'}, - 'hard': {'range': (1, 200), 'attempts': 8, 'name': 'Hard'}, - 'expert': {'range': (1, 500), 'attempts': 12, 'name': 'Expert'}, - 'custom': {'range': None, 'attempts': None, 'name': 'Custom'} - } - - self.achievements = { - 'first_win': {'name': 'First Victory', 'desc': 'Win your first game', 'unlocked': False}, - 'perfectionist': {'name': 'Perfectionist', 'desc': 'Win in 3 attempts or less', 'unlocked': False}, - 'persistent': {'name': 'Persistent', 'desc': 'Play 10 games', 'unlocked': False}, - 'lucky_streak': {'name': 'Lucky Streak', 'desc': 'Win 3 games in a row', 'unlocked': False}, - 'expert_player': {'name': 'Expert Player', 'desc': 'Win on Expert difficulty', 'unlocked': False} - } - - self.load_data() - - def load_data(self): - """Load game data from file""" - try: - if os.path.exists(self.data_file): - with open(self.data_file, 'r') as f: - data = json.load(f) - self.stats = data.get('stats', self.get_default_stats()) - self.high_scores = data.get('high_scores', []) - self.achievements = {**self.achievements, **data.get('achievements', {})} - self.game_history = data.get('game_history', []) - else: - self.stats = self.get_default_stats() - self.high_scores = [] - self.game_history = [] - except Exception as e: - print(f"Warning: Could not load game data - {e}") - self.stats = self.get_default_stats() - self.high_scores = [] - self.game_history = [] - - def save_data(self): - """Save game data to file""" - try: - data = { - 'stats': self.stats, - 'high_scores': self.high_scores, - 'achievements': self.achievements, - 'game_history': self.game_history - } - with open(self.data_file, 'w') as f: - json.dump(data, f, indent=2) - except Exception as e: - print(f"Warning: Could not save game data - {e}") - - def get_default_stats(self): - """Return default statistics""" - return { - 'games_played': 0, - 'games_won': 0, - 'total_attempts': 0, - 'win_streak': 0, - 'best_streak': 0, - 'total_score': 0, - 'difficulty_wins': {'easy': 0, 'medium': 0, 'hard': 0, 'expert': 0, 'custom': 0} - } - - def display_main_menu(self): - """Display main menu""" - print("\\n" + "=" * 60) - print("šŸŽÆ ADVANCED NUMBER GUESSING GAME šŸŽÆ".center(60)) - print("=" * 60) - print("1. šŸŽ® Play Game") - print("2. šŸ“Š View Statistics") - print("3. šŸ† High Scores") - print("4. šŸŽ–ļø Achievements") - print("5. šŸ“ˆ Game History") - print("6. āš™ļø Custom Game") - print("7. ā“ How to Play") - print("8. 🚪 Exit") - print("=" * 60) - - def custom_game_setup(self): - """Set up custom game parameters""" - print("\\nšŸ› ļø CUSTOM GAME SETUP") - print("-" * 30) - - # Get custom range - while True: - try: - min_num = int(input("Enter minimum number: ")) - max_num = int(input("Enter maximum number: ")) - - if min_num >= max_num: - print("āŒ Maximum must be greater than minimum!") - continue - - range_size = max_num - min_num + 1 - if range_size < 2: - print("āŒ Range must contain at least 2 numbers!") - continue - - break - except ValueError: - print("āŒ Please enter valid numbers!") - - # Calculate suggested attempts - suggested_attempts = max(5, int(range_size ** 0.5) + 3) - - while True: - try: - print(f"\\nSuggested attempts for this range: {suggested_attempts}") - attempts = int(input("Enter maximum attempts: ")) - - if attempts < 1: - print("āŒ Must have at least 1 attempt!") - continue - - break - except ValueError: - print("āŒ Please enter a valid number!") - - return {'range': (min_num, max_num), 'attempts': attempts, 'name': 'Custom'} - - def play_game_mode(self): - """Handle game mode selection and play""" - print("\\nšŸŽ® GAME MODES") - print("-" * 20) - - for key, value in self.difficulties.items(): - if key == 'custom': - print(f"{key[0].upper()}. {value['name']}: Create your own challenge") - else: - min_num, max_num = value['range'] - attempts = value['attempts'] - print(f"{key[0].upper()}. {value['name']}: {min_num}-{max_num} ({attempts} attempts)") - - while True: - choice = input("\\nChoose game mode (e/m/h/x/c): ").lower() - - if choice in ['e', 'm', 'h', 'x']: - difficulty_map = {'e': 'easy', 'm': 'medium', 'h': 'hard', 'x': 'expert'} - return self.play_round(difficulty_map[choice]) - elif choice == 'c': - custom_settings = self.custom_game_setup() - return self.play_round('custom', custom_settings) - else: - print("āŒ Invalid choice!") - - def play_round(self, difficulty, custom_settings=None): - """Play a single round""" - if difficulty == 'custom': - settings = custom_settings - else: - settings = self.difficulties[difficulty] - - min_num, max_num = settings['range'] - max_attempts = settings['attempts'] - - print(f"\\nšŸŽ® {settings['name']} Mode") - print(f"Range: {min_num} to {max_num}") - print(f"Max attempts: {max_attempts}") - print("-" * 40) - - secret_number = random.randint(min_num, max_num) - attempts = 0 - start_time = time.time() - guess_history = [] - - while attempts < max_attempts: - guess = self.get_valid_guess(min_num, max_num, attempts + 1) - attempts += 1 - guess_history.append(guess) - - if guess == secret_number: - end_time = time.time() - game_time = end_time - start_time - - print(f"\\nšŸŽ‰ VICTORY! šŸŽ‰") - print(f"Number: {secret_number}") - print(f"Attempts: {attempts}") - print(f"Time: {game_time:.1f} seconds") - - score = self.calculate_score(attempts, max_attempts, difficulty, game_time) - print(f"Score: {score}") - - self.update_stats_win(attempts, difficulty, score, game_time, guess_history, secret_number) - return True - - else: - feedback = "šŸ“ˆ Too low!" if guess < secret_number else "šŸ“‰ Too high!" - print(feedback) - - remaining = max_attempts - attempts - if remaining > 0: - hint = self.get_smart_hint(guess_history, secret_number, min_num, max_num) - print(hint) - print(f"Remaining: {remaining}") - - # Game lost - end_time = time.time() - game_time = end_time - start_time - print(f"\\nšŸ’” Game Over! Number was {secret_number}") - - self.update_stats_loss(attempts, difficulty, game_time, guess_history, secret_number) - return False - - def get_smart_hint(self, guess_history, secret_number, min_num, max_num): - """Provide intelligent hints based on guess history""" - last_guess = guess_history[-1] - difference = abs(last_guess - secret_number) - range_size = max_num - min_num - - # Analyze guess pattern - if len(guess_history) >= 2: - prev_diff = abs(guess_history[-2] - secret_number) - if difference < prev_diff: - trend = "šŸŽÆ Getting warmer!" - elif difference > prev_diff: - trend = "ā„ļø Getting colder!" - else: - trend = "ā†”ļø Same distance..." - else: - trend = "" - - # Distance hint - if difference <= range_size * 0.05: - distance = "šŸ”„ Burning hot!" - elif difference <= range_size * 0.15: - distance = "ā™Øļø Very warm!" - elif difference <= range_size * 0.30: - distance = "šŸŒ”ļø Warm..." - elif difference <= range_size * 0.50: - distance = "🧊 Cool." - else: - distance = "🄶 Very cold!" - - return f"{distance} {trend}" - - def update_stats_win(self, attempts, difficulty, score, game_time, guess_history, secret_number): - """Update statistics for a win""" - self.stats['games_played'] += 1 - self.stats['games_won'] += 1 - self.stats['total_attempts'] += attempts - self.stats['win_streak'] += 1 - self.stats['total_score'] += score - self.stats['difficulty_wins'][difficulty] += 1 - - if self.stats['win_streak'] > self.stats['best_streak']: - self.stats['best_streak'] = self.stats['win_streak'] - - # Add to high scores - self.add_high_score(score, attempts, difficulty, game_time) - - # Add to game history - self.add_to_history(True, attempts, difficulty, score, game_time, guess_history, secret_number) - - # Check achievements - self.check_achievements(attempts, difficulty) - - self.save_data() - - def update_stats_loss(self, attempts, difficulty, game_time, guess_history, secret_number): - """Update statistics for a loss""" - self.stats['games_played'] += 1 - self.stats['total_attempts'] += attempts - self.stats['win_streak'] = 0 - - # Add to game history - self.add_to_history(False, attempts, difficulty, 0, game_time, guess_history, secret_number) - - self.save_data() - - def add_high_score(self, score, attempts, difficulty, game_time): - """Add score to high scores list""" - high_score = { - 'score': score, - 'attempts': attempts, - 'difficulty': difficulty, - 'time': game_time, - 'date': datetime.now().strftime('%Y-%m-%d %H:%M') - } - - self.high_scores.append(high_score) - self.high_scores.sort(key=lambda x: x['score'], reverse=True) - self.high_scores = self.high_scores[:10] # Keep top 10 - - def add_to_history(self, won, attempts, difficulty, score, game_time, guess_history, secret_number): - """Add game to history""" - game_record = { - 'date': datetime.now().strftime('%Y-%m-%d %H:%M'), - 'won': won, - 'attempts': attempts, - 'difficulty': difficulty, - 'score': score, - 'time': game_time, - 'secret_number': secret_number, - 'guesses': guess_history - } - - self.game_history.append(game_record) - - # Keep only last 100 games - if len(self.game_history) > 100: - self.game_history = self.game_history[-100:] - - def check_achievements(self, attempts, difficulty): - """Check and unlock achievements""" - new_achievements = [] - - # First win - if not self.achievements['first_win']['unlocked'] and self.stats['games_won'] == 1: - self.achievements['first_win']['unlocked'] = True - new_achievements.append('first_win') - - # Perfectionist (3 attempts or less) - if not self.achievements['perfectionist']['unlocked'] and attempts <= 3: - self.achievements['perfectionist']['unlocked'] = True - new_achievements.append('perfectionist') - - # Persistent (10 games) - if not self.achievements['persistent']['unlocked'] and self.stats['games_played'] >= 10: - self.achievements['persistent']['unlocked'] = True - new_achievements.append('persistent') - - # Lucky streak (3 wins in a row) - if not self.achievements['lucky_streak']['unlocked'] and self.stats['win_streak'] >= 3: - self.achievements['lucky_streak']['unlocked'] = True - new_achievements.append('lucky_streak') - - # Expert player - if not self.achievements['expert_player']['unlocked'] and difficulty == 'expert': - self.achievements['expert_player']['unlocked'] = True - new_achievements.append('expert_player') - - # Display new achievements - for achievement in new_achievements: - info = self.achievements[achievement] - print(f"\\nšŸŽ–ļø ACHIEVEMENT UNLOCKED: {info['name']}") - print(f" {info['desc']}") - - def calculate_score(self, attempts, max_attempts, difficulty, game_time): - """Calculate game score""" - base_score = 1000 - - # Difficulty multiplier - multipliers = {'easy': 1, 'medium': 1.5, 'hard': 2, 'expert': 3, 'custom': 1.2} - difficulty_bonus = base_score * (multipliers.get(difficulty, 1) - 1) - - # Attempt bonus (more points for fewer attempts) - attempt_bonus = (max_attempts - attempts) * 100 - - # Time bonus (bonus for quick thinking, but not too harsh) - time_bonus = max(0, 500 - int(game_time * 10)) - - total_score = int(base_score + difficulty_bonus + attempt_bonus + time_bonus) - return max(100, total_score) # Minimum score of 100 - - def show_statistics(self): - """Display detailed statistics""" - print("\\nšŸ“Š GAME STATISTICS") - print("=" * 40) - - if self.stats['games_played'] == 0: - print("No games played yet!") - return - - print(f"Games played: {self.stats['games_played']}") - print(f"Games won: {self.stats['games_won']}") - - win_rate = (self.stats['games_won'] / self.stats['games_played']) * 100 - print(f"Win rate: {win_rate:.1f}%") - print(f"Current streak: {self.stats['win_streak']}") - print(f"Best streak: {self.stats['best_streak']}") - print(f"Total score: {self.stats['total_score']}") - - if self.stats['games_won'] > 0: - avg_attempts = self.stats['total_attempts'] / self.stats['games_won'] - avg_score = self.stats['total_score'] / self.stats['games_won'] - print(f"Avg attempts/win: {avg_attempts:.1f}") - print(f"Avg score/win: {avg_score:.0f}") - - print("\\nWins by difficulty:") - for diff, wins in self.stats['difficulty_wins'].items(): - if wins > 0: - print(f" {diff.title()}: {wins}") - - def show_high_scores(self): - """Display high scores""" - print("\\nšŸ† HIGH SCORES") - print("=" * 50) - - if not self.high_scores: - print("No high scores yet!") - return - - for i, score in enumerate(self.high_scores, 1): - print(f"{i:2d}. {score['score']:4d} pts | " - f"{score['attempts']} attempts | " - f"{score['difficulty'].title()} | " - f"{score['date']}") - - def show_achievements(self): - """Display achievements""" - print("\\nšŸŽ–ļø ACHIEVEMENTS") - print("=" * 40) - - unlocked_count = sum(1 for ach in self.achievements.values() if ach['unlocked']) - total_count = len(self.achievements) - print(f"Unlocked: {unlocked_count}/{total_count}") - print() - - for key, ach in self.achievements.items(): - status = "āœ…" if ach['unlocked'] else "šŸ”’" - print(f"{status} {ach['name']}") - print(f" {ach['desc']}") - print() - - def show_game_history(self): - """Display recent game history""" - print("\\nšŸ“ˆ GAME HISTORY (Last 10)") - print("=" * 60) - - if not self.game_history: - print("No games in history!") - return - - recent_games = self.game_history[-10:] - - for game in reversed(recent_games): - result = "WON" if game['won'] else "LOST" - score_text = f"{game['score']} pts" if game['won'] else "0 pts" - - print(f"{game['date']} | {result:4s} | " - f"{game['attempts']} attempts | " - f"{game['difficulty'].title():6s} | " - f"{score_text}") - - def show_how_to_play(self): - """Display game instructions""" - print("\\nā“ HOW TO PLAY") - print("=" * 40) - print("1. Choose a difficulty level or create custom game") - print("2. I'll think of a number within the chosen range") - print("3. You guess the number") - print("4. I'll tell you if your guess is too high or low") - print("5. Keep guessing until you find the number or run out of attempts") - print("\\nScoring:") - print("• Base score varies by difficulty") - print("• Bonus points for fewer attempts") - print("• Time bonus for quick solving") - print("• Unlock achievements for special accomplishments") - print("\\nHints:") - print("• šŸ”„ = Very close") - print("• ā™Øļø = Close") - print("• šŸŒ”ļø = Warm") - print("• 🧊 = Cold") - print("• šŸŽÆ = Getting closer") - print("• ā„ļø = Getting further") +### Score Calculation +```python +def calculate_score(attempts, max_attempts, difficulty): + # Base score depends on difficulty + base_scores = {1: 100, 2: 200, 3: 500} + base_score = base_scores[difficulty] - def get_valid_guess(self, min_num, max_num, attempt_num): - """Get valid guess with better formatting""" - while True: - try: - guess = int(input(f"\\n[{attempt_num}] Your guess ({min_num}-{max_num}): ")) - - if min_num <= guess <= max_num: - return guess - else: - print(f"āŒ Number must be between {min_num} and {max_num}!") - - except ValueError: - print("āŒ Please enter a valid number!") + # Bonus for fewer attempts + attempt_bonus = max(0, (max_attempts - attempts) * 10) - def run(self): - """Main game loop""" - print("Welcome to the Advanced Number Guessing Game! šŸŽÆ") - - while True: - self.display_main_menu() - - choice = input("\\nEnter your choice (1-8): ").strip() - - if choice == '1': - self.play_game_mode() - elif choice == '2': - self.show_statistics() - elif choice == '3': - self.show_high_scores() - elif choice == '4': - self.show_achievements() - elif choice == '5': - self.show_game_history() - elif choice == '6': - custom_settings = self.custom_game_setup() - self.play_round('custom', custom_settings) - elif choice == '7': - self.show_how_to_play() - elif choice == '8': - print("\\nšŸ‘‹ Thanks for playing! See you next time!") - self.save_data() - break - else: - print("āŒ Invalid choice! Please enter 1-8.") - - input("\\nPress Enter to continue...") - -if __name__ == "__main__": - game = AdvancedGuessingGame() - game.run() + return base_score + attempt_bonus ``` ---- - -## šŸŽØ Phase 4: GUI Version (Optional) - -### Implementation - +### High Score Tracking ```python -# gui_guessing_game.py - -import tkinter as tk -from tkinter import ttk, messagebox -import random import json -from datetime import datetime -class GUIGuessingGame: - def __init__(self, root): - self.root = root - self.root.title("Number Guessing Game") - self.root.geometry("500x600") - self.root.resizable(False, False) - - # Game variables - self.secret_number = None - self.attempts = 0 - self.max_attempts = 10 - self.min_num = 1 - self.max_num = 100 - self.game_in_progress = False - - # Statistics - self.stats = {'games_played': 0, 'games_won': 0, 'total_attempts': 0} - self.load_stats() - - self.setup_ui() - self.new_game() - - def setup_ui(self): - """Set up the user interface""" - # Main frame - main_frame = ttk.Frame(self.root, padding="20") - main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S)) - - # Title - title_label = ttk.Label( - main_frame, - text="šŸŽÆ Number Guessing Game", - font=('Arial', 18, 'bold') - ) - title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))\n - # Game info frame - info_frame = ttk.LabelFrame(main_frame, text="Game Info", padding="10") - info_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10)) - - self.range_label = ttk.Label(info_frame, text="Range: 1-100") - self.range_label.grid(row=0, column=0, sticky=tk.W) - - self.attempts_label = ttk.Label(info_frame, text="Attempts: 0/10") - self.attempts_label.grid(row=0, column=1, sticky=tk.E) - - # Difficulty selection - diff_frame = ttk.LabelFrame(main_frame, text="Difficulty", padding="10") - diff_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10)) - - self.difficulty_var = tk.StringVar(value="medium") - difficulties = [ - ("Easy (1-50, 15 attempts)", "easy"), - ("Medium (1-100, 10 attempts)", "medium"), - ("Hard (1-200, 8 attempts)", "hard") - ] - - for i, (text, value) in enumerate(difficulties): - rb = ttk.Radiobutton( - diff_frame, - text=text, - variable=self.difficulty_var, - value=value, - command=self.on_difficulty_change - ) - rb.grid(row=i, column=0, sticky=tk.W) - - # Input frame - input_frame = ttk.LabelFrame(main_frame, text="Your Guess", padding="10") - input_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10)) - - self.guess_var = tk.StringVar() - self.guess_entry = ttk.Entry( - input_frame, - textvariable=self.guess_var, - font=('Arial', 14), - width=10, - justify='center' - ) - self.guess_entry.grid(row=0, column=0, padx=(0, 10)) - self.guess_entry.bind('', lambda e: self.make_guess()) - - self.guess_button = ttk.Button( - input_frame, - text="Guess!", - command=self.make_guess - ) - self.guess_button.grid(row=0, column=1) - - # Feedback frame - feedback_frame = ttk.LabelFrame(main_frame, text="Feedback", padding="10") - feedback_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10)) - - self.feedback_text = tk.Text( - feedback_frame, - height=8, - width=50, - font=('Arial', 10), - state='disabled', - wrap=tk.WORD - ) - self.feedback_text.grid(row=0, column=0, sticky=(tk.W, tk.E)) - - # Scrollbar for feedback - scrollbar = ttk.Scrollbar(feedback_frame, orient="vertical", command=self.feedback_text.yview) - scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S)) - self.feedback_text.configure(yscrollcommand=scrollbar.set) - - # Control buttons - button_frame = ttk.Frame(main_frame) - button_frame.grid(row=5, column=0, columnspan=2, pady=(10, 0))\n - ttk.Button(button_frame, text="New Game", command=self.new_game).grid(row=0, column=0, padx=(0, 10)) - ttk.Button(button_frame, text="Statistics", command=self.show_stats).grid(row=0, column=1, padx=(0, 10)) - ttk.Button(button_frame, text="Hint", command=self.give_hint).grid(row=0, column=2) - - # Configure grid weights - main_frame.columnconfigure(0, weight=1) - main_frame.columnconfigure(1, weight=1) - info_frame.columnconfigure(1, weight=1) - feedback_frame.columnconfigure(0, weight=1) - - def load_stats(self): - """Load statistics from file""" - try: - with open("gui_game_stats.json", "r") as f: - self.stats = json.load(f) - except FileNotFoundError: - pass - - def save_stats(self): - """Save statistics to file""" - try: - with open("gui_game_stats.json", "w") as f: - json.dump(self.stats, f) - except Exception as e: - print(f"Could not save stats: {e}") - - def on_difficulty_change(self): - """Handle difficulty change""" - if not self.game_in_progress: - self.new_game() - - def new_game(self): - """Start a new game""" - difficulty = self.difficulty_var.get() - - if difficulty == "easy": - self.min_num, self.max_num = 1, 50 - self.max_attempts = 15 - elif difficulty == "medium": - self.min_num, self.max_num = 1, 100 - self.max_attempts = 10 - elif difficulty == "hard": - self.min_num, self.max_num = 1, 200 - self.max_attempts = 8 - - self.secret_number = random.randint(self.min_num, self.max_num) - self.attempts = 0 - self.game_in_progress = True - - # Update UI - self.range_label.config(text=f"Range: {self.min_num}-{self.max_num}") - self.attempts_label.config(text=f"Attempts: {self.attempts}/{self.max_attempts}") - self.guess_var.set("") - self.guess_entry.config(state='normal') - self.guess_button.config(state='normal') - - # Clear and update feedback - self.update_feedback("šŸŽÆ New game started! I'm thinking of a number between " - f"{self.min_num} and {self.max_num}.\\n" - f"You have {self.max_attempts} attempts. Good luck!\\n" - + "="*50 + "\\n") - - def update_feedback(self, message): - """Update the feedback text area""" - self.feedback_text.config(state='normal') - self.feedback_text.insert(tk.END, message + "\\n") - self.feedback_text.config(state='disabled') - self.feedback_text.see(tk.END) - - def make_guess(self): - """Process the player's guess""" - if not self.game_in_progress: - messagebox.showinfo("Game Over", "Please start a new game!") - return - - try: - guess = int(self.guess_var.get()) - except ValueError: - messagebox.showerror("Invalid Input", "Please enter a valid number!") - return - - if guess < self.min_num or guess > self.max_num: - messagebox.showerror("Invalid Range", - f"Please enter a number between {self.min_num} and {self.max_num}!") - return - - self.attempts += 1 - self.attempts_label.config(text=f"Attempts: {self.attempts}/{self.max_attempts}") - - if guess == self.secret_number: - # Player wins! - self.update_feedback(f"šŸŽ‰ CONGRATULATIONS! You guessed {self.secret_number} correctly!") - self.update_feedback(f"It took you {self.attempts} attempts.") - - # Calculate score - score = max(100, 1000 - (self.attempts - 1) * 100) - self.update_feedback(f"Your score: {score} points") - - # Update statistics - self.stats['games_played'] += 1 - self.stats['games_won'] += 1 - self.stats['total_attempts'] += self.attempts - self.save_stats() - - self.end_game() - - elif self.attempts >= self.max_attempts: - # Player loses - self.update_feedback(f"šŸ’” Game Over! You've used all {self.max_attempts} attempts.") - self.update_feedback(f"The number was {self.secret_number}.") - - # Update statistics - self.stats['games_played'] += 1 - self.stats['total_attempts'] += self.attempts - self.save_stats() - - self.end_game() - - else: - # Continue game - if guess < self.secret_number: - feedback = f"šŸ“ˆ {guess} is too low!" - else: - feedback = f"šŸ“‰ {guess} is too high!" - - remaining = self.max_attempts - self.attempts - feedback += f" {remaining} attempts remaining." - - # Add hint - difference = abs(guess - self.secret_number) - range_size = self.max_num - self.min_num - - if difference <= range_size * 0.1: - feedback += " šŸ”„ You're very close!" - elif difference <= range_size * 0.25: - feedback += " ā™Øļø You're getting warm!" - elif difference <= range_size * 0.5: - feedback += " šŸŒ”ļø You're in the right area..." - else: - feedback += " 🧊 You're quite far off." - - self.update_feedback(feedback) - - self.guess_var.set("") - - def give_hint(self): - """Provide a hint to the player""" - if not self.game_in_progress: - messagebox.showinfo("Game Over", "Please start a new game!") - return - - # Generate range hint - quarter = (self.max_num - self.min_num) // 4 - - if self.secret_number <= self.min_num + quarter: - hint = f"šŸ’” Hint: The number is in the lower quarter ({self.min_num}-{self.min_num + quarter})" - elif self.secret_number <= self.min_num + 2 * quarter: - hint = f"šŸ’” Hint: The number is in the lower half ({self.min_num}-{self.min_num + 2 * quarter})" - elif self.secret_number <= self.min_num + 3 * quarter: - hint = f"šŸ’” Hint: The number is in the upper half ({self.min_num + 2 * quarter + 1}-{self.max_num})" - else: - hint = f"šŸ’” Hint: The number is in the upper quarter ({self.min_num + 3 * quarter + 1}-{self.max_num})" - - self.update_feedback(hint) - - def end_game(self): - """End the current game""" - self.game_in_progress = False - self.guess_entry.config(state='disabled') - self.guess_button.config(state='disabled') - self.update_feedback("\\nGame ended. Click 'New Game' to play again!") - - def show_stats(self): - """Show game statistics""" - if self.stats['games_played'] == 0: - message = "No games played yet!" - else: - win_rate = (self.stats['games_won'] / self.stats['games_played']) * 100 - avg_attempts = self.stats['total_attempts'] / max(self.stats['games_won'], 1) - - message = f"""šŸ“Š Game Statistics - -Games Played: {self.stats['games_played']} -Games Won: {self.stats['games_won']} -Win Rate: {win_rate:.1f}% -Average Attempts per Win: {avg_attempts:.1f}""" - - messagebox.showinfo("Statistics", message) - -if __name__ == "__main__": - root = tk.Tk() - game = GUIGuessingGame(root) - root.mainloop() +def save_high_score(score, difficulty): + try: + with open('high_scores.json', 'r') as f: + scores = json.load(f) + except FileNotFoundError: + scores = {'easy': 0, 'medium': 0, 'hard': 0} + + difficulty_names = {1: 'easy', 2: 'medium', 3: 'hard'} + difficulty_name = difficulty_names[difficulty] + + if score > scores[difficulty_name]: + scores[difficulty_name] = score + print(f"New high score for {difficulty_name} difficulty: {score}!") + + with open('high_scores.json', 'w') as f: + json.dump(scores, f) + return True + return False ``` ---- - -## 🧪 Testing Your Game +## Testing Your Game ### Test Scenarios +- Play through each difficulty level +- Test edge cases (minimum and maximum numbers) +- Test invalid inputs (letters, negative numbers) +- Test winning on first guess vs. using all attempts +- Verify score calculation and high score saving -1. **Basic Functionality** - - Test winning on first guess - - Test winning on last attempt - - Test losing (using all attempts) - - Test different difficulty levels +### Input Validation +- Handle non-numeric input gracefully +- Ensure guesses are within the valid range +- Provide clear error messages -2. **Input Validation** - - Enter non-numeric input - - Enter numbers outside the range - - Enter negative numbers - - Enter decimal numbers - -3. **Edge Cases** - - Minimum and maximum numbers in range - - Boundary values - - Very large or small ranges (custom mode) - -4. **Persistence Testing** - - Play multiple games and check statistics - - Close and reopen the program - - Verify high scores are saved - - Check achievement unlocking - ---- - -## šŸš€ Project Extensions +## Extensions and Improvements ### Beginner Extensions -1. **Themed Versions**: Animals, colors, or movie guessing -2. **Multiplayer Mode**: Two players take turns guessing -3. **Sound Effects**: Add audio feedback for wins/losses -4. **Different Number Types**: Fractions, negative numbers +- Add a hint system (show if guess is within 10 of the target) +- Create themed versions (guess the age, price, etc.) +- Add sound effects for correct/incorrect guesses +- Implement a simple AI that tries to guess your number ### Intermediate Extensions -1. **AI Opponent**: Computer tries to guess your number -2. **Tournament Mode**: Best of 5 games with scoring -3. **Category System**: Math facts, historical dates, etc. -4. **Mobile Version**: Convert to web app or mobile app +- Multiplayer mode (players take turns) +- Tournament system with multiple rounds +- Different number types (decimals, negative numbers) +- Word guessing variation ### Advanced Extensions -1. **Machine Learning**: AI learns your guessing patterns -2. **Network Multiplayer**: Play against remote players -3. **Adaptive Difficulty**: Game adjusts based on performance -4. **Voice Recognition**: Speak your guesses +- Machine learning to analyze player patterns +- Web-based version with leaderboards +- Mobile app version +- Voice recognition for guesses ---- +## Learning Outcomes -## šŸ† Conclusion +After completing this project, you'll understand: +- How to generate and work with random numbers +- Loop control and conditional logic +- Input validation and error handling +- File operations for data persistence +- Basic game development principles +- User interface design -Congratulations! You've built a complete number guessing game that demonstrates: +## File Structure -- **Game Logic**: Random generation and comparison algorithms -- **User Interface**: Both console and GUI versions -- **Data Management**: Statistics, high scores, and persistence -- **Error Handling**: Input validation and edge cases -- **Code Organization**: Classes, functions, and modularity +``` +number_guessing_game/ +ā”œā”€ā”€ basic_game.py # Phase 1 simple version +ā”œā”€ā”€ enhanced_game.py # Phase 2 with difficulty +ā”œā”€ā”€ advanced_game.py # Phase 3 with scores +ā”œā”€ā”€ gui_game.py # Phase 4 GUI version +ā”œā”€ā”€ high_scores.json # High score data +└── README.md # Project documentation +``` -### Skills Practiced +## Next Steps -āœ… **Control Structures** (loops, conditionals) -āœ… **Random Number Generation** -āœ… **Input Validation** -āœ… **File Operations** -āœ… **Object-Oriented Programming** -āœ… **GUI Programming** -āœ… **Data Persistence** -āœ… **Statistics and Analytics** -āœ… **Achievement Systems** +Once you've completed your guessing game: +1. Challenge friends and family to beat your high scores +2. Add your own creative features and themes +3. Try implementing the AI guesser version +4. Move on to the Password Generator project +5. Share your game and get feedback from others -**Excellent work!** šŸŽ‰ Ready for your next project? Try the [Password Generator](../PasswordGenerator/README.md) or explore other projects in the [Projects Directory](../README.md). \ No newline at end of file +Great work on building an entertaining and educational game! \ No newline at end of file diff --git a/Projects/Beginners/PasswordGenerator/README.md b/Projects/Beginners/PasswordGenerator/README.md index 022d849..c787158 100644 --- a/Projects/Beginners/PasswordGenerator/README.md +++ b/Projects/Beginners/PasswordGenerator/README.md @@ -1 +1,190 @@ -# Password Generator Project\n\nCreate a secure password generator with customizable options for different security requirements.\n\n## Project Overview\n\n**What you'll build**: A password generator that creates random, secure passwords with various customization options including length, character types, and complexity rules.\n\n**What you'll learn**:\n- String manipulation and character sets\n- Random number generation and selection\n- User input validation\n- File operations for saving passwords\n- Security best practices for passwords\n\n## Project Features\n\n### Basic Features\n- Generate random passwords of specified length\n- Include/exclude different character types (letters, numbers, symbols)\n- Basic user interface for password generation\n- Display generated password to user\n\n### Advanced Features\n- Password strength evaluation\n- Save generated passwords to file\n- Bulk password generation\n- Custom character sets\n- Password history and management\n- GUI interface option\n\n## Implementation Guide\n\n### Phase 1: Basic Password Generator\n**Time**: 1-2 hours\n\nCreate a simple password generator:\n\n```python\nimport random\nimport string\n\ndef generate_password(length=12):\n characters = string.ascii_letters + string.digits + string.punctuation\n password = ''.join(random.choice(characters) for _ in range(length))\n return password\n\n# Usage\npassword = generate_password(16)\nprint(f\"Generated password: {password}\")\n```\n\n**Key concepts**: Random selection, string concatenation, loops\n\n### Phase 2: Customizable Generator\n**Time**: 2-3 hours\n\nAdd customization options:\n- Choose password length\n- Select character types to include\n- Exclude similar characters (0, O, l, I)\n- Ensure minimum requirements (at least one number, symbol, etc.)\n\n**Key concepts**: Functions with parameters, conditional logic, input validation\n\n### Phase 3: Advanced Features\n**Time**: 3-4 hours\n\nImplement additional functionality:\n- Password strength checker\n- Save passwords to encrypted file\n- Generate multiple passwords at once\n- Memorable password options (using words)\n\n**Key concepts**: File operations, encryption basics, data structures\n\n### Phase 4: GUI Application\n**Time**: 4-5 hours\n\nCreate a graphical interface:\n- Checkboxes for character type selection\n- Slider for password length\n- Copy to clipboard functionality\n- Password history display\n\n**Key concepts**: GUI programming, event handling, clipboard operations\n\n## Getting Started\n\n### Setup\n1. Create a new project directory\n2. Set up your Python environment\n3. Import required modules (random, string, tkinter for GUI)\n\n### Basic Structure\n```python\nimport random\nimport string\n\nclass PasswordGenerator:\n def __init__(self):\n self.lowercase = string.ascii_lowercase\n self.uppercase = string.ascii_uppercase\n self.digits = string.digits\n self.symbols = string.punctuation\n \n def generate(self, length, use_lowercase=True, use_uppercase=True, \n use_digits=True, use_symbols=True):\n # Implementation here\n pass\n```\n\n## Testing Your Generator\n\n### Test Cases\n- Generate passwords of different lengths (8, 12, 16, 32 characters)\n- Test with different character set combinations\n- Verify password strength requirements\n- Test edge cases (minimum length, maximum length)\n- Ensure randomness (generate multiple passwords, check for patterns)\n\n### Security Considerations\n- Use cryptographically secure random number generation for production\n- Never log or store passwords in plain text\n- Implement proper clipboard clearing\n- Consider password expiration recommendations\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Passphrase generator using word lists\n- Password strength visualization\n- Export passwords to different formats\n- Command line interface\n\n### Intermediate Extensions\n- Integration with password managers\n- Web interface using Flask\n- Password policy compliance checker\n- Bulk generation with CSV export\n\n### Advanced Extensions\n- Secure password storage with encryption\n- Multi-language word support for passphrases\n- API for password generation service\n- Browser extension for password generation\n\n## Common Issues and Solutions\n\n**Issue**: Passwords not random enough\n**Solution**: Use `secrets` module instead of `random` for cryptographic randomness\n\n**Issue**: Generated passwords don't meet requirements\n**Solution**: Implement validation and regeneration logic\n\n**Issue**: GUI freezes during bulk generation\n**Solution**: Use threading for long-running operations\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- How to work with random number generation\n- String manipulation and character sets\n- User input validation and error handling\n- Basic security principles for password generation\n- GUI application development\n- File operations and data persistence\n\n## File Structure\n\n```\npassword_generator/\nā”œā”€ā”€ basic_generator.py # Phase 1 implementation\nā”œā”€ā”€ advanced_generator.py # Phase 2-3 implementation\nā”œā”€ā”€ gui_generator.py # Phase 4 GUI version\nā”œā”€ā”€ password_history.json # Saved password metadata\nā”œā”€ā”€ wordlist.txt # Words for passphrase generation\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your password generator:\n1. Test it thoroughly with different settings\n2. Share your implementation on GitHub\n3. Consider security improvements and best practices\n4. Try building other security-related projects\n5. Explore the Todo List project next\n\nGreat work on building a practical security tool! \ No newline at end of file +# Password Generator Project + +Create a secure password generator with customizable options for different security requirements. + +## Project Overview + +**What you'll build**: A password generator that creates random, secure passwords with various customization options including length, character types, and complexity rules. + +**What you'll learn**: +- String manipulation and character sets +- Random number generation and selection +- User input validation +- File operations for saving passwords +- Security best practices for passwords + +## Project Features + +### Basic Features +- Generate random passwords of specified length +- Include/exclude different character types (letters, numbers, symbols) +- Basic user interface for password generation +- Display generated password to user + +### Advanced Features +- Password strength evaluation +- Save generated passwords to file +- Bulk password generation +- Custom character sets +- Password history and management +- GUI interface option + +## Implementation Guide + +### Phase 1: Basic Password Generator +**Time**: 1-2 hours + +Create a simple password generator: + +```python +import random +import string + +def generate_password(length=12): + characters = string.ascii_letters + string.digits + string.punctuation + password = ''.join(random.choice(characters) for _ in range(length)) + return password + +# Usage +password = generate_password(16) +print(f"Generated password: {password}") +``` + +**Key concepts**: Random selection, string concatenation, loops + +### Phase 2: Customizable Generator +**Time**: 2-3 hours + +Add customization options: +- Choose password length +- Select character types to include +- Exclude similar characters (0, O, l, I) +- Ensure minimum requirements (at least one number, symbol, etc.) + +**Key concepts**: Functions with parameters, conditional logic, input validation + +### Phase 3: Advanced Features +**Time**: 3-4 hours + +Implement additional functionality: +- Password strength checker +- Save passwords to encrypted file +- Generate multiple passwords at once +- Memorable password options (using words) + +**Key concepts**: File operations, encryption basics, data structures + +### Phase 4: GUI Application +**Time**: 4-5 hours + +Create a graphical interface: +- Checkboxes for character type selection +- Slider for password length +- Copy to clipboard functionality +- Password history display + +**Key concepts**: GUI programming, event handling, clipboard operations + +## Getting Started + +### Setup +1. Create a new project directory +2. Set up your Python environment +3. Import required modules (random, string, tkinter for GUI) + +### Basic Structure +```python +import random +import string + +class PasswordGenerator: + def __init__(self): + self.lowercase = string.ascii_lowercase + self.uppercase = string.ascii_uppercase + self.digits = string.digits + self.symbols = string.punctuation + + def generate(self, length, use_lowercase=True, use_uppercase=True, + use_digits=True, use_symbols=True): + # Implementation here + pass +``` + +## Testing Your Generator + +### Test Cases +- Generate passwords of different lengths (8, 12, 16, 32 characters) +- Test with different character set combinations +- Verify password strength requirements +- Test edge cases (minimum length, maximum length) +- Ensure randomness (generate multiple passwords, check for patterns) + +### Security Considerations +- Use cryptographically secure random number generation for production +- Never log or store passwords in plain text +- Implement proper clipboard clearing +- Consider password expiration recommendations + +## Extensions and Improvements + +### Beginner Extensions +- Passphrase generator using word lists +- Password strength visualization +- Export passwords to different formats +- Command line interface + +### Intermediate Extensions +- Integration with password managers +- Web interface using Flask +- Password policy compliance checker +- Bulk generation with CSV export + +### Advanced Extensions +- Secure password storage with encryption +- Multi-language word support for passphrases +- API for password generation service +- Browser extension for password generation + +## Common Issues and Solutions + +**Issue**: Passwords not random enough +**Solution**: Use `secrets` module instead of `random` for cryptographic randomness + +**Issue**: Generated passwords don't meet requirements +**Solution**: Implement validation and regeneration logic + +**Issue**: GUI freezes during bulk generation +**Solution**: Use threading for long-running operations + +## Learning Outcomes + +After completing this project, you'll understand: +- How to work with random number generation +- String manipulation and character sets +- User input validation and error handling +- Basic security principles for password generation +- GUI application development +- File operations and data persistence + +## File Structure + +``` +password_generator/ +ā”œā”€ā”€ basic_generator.py # Phase 1 implementation +ā”œā”€ā”€ advanced_generator.py # Phase 2-3 implementation +ā”œā”€ā”€ gui_generator.py # Phase 4 GUI version +ā”œā”€ā”€ password_history.json # Saved password metadata +ā”œā”€ā”€ wordlist.txt # Words for passphrase generation +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your password generator: +1. Test it thoroughly with different settings +2. Share your implementation on GitHub +3. Consider security improvements and best practices +4. Try building other security-related projects +5. Explore the Todo List project next + +Great work on building a practical security tool! \ No newline at end of file diff --git a/Projects/Beginners/SimpleTextEditor/README.md b/Projects/Beginners/SimpleTextEditor/README.md index 0c4fe1a..981a7b4 100644 --- a/Projects/Beginners/SimpleTextEditor/README.md +++ b/Projects/Beginners/SimpleTextEditor/README.md @@ -1 +1,277 @@ -# Simple Text Editor Project\n\nBuild a basic text editor application with file operations and text manipulation features.\n\n## Project Overview\n\n**What you'll build**: A text editor that can open, edit, and save text files with basic formatting and search functionality.\n\n**What you'll learn**:\n- File input/output operations\n- String manipulation and text processing\n- Basic GUI programming with tkinter\n- Event handling and user interface design\n- Working with text widgets and menus\n\n## Project Features\n\n### Basic Features\n- Open and display text files\n- Edit text content\n- Save files to disk\n- Basic menu system (File, Edit)\n- Text area with scrollbars\n\n### Advanced Features\n- Find and replace functionality\n- Cut, copy, paste operations\n- Undo/redo functionality\n- Word count and statistics\n- Basic text formatting\n- Multiple file tabs\n\n## Implementation Guide\n\n### Phase 1: Basic File Operations\n**Time**: 2-3 hours\n\nCreate command-line text editor:\n- Read file contents\n- Allow text editing\n- Save changes back to file\n- Handle file errors\n\n**Key concepts**: File I/O, string operations, error handling\n\n### Phase 2: GUI Interface\n**Time**: 3-4 hours\n\nBuild graphical interface:\n- Main window with text area\n- File menu (New, Open, Save, Exit)\n- Edit menu (Cut, Copy, Paste)\n- Status bar\n\n**Key concepts**: tkinter GUI, widgets, menu systems\n\n### Phase 3: Enhanced Editing\n**Time**: 3-4 hours\n\nAdd advanced features:\n- Find and replace dialog\n- Undo/redo functionality\n- Line numbers display\n- Word wrap toggle\n- Font size and family selection\n\n**Key concepts**: Advanced GUI programming, text processing\n\n### Phase 4: Advanced Features\n**Time**: 4-5 hours\n\nImplement professional features:\n- Syntax highlighting for code\n- Multiple document interface\n- Auto-save functionality\n- Recent files menu\n- Customizable themes\n\n**Key concepts**: Advanced text processing, configuration management\n\n## Getting Started\n\n### Setup\n1. Create project directory\n2. Plan the user interface layout\n3. Design the file handling system\n\n### Basic Structure\n```python\nimport tkinter as tk\nfrom tkinter import filedialog, messagebox, scrolledtext\n\nclass SimpleTextEditor:\n def __init__(self, root):\n self.root = root\n self.current_file = None\n self.text_changed = False\n self.setup_ui()\n \n def setup_ui(self):\n # Create menu bar\n # Create text area\n # Create status bar\n pass\n```\n\n## User Interface Design\n\n### Main Window Layout\n- Menu bar at top (File, Edit, View, Help)\n- Toolbar with common actions (optional)\n- Large text editing area in center\n- Status bar at bottom showing line/column, word count\n- Scrollbars for text area\n\n### Menu Structure\n```\nFile\nā”œā”€ā”€ New (Ctrl+N)\nā”œā”€ā”€ Open (Ctrl+O)\nā”œā”€ā”€ Save (Ctrl+S)\nā”œā”€ā”€ Save As (Ctrl+Shift+S)\nā”œā”€ā”€ Recent Files\n└── Exit\n\nEdit\nā”œā”€ā”€ Undo (Ctrl+Z)\nā”œā”€ā”€ Redo (Ctrl+Y)\nā”œā”€ā”€ Cut (Ctrl+X)\nā”œā”€ā”€ Copy (Ctrl+C)\nā”œā”€ā”€ Paste (Ctrl+V)\nā”œā”€ā”€ Find (Ctrl+F)\n└── Replace (Ctrl+H)\n```\n\n## Core Functionality\n\n### File Operations\n- New file: Clear text area and reset file path\n- Open file: Use file dialog to select and load file\n- Save file: Write current text to file\n- Save As: Choose new location and save\n\n### Text Editing\n- Standard text input and editing\n- Keyboard shortcuts for common operations\n- Mouse support for selection and cursor positioning\n- Clipboard integration\n\n### Search and Replace\n- Find text with highlighting\n- Replace single or all occurrences\n- Case-sensitive option\n- Regular expression support (advanced)\n\n## Implementation Examples\n\n### Basic File Operations\n```python\ndef open_file(self):\n file_path = filedialog.askopenfilename(\n title=\"Open File\",\n filetypes=[(\"Text Files\", \"*.txt\"), (\"All Files\", \"*.*\")]\n )\n if file_path:\n try:\n with open(file_path, 'r', encoding='utf-8') as file:\n content = file.read()\n self.text_area.delete(1.0, tk.END)\n self.text_area.insert(1.0, content)\n self.current_file = file_path\n self.update_title()\n except Exception as e:\n messagebox.showerror(\"Error\", f\"Could not open file: {e}\")\n```\n\n### Text Change Detection\n```python\ndef on_text_change(self, event=None):\n self.text_changed = True\n self.update_title()\n self.update_status_bar()\n\ndef update_title(self):\n title = \"Simple Text Editor\"\n if self.current_file:\n title += f\" - {os.path.basename(self.current_file)}\"\n if self.text_changed:\n title += \" *\"\n self.root.title(title)\n```\n\n## Testing Your Editor\n\n### Test Scenarios\n- Create new file and add content\n- Open existing text files of various sizes\n- Save files with different names and locations\n- Test cut, copy, paste operations\n- Search for text and replace content\n- Test with special characters and Unicode\n\n### Edge Cases\n- Very large files (performance testing)\n- Files with different encodings\n- Read-only files\n- Network file locations\n- Invalid file paths\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Word count display\n- Simple spell checker\n- Text statistics (characters, lines, paragraphs)\n- Print functionality\n\n### Intermediate Extensions\n- Syntax highlighting for programming languages\n- Auto-completion for common words\n- Plugin system for extensions\n- Customizable keyboard shortcuts\n\n### Advanced Extensions\n- Multiple document interface with tabs\n- Project file management\n- Integration with version control systems\n- Collaborative editing features\n\n## Common Issues and Solutions\n\n**Issue**: Text encoding problems with special characters\n**Solution**: Always specify UTF-8 encoding when reading/writing files\n\n**Issue**: Large files cause application to freeze\n**Solution**: Implement progressive loading and text streaming\n\n**Issue**: Undo/redo not working properly\n**Solution**: Use tkinter's built-in undo functionality or implement custom stack\n\n**Issue**: Find/replace not finding all occurrences\n**Solution**: Implement proper text search algorithms and handle edge cases\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- File I/O operations and error handling\n- GUI programming with tkinter\n- Event-driven programming concepts\n- Text processing and manipulation\n- User interface design principles\n- Software architecture and organization\n\n## File Structure\n\n```\nsimple_text_editor/\nā”œā”€ā”€ basic_editor.py # Phase 1 command-line version\nā”œā”€ā”€ gui_editor.py # Phase 2 basic GUI\nā”œā”€ā”€ advanced_editor.py # Phase 3 enhanced features\nā”œā”€ā”€ full_editor.py # Phase 4 complete version\nā”œā”€ā”€ themes/ # Color themes and settings\n│ └── default.json\nā”œā”€ā”€ icons/ # UI icons (optional)\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your text editor:\n1. Use it to edit your other Python projects!\n2. Add your favorite text editing features\n3. Share your implementation and get feedback\n4. Consider adding syntax highlighting for Python\n5. Try the Contact Book project next for more GUI practice\n\nGreat job on building a practical productivity application! \ No newline at end of file +# Simple Text Editor Project + +Build a basic text editor application with file operations and text manipulation features. + +## Project Overview + +**What you'll build**: A text editor that can open, edit, and save text files with basic formatting and search functionality. + +**What you'll learn**: +- File input/output operations +- String manipulation and text processing +- Basic GUI programming with tkinter +- Event handling and user interface design +- Working with text widgets and menus + +## Project Features + +### Basic Features +- Open and display text files +- Edit text content +- Save files to disk +- Basic menu system (File, Edit) +- Text area with scrollbars + +### Advanced Features +- Find and replace functionality +- Cut, copy, paste operations +- Undo/redo functionality +- Word count and statistics +- Basic text formatting +- Multiple file tabs + +## Implementation Guide + +### Phase 1: Basic File Operations +**Time**: 2-3 hours + +Create command-line text editor: +- Read file contents +- Allow text editing +- Save changes back to file +- Handle file errors + +**Key concepts**: File I/O, string operations, error handling + +### Phase 2: GUI Interface +**Time**: 3-4 hours + +Build graphical interface: +- Main window with text area +- File menu (New, Open, Save, Exit) +- Edit menu (Cut, Copy, Paste) +- Status bar + +**Key concepts**: tkinter GUI, widgets, menu systems + +### Phase 3: Enhanced Editing +**Time**: 3-4 hours + +Add advanced features: +- Find and replace dialog +- Undo/redo functionality +- Line numbers display +- Word wrap toggle +- Font size and family selection + +**Key concepts**: Advanced GUI programming, text processing + +### Phase 4: Advanced Features +**Time**: 4-5 hours + +Implement professional features: +- Syntax highlighting for code +- Multiple document interface +- Auto-save functionality +- Recent files menu +- Customizable themes + +**Key concepts**: Advanced text processing, configuration management + +## Getting Started + +### Setup +1. Create project directory +2. Plan the user interface layout +3. Design the file handling system + +### Basic Structure +```python +import tkinter as tk +from tkinter import filedialog, messagebox, scrolledtext + +class SimpleTextEditor: + def __init__(self, root): + self.root = root + self.current_file = None + self.text_changed = False + self.setup_ui() + + def setup_ui(self): + # Create menu bar + # Create text area + # Create status bar + pass +``` + +## User Interface Design + +### Main Window Layout +- Menu bar at top (File, Edit, View, Help) +- Toolbar with common actions (optional) +- Large text editing area in center +- Status bar at bottom showing line/column, word count +- Scrollbars for text area + +### Menu Structure +``` +File +ā”œā”€ā”€ New (Ctrl+N) +ā”œā”€ā”€ Open (Ctrl+O) +ā”œā”€ā”€ Save (Ctrl+S) +ā”œā”€ā”€ Save As (Ctrl+Shift+S) +ā”œā”€ā”€ Recent Files +└── Exit + +Edit +ā”œā”€ā”€ Undo (Ctrl+Z) +ā”œā”€ā”€ Redo (Ctrl+Y) +ā”œā”€ā”€ Cut (Ctrl+X) +ā”œā”€ā”€ Copy (Ctrl+C) +ā”œā”€ā”€ Paste (Ctrl+V) +ā”œā”€ā”€ Find (Ctrl+F) +└── Replace (Ctrl+H) +``` + +## Core Functionality + +### File Operations +- New file: Clear text area and reset file path +- Open file: Use file dialog to select and load file +- Save file: Write current text to file +- Save As: Choose new location and save + +### Text Editing +- Standard text input and editing +- Keyboard shortcuts for common operations +- Mouse support for selection and cursor positioning +- Clipboard integration + +### Search and Replace +- Find text with highlighting +- Replace single or all occurrences +- Case-sensitive option +- Regular expression support (advanced) + +## Implementation Examples + +### Basic File Operations +```python +def open_file(self): + file_path = filedialog.askopenfilename( + title="Open File", + filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")] + ) + if file_path: + try: + with open(file_path, 'r', encoding='utf-8') as file: + content = file.read() + self.text_area.delete(1.0, tk.END) + self.text_area.insert(1.0, content) + self.current_file = file_path + self.update_title() + except Exception as e: + messagebox.showerror("Error", f"Could not open file: {e}") +``` + +### Text Change Detection +```python +def on_text_change(self, event=None): + self.text_changed = True + self.update_title() + self.update_status_bar() + +def update_title(self): + title = "Simple Text Editor" + if self.current_file: + title += f" - {os.path.basename(self.current_file)}" + if self.text_changed: + title += " *" + self.root.title(title) +``` + +## Testing Your Editor + +### Test Scenarios +- Create new file and add content +- Open existing text files of various sizes +- Save files with different names and locations +- Test cut, copy, paste operations +- Search for text and replace content +- Test with special characters and Unicode + +### Edge Cases +- Very large files (performance testing) +- Files with different encodings +- Read-only files +- Network file locations +- Invalid file paths + +## Extensions and Improvements + +### Beginner Extensions +- Word count display +- Simple spell checker +- Text statistics (characters, lines, paragraphs) +- Print functionality + +### Intermediate Extensions +- Syntax highlighting for programming languages +- Auto-completion for common words +- Plugin system for extensions +- Customizable keyboard shortcuts + +### Advanced Extensions +- Multiple document interface with tabs +- Project file management +- Integration with version control systems +- Collaborative editing features + +## Common Issues and Solutions + +**Issue**: Text encoding problems with special characters +**Solution**: Always specify UTF-8 encoding when reading/writing files + +**Issue**: Large files cause application to freeze +**Solution**: Implement progressive loading and text streaming + +**Issue**: Undo/redo not working properly +**Solution**: Use tkinter's built-in undo functionality or implement custom stack + +**Issue**: Find/replace not finding all occurrences +**Solution**: Implement proper text search algorithms and handle edge cases + +## Learning Outcomes + +After completing this project, you'll understand: +- File I/O operations and error handling +- GUI programming with tkinter +- Event-driven programming concepts +- Text processing and manipulation +- User interface design principles +- Software architecture and organization + +## File Structure + +``` +simple_text_editor/ +ā”œā”€ā”€ basic_editor.py # Phase 1 command-line version +ā”œā”€ā”€ gui_editor.py # Phase 2 basic GUI +ā”œā”€ā”€ advanced_editor.py # Phase 3 enhanced features +ā”œā”€ā”€ full_editor.py # Phase 4 complete version +ā”œā”€ā”€ themes/ # Color themes and settings +│ └── default.json +ā”œā”€ā”€ icons/ # UI icons (optional) +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your text editor: +1. Use it to edit your other Python projects! +2. Add your favorite text editing features +3. Share your implementation and get feedback +4. Consider adding syntax highlighting for Python +5. Try the Contact Book project next for more GUI practice + +Great job on building a practical productivity application! \ No newline at end of file diff --git a/Projects/Beginners/TodoList/README.md b/Projects/Beginners/TodoList/README.md index 62319a6..ce46bcf 100644 --- a/Projects/Beginners/TodoList/README.md +++ b/Projects/Beginners/TodoList/README.md @@ -1 +1,254 @@ -# Todo List Project\n\nBuild a task management application to organize and track your daily activities and projects.\n\n## Project Overview\n\n**What you'll build**: A todo list application that allows you to add, remove, mark as complete, and persist tasks across program runs.\n\n**What you'll learn**:\n- Working with lists and dictionaries\n- File operations for data persistence\n- Date and time handling\n- User interface design\n- Data validation and error handling\n\n## Project Features\n\n### Basic Features\n- Add new tasks with descriptions\n- Mark tasks as complete/incomplete\n- Remove tasks from the list\n- Display all tasks with status\n- Save tasks to file for persistence\n\n### Advanced Features\n- Task categories and priorities\n- Due dates and reminders\n- Search and filter functionality\n- Task statistics and progress tracking\n- Export tasks to different formats\n\n## Implementation Guide\n\n### Phase 1: Basic Todo List\n**Time**: 2-3 hours\n\nCreate a simple command-line todo list:\n- Add tasks to a list\n- Display tasks with numbering\n- Mark tasks as done\n- Remove tasks\n- Basic menu system\n\n**Key concepts**: Lists, dictionaries, loops, conditional statements\n\n### Phase 2: Data Persistence\n**Time**: 2-3 hours\n\nAdd file operations:\n- Save tasks to JSON file\n- Load tasks when program starts\n- Handle file errors gracefully\n- Backup functionality\n\n**Key concepts**: File I/O, JSON handling, exception handling\n\n### Phase 3: Enhanced Features\n**Time**: 3-4 hours\n\nImplement advanced functionality:\n- Task priorities (high, medium, low)\n- Due dates with date validation\n- Task categories\n- Search and filter options\n- Progress statistics\n\n**Key concepts**: Date/time operations, data filtering, validation\n\n### Phase 4: GUI Version\n**Time**: 4-5 hours\n\nCreate a graphical interface:\n- Task list display with checkboxes\n- Add/edit task dialogs\n- Priority and category selection\n- Progress visualization\n\n**Key concepts**: GUI programming, event handling, data binding\n\n## Getting Started\n\n### Setup\n1. Create project directory and files\n2. Plan your data structure for tasks\n3. Design the user interface flow\n\n### Basic Task Structure\n```python\ntask = {\n 'id': 1,\n 'description': 'Complete Python project',\n 'completed': False,\n 'created_date': '2025-10-01',\n 'priority': 'high',\n 'category': 'work'\n}\n```\n\n### Core Functions\n```python\ndef add_task(description, priority='medium', category='general'):\n # Add new task to list\n pass\n\ndef complete_task(task_id):\n # Mark task as completed\n pass\n\ndef remove_task(task_id):\n # Remove task from list\n pass\n\ndef display_tasks(filter_by=None):\n # Show tasks with optional filtering\n pass\n```\n\n## User Interface Design\n\n### Command Line Menu\n```\n=== TODO LIST MANAGER ===\n1. Add Task\n2. View Tasks\n3. Mark Complete\n4. Remove Task\n5. Search Tasks\n6. Statistics\n7. Exit\n\nChoose an option: \n```\n\n### Task Display Format\n```\n[1] [ ] High - Complete Python project (Work)\n[2] [X] Medium - Buy groceries (Personal)\n[3] [ ] Low - Read book chapter (Education)\n```\n\n## Data Management\n\n### File Structure\n- Use JSON format for easy reading/writing\n- Include metadata (creation date, last modified)\n- Implement backup system\n- Handle concurrent access if needed\n\n### Example JSON Structure\n```json\n{\n \"tasks\": [\n {\n \"id\": 1,\n \"description\": \"Complete project\",\n \"completed\": false,\n \"created_date\": \"2025-10-01T10:00:00\",\n \"priority\": \"high\",\n \"category\": \"work\",\n \"due_date\": \"2025-10-15T23:59:59\"\n }\n ],\n \"metadata\": {\n \"last_modified\": \"2025-10-01T10:30:00\",\n \"total_tasks\": 1,\n \"completed_tasks\": 0\n }\n}\n```\n\n## Testing Your Application\n\n### Test Scenarios\n- Add multiple tasks with different properties\n- Mark tasks as complete and incomplete\n- Remove tasks and verify list updates\n- Test file saving and loading\n- Search for tasks with various criteria\n- Test edge cases (empty list, invalid inputs)\n\n### Data Validation\n- Ensure task descriptions are not empty\n- Validate date formats for due dates\n- Check priority values are valid\n- Handle duplicate task IDs\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Task notes and detailed descriptions\n- Simple reminder notifications\n- Task completion time tracking\n- Export to text or CSV format\n\n### Intermediate Extensions\n- Subtasks and task dependencies\n- Recurring tasks\n- Team collaboration features\n- Integration with calendar applications\n\n### Advanced Extensions\n- Web-based interface\n- Mobile app synchronization\n- AI-powered task suggestions\n- Integration with project management tools\n\n## Common Issues and Solutions\n\n**Issue**: File corruption or missing file\n**Solution**: Implement backup system and file validation\n\n**Issue**: Task IDs become inconsistent\n**Solution**: Use UUID or implement proper ID management\n\n**Issue**: Date parsing errors\n**Solution**: Use datetime module with proper error handling\n\n**Issue**: Large task lists become slow\n**Solution**: Implement pagination and efficient data structures\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- How to design and implement data structures\n- File operations and data persistence\n- User input validation and error handling\n- Date and time operations in Python\n- Basic GUI programming concepts\n- Software design patterns and organization\n\n## File Structure\n\n```\ntodo_list/\nā”œā”€ā”€ basic_todo.py # Phase 1 implementation\nā”œā”€ā”€ persistent_todo.py # Phase 2 with file operations\nā”œā”€ā”€ advanced_todo.py # Phase 3 with full features\nā”œā”€ā”€ gui_todo.py # Phase 4 GUI version\nā”œā”€ā”€ tasks.json # Task data file\nā”œā”€ā”€ backup/ # Backup files directory\n│ └── tasks_backup.json\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your todo list:\n1. Use it to manage your own tasks!\n2. Add your favorite features and customizations\n3. Share your implementation with others\n4. Consider building a web version\n5. Try the Contact Book project next for more data management practice\n\nExcellent work on building a practical productivity tool! \ No newline at end of file +# Todo List Project + +Build a task management application to organize and track your daily activities and projects. + +## Project Overview + +**What you'll build**: A todo list application that allows you to add, remove, mark as complete, and persist tasks across program runs. + +**What you'll learn**: +- Working with lists and dictionaries +- File operations for data persistence +- Date and time handling +- User interface design +- Data validation and error handling + +## Project Features + +### Basic Features +- Add new tasks with descriptions +- Mark tasks as complete/incomplete +- Remove tasks from the list +- Display all tasks with status +- Save tasks to file for persistence + +### Advanced Features +- Task categories and priorities +- Due dates and reminders +- Search and filter functionality +- Task statistics and progress tracking +- Export tasks to different formats + +## Implementation Guide + +### Phase 1: Basic Todo List +**Time**: 2-3 hours + +Create a simple command-line todo list: +- Add tasks to a list +- Display tasks with numbering +- Mark tasks as done +- Remove tasks +- Basic menu system + +**Key concepts**: Lists, dictionaries, loops, conditional statements + +### Phase 2: Data Persistence +**Time**: 2-3 hours + +Add file operations: +- Save tasks to JSON file +- Load tasks when program starts +- Handle file errors gracefully +- Backup functionality + +**Key concepts**: File I/O, JSON handling, exception handling + +### Phase 3: Enhanced Features +**Time**: 3-4 hours + +Implement advanced functionality: +- Task priorities (high, medium, low) +- Due dates with date validation +- Task categories +- Search and filter options +- Progress statistics + +**Key concepts**: Date/time operations, data filtering, validation + +### Phase 4: GUI Version +**Time**: 4-5 hours + +Create a graphical interface: +- Task list display with checkboxes +- Add/edit task dialogs +- Priority and category selection +- Progress visualization + +**Key concepts**: GUI programming, event handling, data binding + +## Getting Started + +### Setup +1. Create project directory and files +2. Plan your data structure for tasks +3. Design the user interface flow + +### Basic Task Structure +```python +task = { + 'id': 1, + 'description': 'Complete Python project', + 'completed': False, + 'created_date': '2025-10-01', + 'priority': 'high', + 'category': 'work' +} +``` + +### Core Functions +```python +def add_task(description, priority='medium', category='general'): + # Add new task to list + pass + +def complete_task(task_id): + # Mark task as completed + pass + +def remove_task(task_id): + # Remove task from list + pass + +def display_tasks(filter_by=None): + # Show tasks with optional filtering + pass +``` + +## User Interface Design + +### Command Line Menu +``` +=== TODO LIST MANAGER === +1. Add Task +2. View Tasks +3. Mark Complete +4. Remove Task +5. Search Tasks +6. Statistics +7. Exit + +Choose an option: +``` + +### Task Display Format +``` +[1] [ ] High - Complete Python project (Work) +[2] [X] Medium - Buy groceries (Personal) +[3] [ ] Low - Read book chapter (Education) +``` + +## Data Management + +### File Structure +- Use JSON format for easy reading/writing +- Include metadata (creation date, last modified) +- Implement backup system +- Handle concurrent access if needed + +### Example JSON Structure +```json +{ + "tasks": [ + { + "id": 1, + "description": "Complete project", + "completed": false, + "created_date": "2025-10-01T10:00:00", + "priority": "high", + "category": "work", + "due_date": "2025-10-15T23:59:59" + } + ], + "metadata": { + "last_modified": "2025-10-01T10:30:00", + "total_tasks": 1, + "completed_tasks": 0 + } +} +``` + +## Testing Your Application + +### Test Scenarios +- Add multiple tasks with different properties +- Mark tasks as complete and incomplete +- Remove tasks and verify list updates +- Test file saving and loading +- Search for tasks with various criteria +- Test edge cases (empty list, invalid inputs) + +### Data Validation +- Ensure task descriptions are not empty +- Validate date formats for due dates +- Check priority values are valid +- Handle duplicate task IDs + +## Extensions and Improvements + +### Beginner Extensions +- Task notes and detailed descriptions +- Simple reminder notifications +- Task completion time tracking +- Export to text or CSV format + +### Intermediate Extensions +- Subtasks and task dependencies +- Recurring tasks +- Team collaboration features +- Integration with calendar applications + +### Advanced Extensions +- Web-based interface +- Mobile app synchronization +- AI-powered task suggestions +- Integration with project management tools + +## Common Issues and Solutions + +**Issue**: File corruption or missing file +**Solution**: Implement backup system and file validation + +**Issue**: Task IDs become inconsistent +**Solution**: Use UUID or implement proper ID management + +**Issue**: Date parsing errors +**Solution**: Use datetime module with proper error handling + +**Issue**: Large task lists become slow +**Solution**: Implement pagination and efficient data structures + +## Learning Outcomes + +After completing this project, you'll understand: +- How to design and implement data structures +- File operations and data persistence +- User input validation and error handling +- Date and time operations in Python +- Basic GUI programming concepts +- Software design patterns and organization + +## File Structure + +``` +todo_list/ +ā”œā”€ā”€ basic_todo.py # Phase 1 implementation +ā”œā”€ā”€ persistent_todo.py # Phase 2 with file operations +ā”œā”€ā”€ advanced_todo.py # Phase 3 with full features +ā”œā”€ā”€ gui_todo.py # Phase 4 GUI version +ā”œā”€ā”€ tasks.json # Task data file +ā”œā”€ā”€ backup/ # Backup files directory +│ └── tasks_backup.json +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your todo list: +1. Use it to manage your own tasks! +2. Add your favorite features and customizations +3. Share your implementation with others +4. Consider building a web version +5. Try the Contact Book project next for more data management practice + +Excellent work on building a practical productivity tool! \ No newline at end of file diff --git a/Projects/Intermediate/ContactBook/README.md b/Projects/Intermediate/ContactBook/README.md index 2d3e067..142b4e8 100644 --- a/Projects/Intermediate/ContactBook/README.md +++ b/Projects/Intermediate/ContactBook/README.md @@ -1 +1,315 @@ -# Contact Book Project\n\nBuild a contact management system to store and organize personal and professional contacts.\n\n## Project Overview\n\n**What you'll build**: A contact book application that stores contact information, supports searching and filtering, and maintains data persistence.\n\n**What you'll learn**:\n- Object-oriented programming with classes\n- Data validation and input sanitization\n- File operations and data persistence\n- Search and filtering algorithms\n- Database basics (optional advanced feature)\n\n## Project Features\n\n### Core Features\n- Add new contacts with multiple fields\n- Edit existing contact information\n- Delete contacts from the book\n- Search contacts by name, phone, or email\n- Display all contacts in organized format\n- Save/load contacts to/from file\n\n### Advanced Features\n- Contact categories and groups\n- Import/export contacts (CSV, JSON)\n- Contact photos and additional fields\n- Backup and restore functionality\n- Advanced search with filters\n- Contact statistics and analytics\n\n## Implementation Guide\n\n### Phase 1: Contact Class Design\n**Time**: 2-3 hours\n\nCreate the Contact class and basic operations:\n- Design Contact class with properties\n- Add methods for contact manipulation\n- Implement basic contact list management\n- Create simple command-line interface\n\n**Key concepts**: Classes, objects, methods, data encapsulation\n\n### Phase 2: Data Persistence\n**Time**: 2-3 hours\n\nAdd file operations:\n- Save contacts to JSON file\n- Load contacts on program start\n- Handle file errors and corruption\n- Implement backup system\n\n**Key concepts**: File I/O, JSON serialization, error handling\n\n### Phase 3: Search and Validation\n**Time**: 3-4 hours\n\nEnhance functionality:\n- Input validation for email, phone numbers\n- Advanced search capabilities\n- Contact sorting options\n- Data integrity checks\n\n**Key concepts**: Regular expressions, data validation, search algorithms\n\n### Phase 4: GUI and Advanced Features\n**Time**: 4-5 hours\n\nBuild graphical interface:\n- Contact list display with details\n- Add/edit contact forms\n- Search and filter interface\n- Import/export functionality\n\n**Key concepts**: GUI programming, data binding, file formats\n\n## Getting Started\n\n### Setup\n1. Plan the contact data structure\n2. Design the class hierarchy\n3. Create the user interface flow\n\n### Contact Class Design\n```python\nclass Contact:\n def __init__(self, first_name, last_name, phone=\"\", email=\"\", address=\"\"):\n self.first_name = first_name\n self.last_name = last_name\n self.phone = phone\n self.email = email\n self.address = address\n self.created_date = datetime.now()\n self.modified_date = datetime.now()\n \n def full_name(self):\n return f\"{self.first_name} {self.last_name}\"\n \n def validate_email(self):\n # Email validation logic\n pass\n \n def validate_phone(self):\n # Phone validation logic\n pass\n```\n\n### ContactBook Class\n```python\nclass ContactBook:\n def __init__(self):\n self.contacts = []\n self.filename = \"contacts.json\"\n self.load_contacts()\n \n def add_contact(self, contact):\n # Add contact to list\n pass\n \n def search_contacts(self, query):\n # Search functionality\n pass\n \n def save_contacts(self):\n # Save to file\n pass\n```\n\n## Data Structure Design\n\n### Contact Information Fields\n- **Required**: First name, last name\n- **Optional**: Phone number, email address, physical address\n- **Metadata**: Creation date, last modified date\n- **Advanced**: Birthday, company, job title, notes, categories\n\n### Data Validation Rules\n- Name fields: Non-empty, reasonable length\n- Email: Valid email format using regex\n- Phone: Valid phone number format\n- Address: Optional but structured if provided\n\n### File Storage Format\n```json\n{\n \"contacts\": [\n {\n \"first_name\": \"John\",\n \"last_name\": \"Doe\",\n \"phone\": \"+1-555-123-4567\",\n \"email\": \"john.doe@example.com\",\n \"address\": \"123 Main St, City, State 12345\",\n \"created_date\": \"2025-10-01T10:00:00\",\n \"modified_date\": \"2025-10-01T10:00:00\",\n \"categories\": [\"work\", \"friend\"]\n }\n ],\n \"metadata\": {\n \"version\": \"1.0\",\n \"total_contacts\": 1,\n \"last_backup\": \"2025-10-01T09:00:00\"\n }\n}\n```\n\n## User Interface Design\n\n### Command Line Interface\n```\n=== CONTACT BOOK ===\n1. Add Contact\n2. View All Contacts\n3. Search Contacts\n4. Edit Contact\n5. Delete Contact\n6. Export Contacts\n7. Import Contacts\n8. Exit\n\nChoose an option: \n```\n\n### Contact Display Format\n```\n[1] John Doe\n Phone: +1-555-123-4567\n Email: john.doe@example.com\n Address: 123 Main St, City, State 12345\n Categories: work, friend\n Added: 2025-10-01\n```\n\n## Core Functionality Implementation\n\n### Search Features\n- Search by name (partial matches)\n- Search by phone number\n- Search by email address\n- Filter by categories\n- Advanced search with multiple criteria\n\n### Data Validation Examples\n```python\nimport re\n\ndef validate_email(email):\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n return re.match(pattern, email) is not None\n\ndef validate_phone(phone):\n # Remove non-digit characters for validation\n digits = re.sub(r'\\D', '', phone)\n return len(digits) >= 10\n```\n\n### Import/Export Features\n- Export to CSV for spreadsheet compatibility\n- Export to JSON for backup/restore\n- Import from various formats\n- Data mapping and conversion\n\n## Testing Your Contact Book\n\n### Test Scenarios\n- Add contacts with various field combinations\n- Test search functionality with different queries\n- Validate email and phone number formats\n- Test file save/load operations\n- Import/export with sample data\n- Handle edge cases (empty fields, special characters)\n\n### Data Integrity Tests\n- Duplicate contact detection\n- Data corruption recovery\n- Large contact list performance\n- Concurrent access handling\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Contact photos and avatars\n- Birthday reminders\n- Contact notes and comments\n- Simple contact sharing\n\n### Intermediate Extensions\n- Database storage (SQLite)\n- Contact synchronization with phone/email\n- Advanced contact analytics\n- Contact relationship mapping\n\n### Advanced Extensions\n- Cloud synchronization\n- Multi-user support with permissions\n- Integration with email clients\n- API for external applications\n\n## Common Issues and Solutions\n\n**Issue**: Contact data becomes corrupted\n**Solution**: Implement data validation and automatic backups\n\n**Issue**: Search becomes slow with many contacts\n**Solution**: Implement indexing and optimized search algorithms\n\n**Issue**: Import fails with different file formats\n**Solution**: Add robust file format detection and conversion\n\n**Issue**: Duplicate contacts created\n**Solution**: Implement duplicate detection based on multiple fields\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- Object-oriented programming principles\n- Data validation and sanitization techniques\n- File operations and data serialization\n- Search and filtering algorithms\n- User interface design patterns\n- Error handling and data integrity\n\n## File Structure\n\n```\ncontact_book/\nā”œā”€ā”€ models/\n│ ā”œā”€ā”€ contact.py # Contact class definition\n│ └── contact_book.py # ContactBook class\nā”œā”€ā”€ utils/\n│ ā”œā”€ā”€ validation.py # Data validation functions\n│ └── file_handler.py # File I/O operations\nā”œā”€ā”€ ui/\n│ ā”œā”€ā”€ cli_interface.py # Command-line interface\n│ └── gui_interface.py # Graphical interface (optional)\nā”œā”€ā”€ data/\n│ ā”œā”€ā”€ contacts.json # Main contact data\n│ └── backups/ # Backup files\nā”œā”€ā”€ tests/\n│ └── test_contacts.py # Unit tests\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your contact book:\n1. Add your real contacts and use it daily\n2. Implement your most-wanted features\n3. Share with friends and get feedback\n4. Consider mobile app version\n5. Try the Expense Tracker project next for more data management\n\nExcellent work on building a practical data management application! \ No newline at end of file +# Contact Book Project + +Build a contact management system to store and organize personal and professional contacts. + +## Project Overview + +**What you'll build**: A contact book application that stores contact information, supports searching and filtering, and maintains data persistence. + +**What you'll learn**: +- Object-oriented programming with classes +- Data validation and input sanitization +- File operations and data persistence +- Search and filtering algorithms +- Database basics (optional advanced feature) + +## Project Features + +### Core Features +- Add new contacts with multiple fields +- Edit existing contact information +- Delete contacts from the book +- Search contacts by name, phone, or email +- Display all contacts in organized format +- Save/load contacts to/from file + +### Advanced Features +- Contact categories and groups +- Import/export contacts (CSV, JSON) +- Contact photos and additional fields +- Backup and restore functionality +- Advanced search with filters +- Contact statistics and analytics + +## Implementation Guide + +### Phase 1: Contact Class Design +**Time**: 2-3 hours + +Create the Contact class and basic operations: +- Design Contact class with properties +- Add methods for contact manipulation +- Implement basic contact list management +- Create simple command-line interface + +**Key concepts**: Classes, objects, methods, data encapsulation + +### Phase 2: Data Persistence +**Time**: 2-3 hours + +Add file operations: +- Save contacts to JSON file +- Load contacts on program start +- Handle file errors and corruption +- Implement backup system + +**Key concepts**: File I/O, JSON serialization, error handling + +### Phase 3: Search and Validation +**Time**: 3-4 hours + +Enhance functionality: +- Input validation for email, phone numbers +- Advanced search capabilities +- Contact sorting options +- Data integrity checks + +**Key concepts**: Regular expressions, data validation, search algorithms + +### Phase 4: GUI and Advanced Features +**Time**: 4-5 hours + +Build graphical interface: +- Contact list display with details +- Add/edit contact forms +- Search and filter interface +- Import/export functionality + +**Key concepts**: GUI programming, data binding, file formats + +## Getting Started + +### Setup +1. Plan the contact data structure +2. Design the class hierarchy +3. Create the user interface flow + +### Contact Class Design +```python +class Contact: + def __init__(self, first_name, last_name, phone="", email="", address=""): + self.first_name = first_name + self.last_name = last_name + self.phone = phone + self.email = email + self.address = address + self.created_date = datetime.now() + self.modified_date = datetime.now() + + def full_name(self): + return f"{self.first_name} {self.last_name}" + + def validate_email(self): + # Email validation logic + pass + + def validate_phone(self): + # Phone validation logic + pass +``` + +### ContactBook Class +```python +class ContactBook: + def __init__(self): + self.contacts = [] + self.filename = "contacts.json" + self.load_contacts() + + def add_contact(self, contact): + # Add contact to list + pass + + def search_contacts(self, query): + # Search functionality + pass + + def save_contacts(self): + # Save to file + pass +``` + +## Data Structure Design + +### Contact Information Fields +- **Required**: First name, last name +- **Optional**: Phone number, email address, physical address +- **Metadata**: Creation date, last modified date +- **Advanced**: Birthday, company, job title, notes, categories + +### Data Validation Rules +- Name fields: Non-empty, reasonable length +- Email: Valid email format using regex +- Phone: Valid phone number format +- Address: Optional but structured if provided + +### File Storage Format +```json +{ + "contacts": [ + { + "first_name": "John", + "last_name": "Doe", + "phone": "+1-555-123-4567", + "email": "john.doe@example.com", + "address": "123 Main St, City, State 12345", + "created_date": "2025-10-01T10:00:00", + "modified_date": "2025-10-01T10:00:00", + "categories": ["work", "friend"] + } + ], + "metadata": { + "version": "1.0", + "total_contacts": 1, + "last_backup": "2025-10-01T09:00:00" + } +} +``` + +## User Interface Design + +### Command Line Interface +``` +=== CONTACT BOOK === +1. Add Contact +2. View All Contacts +3. Search Contacts +4. Edit Contact +5. Delete Contact +6. Export Contacts +7. Import Contacts +8. Exit + +Choose an option: +``` + +### Contact Display Format +``` +[1] John Doe + Phone: +1-555-123-4567 + Email: john.doe@example.com + Address: 123 Main St, City, State 12345 + Categories: work, friend + Added: 2025-10-01 +``` + +## Core Functionality Implementation + +### Search Features +- Search by name (partial matches) +- Search by phone number +- Search by email address +- Filter by categories +- Advanced search with multiple criteria + +### Data Validation Examples +```python +import re + +def validate_email(email): + pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' + return re.match(pattern, email) is not None + +def validate_phone(phone): + # Remove non-digit characters for validation + digits = re.sub(r'\D', '', phone) + return len(digits) >= 10 +``` + +### Import/Export Features +- Export to CSV for spreadsheet compatibility +- Export to JSON for backup/restore +- Import from various formats +- Data mapping and conversion + +## Testing Your Contact Book + +### Test Scenarios +- Add contacts with various field combinations +- Test search functionality with different queries +- Validate email and phone number formats +- Test file save/load operations +- Import/export with sample data +- Handle edge cases (empty fields, special characters) + +### Data Integrity Tests +- Duplicate contact detection +- Data corruption recovery +- Large contact list performance +- Concurrent access handling + +## Extensions and Improvements + +### Beginner Extensions +- Contact photos and avatars +- Birthday reminders +- Contact notes and comments +- Simple contact sharing + +### Intermediate Extensions +- Database storage (SQLite) +- Contact synchronization with phone/email +- Advanced contact analytics +- Contact relationship mapping + +### Advanced Extensions +- Cloud synchronization +- Multi-user support with permissions +- Integration with email clients +- API for external applications + +## Common Issues and Solutions + +**Issue**: Contact data becomes corrupted +**Solution**: Implement data validation and automatic backups + +**Issue**: Search becomes slow with many contacts +**Solution**: Implement indexing and optimized search algorithms + +**Issue**: Import fails with different file formats +**Solution**: Add robust file format detection and conversion + +**Issue**: Duplicate contacts created +**Solution**: Implement duplicate detection based on multiple fields + +## Learning Outcomes + +After completing this project, you'll understand: +- Object-oriented programming principles +- Data validation and sanitization techniques +- File operations and data serialization +- Search and filtering algorithms +- User interface design patterns +- Error handling and data integrity + +## File Structure + +``` +contact_book/ +ā”œā”€ā”€ models/ +│ ā”œā”€ā”€ contact.py # Contact class definition +│ └── contact_book.py # ContactBook class +ā”œā”€ā”€ utils/ +│ ā”œā”€ā”€ validation.py # Data validation functions +│ └── file_handler.py # File I/O operations +ā”œā”€ā”€ ui/ +│ ā”œā”€ā”€ cli_interface.py # Command-line interface +│ └── gui_interface.py # Graphical interface (optional) +ā”œā”€ā”€ data/ +│ ā”œā”€ā”€ contacts.json # Main contact data +│ └── backups/ # Backup files +ā”œā”€ā”€ tests/ +│ └── test_contacts.py # Unit tests +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your contact book: +1. Add your real contacts and use it daily +2. Implement your most-wanted features +3. Share with friends and get feedback +4. Consider mobile app version +5. Try the Expense Tracker project next for more data management + +Excellent work on building a practical data management application! \ No newline at end of file diff --git a/Projects/Intermediate/ExpenseTracker/README.md b/Projects/Intermediate/ExpenseTracker/README.md index 99582d2..22a0efe 100644 --- a/Projects/Intermediate/ExpenseTracker/README.md +++ b/Projects/Intermediate/ExpenseTracker/README.md @@ -1 +1,373 @@ -# Expense Tracker Project\n\nBuild a personal finance management tool to track income, expenses, and analyze spending patterns.\n\n## Project Overview\n\n**What you'll build**: An expense tracking application that records financial transactions, categorizes spending, and provides insights into your financial habits.\n\n**What you'll learn**:\n- Working with dates and time data\n- Data analysis and visualization\n- File operations and data persistence\n- Mathematical calculations and statistics\n- Creating reports and summaries\n\n## Project Features\n\n### Core Features\n- Add income and expense transactions\n- Categorize transactions (food, transport, entertainment, etc.)\n- View transaction history\n- Calculate totals and balances\n- Generate monthly/yearly reports\n- Data persistence across sessions\n\n### Advanced Features\n- Budget planning and tracking\n- Spending analysis with charts\n- Recurring transaction support\n- Export data to various formats\n- Multi-currency support\n- Financial goal tracking\n\n## Implementation Guide\n\n### Phase 1: Basic Transaction Management\n**Time**: 2-3 hours\n\nCreate core transaction functionality:\n- Transaction class design\n- Add/view transactions\n- Basic categorization\n- Simple calculations\n\n**Key concepts**: Classes, date handling, basic math operations\n\n### Phase 2: Data Analysis\n**Time**: 3-4 hours\n\nAdd analysis features:\n- Monthly/yearly summaries\n- Category-wise breakdown\n- Balance calculations\n- Trend analysis\n\n**Key concepts**: Data aggregation, statistical calculations, date operations\n\n### Phase 3: Reporting and Visualization\n**Time**: 3-4 hours\n\nImplement reporting:\n- Generate detailed reports\n- Create simple charts and graphs\n- Export functionality\n- Budget vs actual comparisons\n\n**Key concepts**: Data visualization, file export, report generation\n\n### Phase 4: Advanced Features\n**Time**: 4-5 hours\n\nAdd sophisticated functionality:\n- Budget planning interface\n- Recurring transactions\n- Advanced filtering and search\n- Goal tracking and notifications\n\n**Key concepts**: Advanced data structures, scheduling, notification systems\n\n## Getting Started\n\n### Setup\n1. Plan the transaction data structure\n2. Design category system\n3. Create the user interface flow\n\n### Transaction Class Design\n```python\nfrom datetime import datetime\nfrom enum import Enum\n\nclass TransactionType(Enum):\n INCOME = \"income\"\n EXPENSE = \"expense\"\n\nclass Transaction:\n def __init__(self, amount, category, description, transaction_type, date=None):\n self.amount = float(amount)\n self.category = category\n self.description = description\n self.type = transaction_type\n self.date = date or datetime.now()\n self.id = self.generate_id()\n \n def generate_id(self):\n # Generate unique transaction ID\n pass\n```\n\n### ExpenseTracker Class\n```python\nclass ExpenseTracker:\n def __init__(self):\n self.transactions = []\n self.categories = {\n 'expense': ['Food', 'Transport', 'Entertainment', 'Utilities', 'Other'],\n 'income': ['Salary', 'Freelance', 'Investment', 'Gift', 'Other']\n }\n self.load_data()\n \n def add_transaction(self, amount, category, description, transaction_type):\n # Add new transaction\n pass\n \n def get_balance(self):\n # Calculate current balance\n pass\n \n def get_monthly_summary(self, month, year):\n # Generate monthly report\n pass\n```\n\n## Data Structure Design\n\n### Transaction Data\n```json\n{\n \"id\": \"txn_20251001_001\",\n \"amount\": 25.50,\n \"category\": \"Food\",\n \"description\": \"Lunch at restaurant\",\n \"type\": \"expense\",\n \"date\": \"2025-10-01T12:30:00\",\n \"tags\": [\"restaurant\", \"lunch\"],\n \"payment_method\": \"credit_card\"\n}\n```\n\n### Category Structure\n```python\nCATEGORIES = {\n 'expense': {\n 'Food': ['Groceries', 'Restaurants', 'Takeout'],\n 'Transport': ['Gas', 'Public Transport', 'Taxi'],\n 'Entertainment': ['Movies', 'Games', 'Subscriptions'],\n 'Bills': ['Rent', 'Utilities', 'Internet'],\n 'Shopping': ['Clothing', 'Electronics', 'Household']\n },\n 'income': {\n 'Work': ['Salary', 'Bonus', 'Overtime'],\n 'Business': ['Sales', 'Services', 'Freelance'],\n 'Investment': ['Dividends', 'Interest', 'Capital Gains'],\n 'Other': ['Gift', 'Refund', 'Miscellaneous']\n }\n}\n```\n\n## User Interface Design\n\n### Main Menu\n```\n=== EXPENSE TRACKER ===\n1. Add Transaction\n2. View Transactions\n3. Monthly Summary\n4. Category Analysis\n5. Balance Report\n6. Budget Manager\n7. Export Data\n8. Exit\n\nCurrent Balance: $1,250.75\nChoose an option: \n```\n\n### Transaction Entry Form\n```\n=== ADD TRANSACTION ===\nType (1-Income, 2-Expense): 2\nAmount: $25.50\nCategory: Food\nDescription: Lunch at restaurant\nDate (YYYY-MM-DD) or Enter for today: 2025-10-01\n\nTransaction added successfully!\n```\n\n## Core Features Implementation\n\n### Balance Calculation\n```python\ndef calculate_balance(self):\n total_income = sum(t.amount for t in self.transactions \n if t.type == TransactionType.INCOME)\n total_expenses = sum(t.amount for t in self.transactions \n if t.type == TransactionType.EXPENSE)\n return total_income - total_expenses\n```\n\n### Monthly Summary\n```python\ndef get_monthly_summary(self, month, year):\n monthly_transactions = [\n t for t in self.transactions \n if t.date.month == month and t.date.year == year\n ]\n \n income = sum(t.amount for t in monthly_transactions \n if t.type == TransactionType.INCOME)\n expenses = sum(t.amount for t in monthly_transactions \n if t.type == TransactionType.EXPENSE)\n \n return {\n 'month': f\"{month}/{year}\",\n 'income': income,\n 'expenses': expenses,\n 'net': income - expenses,\n 'transaction_count': len(monthly_transactions)\n }\n```\n\n### Category Analysis\n```python\ndef analyze_spending_by_category(self, start_date=None, end_date=None):\n filtered_transactions = self.filter_by_date(start_date, end_date)\n expenses = [t for t in filtered_transactions \n if t.type == TransactionType.EXPENSE]\n \n category_totals = {}\n for transaction in expenses:\n category = transaction.category\n category_totals[category] = category_totals.get(category, 0) + transaction.amount\n \n return category_totals\n```\n\n## Reporting Features\n\n### Monthly Report Format\n```\n=== MONTHLY REPORT - October 2025 ===\n\nIncome:\n Salary: $3,000.00\n Freelance: $500.00\n Total: $3,500.00\n\nExpenses:\n Food: $450.00\n Transport: $200.00\n Bills: $800.00\n Other: $150.00\n Total: $1,600.00\n\nNet Income: $1,900.00\nTransactions: 45\n```\n\n### Data Export Options\n- CSV format for spreadsheet analysis\n- JSON format for backup/restore\n- PDF reports for sharing\n- Simple text summaries\n\n## Testing Your Expense Tracker\n\n### Test Scenarios\n- Add various types of transactions\n- Test date calculations and filtering\n- Verify balance calculations\n- Generate reports for different time periods\n- Test data persistence and loading\n- Handle edge cases (negative amounts, future dates)\n\n### Sample Test Data\n```python\ntest_transactions = [\n Transaction(3000, \"Salary\", \"Monthly salary\", TransactionType.INCOME),\n Transaction(25, \"Food\", \"Lunch\", TransactionType.EXPENSE),\n Transaction(50, \"Transport\", \"Gas\", TransactionType.EXPENSE),\n Transaction(100, \"Entertainment\", \"Movie tickets\", TransactionType.EXPENSE)\n]\n```\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Receipt photo attachment\n- Simple budgeting alerts\n- Currency conversion\n- Transaction search functionality\n\n### Intermediate Extensions\n- Investment tracking\n- Bill reminder system\n- Advanced data visualization\n- Mobile app synchronization\n\n### Advanced Extensions\n- Machine learning for expense prediction\n- Bank account integration\n- Multi-user family budgeting\n- Financial planning tools\n\n## Common Issues and Solutions\n\n**Issue**: Date calculations are incorrect\n**Solution**: Use datetime module properly and handle timezones\n\n**Issue**: Floating point precision errors with money\n**Solution**: Use decimal module for precise financial calculations\n\n**Issue**: Reports are slow with many transactions\n**Solution**: Implement efficient data filtering and caching\n\n**Issue**: Data loss during program crashes\n**Solution**: Implement auto-save and backup mechanisms\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- Date and time manipulation in Python\n- Data analysis and aggregation techniques\n- Financial calculations and precision handling\n- Report generation and data visualization\n- File operations and data persistence\n- User interface design for data entry\n\n## File Structure\n\n```\nexpense_tracker/\nā”œā”€ā”€ models/\n│ ā”œā”€ā”€ transaction.py # Transaction class\n│ └── expense_tracker.py # Main tracker class\nā”œā”€ā”€ utils/\n│ ā”œā”€ā”€ date_utils.py # Date manipulation helpers\n│ ā”œā”€ā”€ calculations.py # Financial calculations\n│ └── export_utils.py # Data export functions\nā”œā”€ā”€ reports/\n│ ā”œā”€ā”€ monthly_report.py # Monthly report generator\n│ └── category_report.py # Category analysis\nā”œā”€ā”€ data/\n│ ā”œā”€ā”€ transactions.json # Transaction data\n│ ā”œā”€ā”€ categories.json # Category definitions\n│ └── backups/ # Backup files\nā”œā”€ā”€ ui/\n│ ā”œā”€ā”€ cli_interface.py # Command-line interface\n│ └── gui_interface.py # Graphical interface (optional)\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your expense tracker:\n1. Start tracking your real expenses!\n2. Analyze your spending patterns\n3. Set up budgets and financial goals\n4. Share insights with family or friends\n5. Try the Web Scraper project next for data collection skills\n\nFantastic work on building a practical financial management tool! \ No newline at end of file +# Expense Tracker Project + +Build a personal finance management tool to track income, expenses, and analyze spending patterns. + +## Project Overview + +**What you'll build**: An expense tracking application that records financial transactions, categorizes spending, and provides insights into your financial habits. + +**What you'll learn**: +- Working with dates and time data +- Data analysis and visualization +- File operations and data persistence +- Mathematical calculations and statistics +- Creating reports and summaries + +## Project Features + +### Core Features +- Add income and expense transactions +- Categorize transactions (food, transport, entertainment, etc.) +- View transaction history +- Calculate totals and balances +- Generate monthly/yearly reports +- Data persistence across sessions + +### Advanced Features +- Budget planning and tracking +- Spending analysis with charts +- Recurring transaction support +- Export data to various formats +- Multi-currency support +- Financial goal tracking + +## Implementation Guide + +### Phase 1: Basic Transaction Management +**Time**: 2-3 hours + +Create core transaction functionality: +- Transaction class design +- Add/view transactions +- Basic categorization +- Simple calculations + +**Key concepts**: Classes, date handling, basic math operations + +### Phase 2: Data Analysis +**Time**: 3-4 hours + +Add analysis features: +- Monthly/yearly summaries +- Category-wise breakdown +- Balance calculations +- Trend analysis + +**Key concepts**: Data aggregation, statistical calculations, date operations + +### Phase 3: Reporting and Visualization +**Time**: 3-4 hours + +Implement reporting: +- Generate detailed reports +- Create simple charts and graphs +- Export functionality +- Budget vs actual comparisons + +**Key concepts**: Data visualization, file export, report generation + +### Phase 4: Advanced Features +**Time**: 4-5 hours + +Add sophisticated functionality: +- Budget planning interface +- Recurring transactions +- Advanced filtering and search +- Goal tracking and notifications + +**Key concepts**: Advanced data structures, scheduling, notification systems + +## Getting Started + +### Setup +1. Plan the transaction data structure +2. Design category system +3. Create the user interface flow + +### Transaction Class Design +```python +from datetime import datetime +from enum import Enum + +class TransactionType(Enum): + INCOME = "income" + EXPENSE = "expense" + +class Transaction: + def __init__(self, amount, category, description, transaction_type, date=None): + self.amount = float(amount) + self.category = category + self.description = description + self.type = transaction_type + self.date = date or datetime.now() + self.id = self.generate_id() + + def generate_id(self): + # Generate unique transaction ID + pass +``` + +### ExpenseTracker Class +```python +class ExpenseTracker: + def __init__(self): + self.transactions = [] + self.categories = { + 'expense': ['Food', 'Transport', 'Entertainment', 'Utilities', 'Other'], + 'income': ['Salary', 'Freelance', 'Investment', 'Gift', 'Other'] + } + self.load_data() + + def add_transaction(self, amount, category, description, transaction_type): + # Add new transaction + pass + + def get_balance(self): + # Calculate current balance + pass + + def get_monthly_summary(self, month, year): + # Generate monthly report + pass +``` + +## Data Structure Design + +### Transaction Data +```json +{ + "id": "txn_20251001_001", + "amount": 25.50, + "category": "Food", + "description": "Lunch at restaurant", + "type": "expense", + "date": "2025-10-01T12:30:00", + "tags": ["restaurant", "lunch"], + "payment_method": "credit_card" +} +``` + +### Category Structure +```python +CATEGORIES = { + 'expense': { + 'Food': ['Groceries', 'Restaurants', 'Takeout'], + 'Transport': ['Gas', 'Public Transport', 'Taxi'], + 'Entertainment': ['Movies', 'Games', 'Subscriptions'], + 'Bills': ['Rent', 'Utilities', 'Internet'], + 'Shopping': ['Clothing', 'Electronics', 'Household'] + }, + 'income': { + 'Work': ['Salary', 'Bonus', 'Overtime'], + 'Business': ['Sales', 'Services', 'Freelance'], + 'Investment': ['Dividends', 'Interest', 'Capital Gains'], + 'Other': ['Gift', 'Refund', 'Miscellaneous'] + } +} +``` + +## User Interface Design + +### Main Menu +```plaintext +=== EXPENSE TRACKER === +1. Add Transaction +2. View Transactions +3. Monthly Summary +4. Category Analysis +5. Balance Report +6. Budget Manager +7. Export Data +8. Exit + +Current Balance: $1,250.75 +Choose an option: +``` + +### Transaction Entry Form +```plaintext +=== ADD TRANSACTION === +Type (1-Income, 2-Expense): 2 +Amount: $25.50 +Category: Food +Description: Lunch at restaurant +Date (YYYY-MM-DD) or Enter for today: 2025-10-01 + +Transaction added successfully! +``` + +## Core Features Implementation + +### Balance Calculation +```python +def calculate_balance(self): + total_income = sum(t.amount for t in self.transactions + if t.type == TransactionType.INCOME) + total_expenses = sum(t.amount for t in self.transactions + if t.type == TransactionType.EXPENSE) + return total_income - total_expenses +``` + +### Monthly Summary +```python +def get_monthly_summary(self, month, year): + monthly_transactions = [ + t for t in self.transactions + if t.date.month == month and t.date.year == year + ] + + income = sum(t.amount for t in monthly_transactions + if t.type == TransactionType.INCOME) + expenses = sum(t.amount for t in monthly_transactions + if t.type == TransactionType.EXPENSE) + + return { + 'month': f"{month}/{year}", + 'income': income, + 'expenses': expenses, + 'net': income - expenses, + 'transaction_count': len(monthly_transactions) + } +``` + +### Category Analysis +```python +def analyze_spending_by_category(self, start_date=None, end_date=None): + filtered_transactions = self.filter_by_date(start_date, end_date) + expenses = [t for t in filtered_transactions + if t.type == TransactionType.EXPENSE] + + category_totals = {} + for transaction in expenses: + category = transaction.category + category_totals[category] = category_totals.get(category, 0) + transaction.amount + + return category_totals +``` + +## Reporting Features + +### Monthly Report Format +```plaintext +=== MONTHLY REPORT - October 2025 === + +Income: + Salary: $3,000.00 + Freelance: $500.00 + Total: $3,500.00 + +Expenses: + Food: $450.00 + Transport: $200.00 + Bills: $800.00 + Other: $150.00 + Total: $1,600.00 + +Net Income: $1,900.00 +Transactions: 45 +``` + +### Data Export Options +- CSV format for spreadsheet analysis +- JSON format for backup/restore +- PDF reports for sharing +- Simple text summaries + +## Testing Your Expense Tracker + +### Test Scenarios +- Add various types of transactions +- Test date calculations and filtering +- Verify balance calculations +- Generate reports for different time periods +- Test data persistence and loading +- Handle edge cases (negative amounts, future dates) + +### Sample Test Data +```python +test_transactions = [ + Transaction(3000, "Salary", "Monthly salary", TransactionType.INCOME), + Transaction(25, "Food", "Lunch", TransactionType.EXPENSE), + Transaction(50, "Transport", "Gas", TransactionType.EXPENSE), + Transaction(100, "Entertainment", "Movie tickets", TransactionType.EXPENSE) +] +``` + +## Extensions and Improvements + +### Beginner Extensions +- Receipt photo attachment +- Simple budgeting alerts +- Currency conversion +- Transaction search functionality + +### Intermediate Extensions +- Investment tracking +- Bill reminder system +- Advanced data visualization +- Mobile app synchronization + +### Advanced Extensions +- Machine learning for expense prediction +- Bank account integration +- Multi-user family budgeting +- Financial planning tools + +## Common Issues and Solutions + +**Issue**: Date calculations are incorrect +**Solution**: Use datetime module properly and handle timezones + +**Issue**: Floating point precision errors with money +**Solution**: Use decimal module for precise financial calculations + +**Issue**: Reports are slow with many transactions +**Solution**: Implement efficient data filtering and caching + +**Issue**: Data loss during program crashes +**Solution**: Implement auto-save and backup mechanisms + +## Learning Outcomes + +After completing this project, you'll understand: +- Date and time manipulation in Python +- Data analysis and aggregation techniques +- Financial calculations and precision handling +- Report generation and data visualization +- File operations and data persistence +- User interface design for data entry + +## File Structure + +``` +expense_tracker/ +ā”œā”€ā”€ models/ +│ ā”œā”€ā”€ transaction.py # Transaction class +│ └── expense_tracker.py # Main tracker class +ā”œā”€ā”€ utils/ +│ ā”œā”€ā”€ date_utils.py # Date manipulation helpers +│ ā”œā”€ā”€ calculations.py # Financial calculations +│ └── export_utils.py # Data export functions +ā”œā”€ā”€ reports/ +│ ā”œā”€ā”€ monthly_report.py # Monthly report generator +│ └── category_report.py # Category analysis +ā”œā”€ā”€ data/ +│ ā”œā”€ā”€ transactions.json # Transaction data +│ ā”œā”€ā”€ categories.json # Category definitions +│ └── backups/ # Backup files +ā”œā”€ā”€ ui/ +│ ā”œā”€ā”€ cli_interface.py # Command-line interface +│ └── gui_interface.py # Graphical interface (optional) +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your expense tracker: +1. Start tracking your real expenses! +2. Analyze your spending patterns +3. Set up budgets and financial goals +4. Share insights with family or friends +5. Try the Web Scraper project next for data collection skills + +Fantastic work on building a practical financial management tool! \ No newline at end of file diff --git a/Projects/Intermediate/QuizGame/README.md b/Projects/Intermediate/QuizGame/README.md index 6f51669..31b4aee 100644 --- a/Projects/Intermediate/QuizGame/README.md +++ b/Projects/Intermediate/QuizGame/README.md @@ -1 +1,442 @@ -# Quiz Game Project\n\nBuild an interactive quiz application with multiple question types, scoring, and progress tracking.\n\n## Project Overview\n\n**What you'll build**: A quiz game that loads questions from files, presents them to users, tracks scores, and provides feedback on performance.\n\n**What you'll learn**:\n- Object-oriented programming with classes\n- JSON file handling for data storage\n- Game logic and state management\n- User interface design and interaction\n- Score calculation and statistics\n- Randomization and question shuffling\n\n## Project Features\n\n### Core Features\n- Load questions from JSON files\n- Multiple choice and true/false questions\n- Score tracking and calculation\n- Timer functionality (optional)\n- Results summary and feedback\n- Save high scores\n\n### Advanced Features\n- Multiple quiz categories\n- Difficulty levels\n- Question randomization\n- Detailed statistics and analytics\n- User profiles and progress tracking\n- Export results and certificates\n\n## Implementation Guide\n\n### Phase 1: Basic Quiz Structure\n**Time**: 2-3 hours\n\nCreate core quiz functionality:\n- Question and Quiz classes\n- Basic question presentation\n- Score calculation\n- Simple command-line interface\n\n**Key concepts**: Classes, methods, basic game logic\n\n### Phase 2: Data Management\n**Time**: 2-3 hours\n\nAdd file operations:\n- Load questions from JSON files\n- Save and load user scores\n- Handle different question types\n- Error handling for file operations\n\n**Key concepts**: File I/O, JSON handling, data validation\n\n### Phase 3: Enhanced Features\n**Time**: 3-4 hours\n\nImplement advanced functionality:\n- Categories and difficulty levels\n- Timer and time tracking\n- Question randomization\n- Detailed feedback and explanations\n\n**Key concepts**: Advanced data structures, timing, randomization\n\n### Phase 4: GUI and Polish\n**Time**: 4-5 hours\n\nCreate graphical interface:\n- Question display with buttons\n- Progress bars and timers\n- Results visualization\n- Settings and preferences\n\n**Key concepts**: GUI programming, visual design, user experience\n\n## Getting Started\n\n### Setup\n1. Plan the question data structure\n2. Design the class hierarchy\n3. Create sample question files\n\n### Question Class Design\n```python\nclass Question:\n def __init__(self, text, options, correct_answer, explanation=\"\", difficulty=\"medium\"):\n self.text = text\n self.options = options # List of possible answers\n self.correct_answer = correct_answer # Index or text of correct answer\n self.explanation = explanation\n self.difficulty = difficulty\n self.category = \"\"\n \n def is_correct(self, user_answer):\n return user_answer == self.correct_answer\n \n def get_points(self):\n difficulty_points = {\"easy\": 1, \"medium\": 2, \"hard\": 3}\n return difficulty_points.get(self.difficulty, 1)\n```\n\n### Quiz Class Design\n```python\nimport random\nimport time\nfrom datetime import datetime\n\nclass Quiz:\n def __init__(self, questions, title=\"General Quiz\"):\n self.questions = questions\n self.title = title\n self.current_question = 0\n self.score = 0\n self.start_time = None\n self.user_answers = []\n self.time_limit = None # seconds per question\n \n def start(self):\n self.start_time = datetime.now()\n self.shuffle_questions()\n \n def shuffle_questions(self):\n random.shuffle(self.questions)\n \n def get_current_question(self):\n if self.current_question < len(self.questions):\n return self.questions[self.current_question]\n return None\n \n def submit_answer(self, answer):\n question = self.get_current_question()\n if question:\n is_correct = question.is_correct(answer)\n if is_correct:\n self.score += question.get_points()\n \n self.user_answers.append({\n 'question': question.text,\n 'user_answer': answer,\n 'correct_answer': question.correct_answer,\n 'is_correct': is_correct\n })\n \n self.current_question += 1\n return is_correct\n return False\n```\n\n## Question Data Structure\n\n### JSON Format\n```json\n{\n \"quiz_title\": \"Python Programming Quiz\",\n \"category\": \"Programming\",\n \"questions\": [\n {\n \"id\": 1,\n \"text\": \"What is the output of print(2 ** 3)?\",\n \"type\": \"multiple_choice\",\n \"options\": [\"6\", \"8\", \"9\", \"12\"],\n \"correct_answer\": 1,\n \"explanation\": \"2 ** 3 means 2 to the power of 3, which equals 8.\",\n \"difficulty\": \"easy\",\n \"points\": 1\n },\n {\n \"id\": 2,\n \"text\": \"Python is a compiled language.\",\n \"type\": \"true_false\",\n \"options\": [\"True\", \"False\"],\n \"correct_answer\": 1,\n \"explanation\": \"Python is an interpreted language, not compiled.\",\n \"difficulty\": \"medium\",\n \"points\": 2\n }\n ]\n}\n```\n\n### Question Types\n- **Multiple Choice**: 4 options, one correct\n- **True/False**: Two options\n- **Fill in the Blank**: Text input required\n- **Matching**: Match items from two lists\n\n## User Interface Design\n\n### Command Line Interface\n```\n=== PYTHON PROGRAMMING QUIZ ===\n\nQuestion 1 of 10 Score: 0\n\nWhat is the output of print(2 ** 3)?\n\nA) 6\nB) 8\nC) 9\nD) 12\n\nYour answer (A/B/C/D): B\n\nCorrect! 2 ** 3 means 2 to the power of 3, which equals 8.\n\nPress Enter to continue...\n```\n\n### GUI Layout\n- Question counter and progress bar\n- Question text display area\n- Answer options as buttons or radio buttons\n- Next/Submit button\n- Score display\n- Timer (if enabled)\n\n## Game Logic Implementation\n\n### Quiz Flow\n```python\nclass QuizGame:\n def __init__(self):\n self.quizzes = {}\n self.high_scores = []\n self.load_quizzes()\n self.load_scores()\n \n def load_quizzes(self):\n # Load quiz files from data directory\n import os\n import json\n \n quiz_dir = \"data/quizzes\"\n for filename in os.listdir(quiz_dir):\n if filename.endswith('.json'):\n with open(os.path.join(quiz_dir, filename), 'r') as f:\n quiz_data = json.load(f)\n self.quizzes[quiz_data['category']] = self.create_quiz(quiz_data)\n \n def create_quiz(self, quiz_data):\n questions = []\n for q_data in quiz_data['questions']:\n question = Question(\n text=q_data['text'],\n options=q_data['options'],\n correct_answer=q_data['correct_answer'],\n explanation=q_data.get('explanation', ''),\n difficulty=q_data.get('difficulty', 'medium')\n )\n questions.append(question)\n \n return Quiz(questions, quiz_data['quiz_title'])\n```\n\n### Scoring System\n```python\nclass ScoreCalculator:\n @staticmethod\n def calculate_final_score(quiz):\n total_possible = sum(q.get_points() for q in quiz.questions)\n percentage = (quiz.score / total_possible) * 100 if total_possible > 0 else 0\n \n return {\n 'raw_score': quiz.score,\n 'total_possible': total_possible,\n 'percentage': percentage,\n 'grade': ScoreCalculator.get_letter_grade(percentage),\n 'time_taken': ScoreCalculator.calculate_time_taken(quiz)\n }\n \n @staticmethod\n def get_letter_grade(percentage):\n if percentage >= 90: return 'A'\n elif percentage >= 80: return 'B'\n elif percentage >= 70: return 'C'\n elif percentage >= 60: return 'D'\n else: return 'F'\n```\n\n## Advanced Features\n\n### Timer Implementation\n```python\nimport threading\nimport time\n\nclass QuizTimer:\n def __init__(self, time_limit, callback):\n self.time_limit = time_limit\n self.callback = callback\n self.start_time = None\n self.is_running = False\n \n def start(self):\n self.start_time = time.time()\n self.is_running = True\n timer_thread = threading.Thread(target=self._run_timer)\n timer_thread.start()\n \n def _run_timer(self):\n while self.is_running and self.get_remaining_time() > 0:\n time.sleep(0.1)\n \n if self.is_running:\n self.callback() # Time's up!\n \n def get_remaining_time(self):\n if not self.start_time:\n return self.time_limit\n elapsed = time.time() - self.start_time\n return max(0, self.time_limit - elapsed)\n```\n\n### Statistics and Analytics\n```python\nclass QuizStatistics:\n def __init__(self, quiz_results):\n self.results = quiz_results\n \n def get_category_performance(self):\n # Analyze performance by question category\n pass\n \n def get_difficulty_analysis(self):\n # Show performance by difficulty level\n pass\n \n def get_improvement_suggestions(self):\n # Provide personalized feedback\n pass\n```\n\n## Testing Your Quiz Game\n\n### Test Scenarios\n- Load different quiz files\n- Answer questions correctly and incorrectly\n- Test timer functionality\n- Verify score calculations\n- Test with various question types\n- Handle invalid inputs gracefully\n\n### Sample Test Data\n```json\n{\n \"quiz_title\": \"Test Quiz\",\n \"category\": \"Test\",\n \"questions\": [\n {\n \"text\": \"Test question?\",\n \"type\": \"multiple_choice\",\n \"options\": [\"A\", \"B\", \"C\", \"D\"],\n \"correct_answer\": 0,\n \"difficulty\": \"easy\"\n }\n ]\n}\n```\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Hint system for difficult questions\n- Achievement badges and rewards\n- Question favorites and bookmarks\n- Simple quiz creation tool\n\n### Intermediate Extensions\n- Multiplayer quiz competitions\n- Adaptive difficulty adjustment\n- Integration with external quiz APIs\n- Mobile app version\n\n### Advanced Extensions\n- AI-powered question generation\n- Speech recognition for answers\n- Virtual reality quiz environments\n- Learning management system integration\n\n## Common Issues and Solutions\n\n**Issue**: Questions not loading from files\n**Solution**: Check file paths, JSON syntax, and error handling\n\n**Issue**: Timer not working correctly\n**Solution**: Use proper threading and time management\n\n**Issue**: Scores not calculating properly\n**Solution**: Debug scoring logic and validate question data\n\n**Issue**: GUI freezing during quiz\n**Solution**: Use proper event handling and avoid blocking operations\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- Object-oriented programming design patterns\n- File operations and data serialization\n- Game logic and state management\n- User interface design and interaction\n- Threading and timing operations\n- Data analysis and statistics\n\n## File Structure\n\n```\nquiz_game/\nā”œā”€ā”€ models/\n│ ā”œā”€ā”€ question.py # Question class\n│ ā”œā”€ā”€ quiz.py # Quiz class\n│ └── game.py # Main game logic\nā”œā”€ā”€ data/\n│ ā”œā”€ā”€ quizzes/ # Quiz JSON files\n│ │ ā”œā”€ā”€ python.json\n│ │ ā”œā”€ā”€ history.json\n│ │ └── science.json\n│ └── scores.json # High scores\nā”œā”€ā”€ ui/\n│ ā”œā”€ā”€ cli_interface.py # Command-line interface\n│ └── gui_interface.py # Graphical interface\nā”œā”€ā”€ utils/\n│ ā”œā”€ā”€ timer.py # Timer functionality\n│ ā”œā”€ā”€ statistics.py # Analytics and stats\n│ └── file_handler.py # File operations\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your quiz game:\n1. Create quiz content for your favorite subjects\n2. Challenge friends and family to play\n3. Add your own creative features\n4. Share quizzes with the community\n5. Try the Server project next for web-based applications\n\nExcellent work on building an engaging educational tool! \ No newline at end of file +# Quiz Game Project + +Build an interactive quiz application with multiple question types, scoring, and progress tracking. + +## Project Overview + +**What you'll build**: A quiz game that loads questions from files, presents them to users, tracks scores, and provides feedback on performance. + +**What you'll learn**: +- Object-oriented programming with classes +- JSON file handling for data storage +- Game logic and state management +- User interface design and interaction +- Score calculation and statistics +- Randomization and question shuffling + +## Project Features + +### Core Features +- Load questions from JSON files +- Multiple choice and true/false questions +- Score tracking and calculation +- Timer functionality (optional) +- Results summary and feedback +- Save high scores + +### Advanced Features +- Multiple quiz categories +- Difficulty levels +- Question randomization +- Detailed statistics and analytics +- User profiles and progress tracking +- Export results and certificates + +## Implementation Guide + +### Phase 1: Basic Quiz Structure +**Time**: 2-3 hours + +Create core quiz functionality: +- Question and Quiz classes +- Basic question presentation +- Score calculation +- Simple command-line interface + +**Key concepts**: Classes, methods, basic game logic + +### Phase 2: Data Management +**Time**: 2-3 hours + +Add file operations: +- Load questions from JSON files +- Save and load user scores +- Handle different question types +- Error handling for file operations + +**Key concepts**: File I/O, JSON handling, data validation + +### Phase 3: Enhanced Features +**Time**: 3-4 hours + +Implement advanced functionality: +- Categories and difficulty levels +- Timer and time tracking +- Question randomization +- Detailed feedback and explanations + +**Key concepts**: Advanced data structures, timing, randomization + +### Phase 4: GUI and Polish +**Time**: 4-5 hours + +Create graphical interface: +- Question display with buttons +- Progress bars and timers +- Results visualization +- Settings and preferences + +**Key concepts**: GUI programming, visual design, user experience + +## Getting Started + +### Setup +1. Plan the question data structure +2. Design the class hierarchy +3. Create sample question files + +### Question Class Design +```python +class Question: + def __init__(self, text, options, correct_answer, explanation="", difficulty="medium"): + self.text = text + self.options = options # List of possible answers + self.correct_answer = correct_answer # Index or text of correct answer + self.explanation = explanation + self.difficulty = difficulty + self.category = "" + + def is_correct(self, user_answer): + return user_answer == self.correct_answer + + def get_points(self): + difficulty_points = {"easy": 1, "medium": 2, "hard": 3} + return difficulty_points.get(self.difficulty, 1) +``` + +### Quiz Class Design +```python +import random +import time +from datetime import datetime + +class Quiz: + def __init__(self, questions, title="General Quiz"): + self.questions = questions + self.title = title + self.current_question = 0 + self.score = 0 + self.start_time = None + self.user_answers = [] + self.time_limit = None # seconds per question + + def start(self): + self.start_time = datetime.now() + self.shuffle_questions() + + def shuffle_questions(self): + random.shuffle(self.questions) + + def get_current_question(self): + if self.current_question < len(self.questions): + return self.questions[self.current_question] + return None + + def submit_answer(self, answer): + question = self.get_current_question() + if question: + is_correct = question.is_correct(answer) + if is_correct: + self.score += question.get_points() + + self.user_answers.append({ + 'question': question.text, + 'user_answer': answer, + 'correct_answer': question.correct_answer, + 'is_correct': is_correct + }) + + self.current_question += 1 + return is_correct + return False +``` + +## Question Data Structure + +### JSON Format +```json +{ + "quiz_title": "Python Programming Quiz", + "category": "Programming", + "questions": [ + { + "id": 1, + "text": "What is the output of print(2 ** 3)?", + "type": "multiple_choice", + "options": ["6", "8", "9", "12"], + "correct_answer": 1, + "explanation": "2 ** 3 means 2 to the power of 3, which equals 8.", + "difficulty": "easy", + "points": 1 + }, + { + "id": 2, + "text": "Python is a compiled language.", + "type": "true_false", + "options": ["True", "False"], + "correct_answer": 1, + "explanation": "Python is an interpreted language, not compiled.", + "difficulty": "medium", + "points": 2 + } + ] +} +``` + +### Question Types +- **Multiple Choice**: 4 options, one correct +- **True/False**: Two options +- **Fill in the Blank**: Text input required +- **Matching**: Match items from two lists + +## User Interface Design + +### Command Line Interface +```plaintext +=== PYTHON PROGRAMMING QUIZ === + +Question 1 of 10 Score: 0 + +What is the output of print(2 ** 3)? + +A) 6 +B) 8 +C) 9 +D) 12 + +Your answer (A/B/C/D): B + +Correct! 2 ** 3 means 2 to the power of 3, which equals 8. + +Press Enter to continue... +``` + +### GUI Layout +- Question counter and progress bar +- Question text display area +- Answer options as buttons or radio buttons +- Next/Submit button +- Score display +- Timer (if enabled) + +## Game Logic Implementation + +### Quiz Flow +```python +class QuizGame: + def __init__(self): + self.quizzes = {} + self.high_scores = [] + self.load_quizzes() + self.load_scores() + + def load_quizzes(self): + # Load quiz files from data directory + import os + import json + + quiz_dir = "data/quizzes" + for filename in os.listdir(quiz_dir): + if filename.endswith('.json'): + with open(os.path.join(quiz_dir, filename), 'r') as f: + quiz_data = json.load(f) + self.quizzes[quiz_data['category']] = self.create_quiz(quiz_data) + + def create_quiz(self, quiz_data): + questions = [] + for q_data in quiz_data['questions']: + question = Question( + text=q_data['text'], + options=q_data['options'], + correct_answer=q_data['correct_answer'], + explanation=q_data.get('explanation', ''), + difficulty=q_data.get('difficulty', 'medium') + ) + questions.append(question) + + return Quiz(questions, quiz_data['quiz_title']) +``` + +### Scoring System +```python +class ScoreCalculator: + @staticmethod + def calculate_final_score(quiz): + total_possible = sum(q.get_points() for q in quiz.questions) + percentage = (quiz.score / total_possible) * 100 if total_possible > 0 else 0 + + return { + 'raw_score': quiz.score, + 'total_possible': total_possible, + 'percentage': percentage, + 'grade': ScoreCalculator.get_letter_grade(percentage), + 'time_taken': ScoreCalculator.calculate_time_taken(quiz) + } + + @staticmethod + def get_letter_grade(percentage): + if percentage >= 90: return 'A' + elif percentage >= 80: return 'B' + elif percentage >= 70: return 'C' + elif percentage >= 60: return 'D' + else: return 'F' +``` + +## Advanced Features + +### Timer Implementation +```python +import threading +import time + +class QuizTimer: + def __init__(self, time_limit, callback): + self.time_limit = time_limit + self.callback = callback + self.start_time = None + self.is_running = False + + def start(self): + self.start_time = time.time() + self.is_running = True + timer_thread = threading.Thread(target=self._run_timer) + timer_thread.start() + + def _run_timer(self): + while self.is_running and self.get_remaining_time() > 0: + time.sleep(0.1) + + if self.is_running: + self.callback() # Time's up! + + def get_remaining_time(self): + if not self.start_time: + return self.time_limit + elapsed = time.time() - self.start_time + return max(0, self.time_limit - elapsed) +``` + +### Statistics and Analytics +```python +class QuizStatistics: + def __init__(self, quiz_results): + self.results = quiz_results + + def get_category_performance(self): + # Analyze performance by question category + pass + + def get_difficulty_analysis(self): + # Show performance by difficulty level + pass + + def get_improvement_suggestions(self): + # Provide personalized feedback + pass +``` + +## Testing Your Quiz Game + +### Test Scenarios +- Load different quiz files +- Answer questions correctly and incorrectly +- Test timer functionality +- Verify score calculations +- Test with various question types +- Handle invalid inputs gracefully + +### Sample Test Data +```json +{ + "quiz_title": "Test Quiz", + "category": "Test", + "questions": [ + { + "text": "Test question?", + "type": "multiple_choice", + "options": ["A", "B", "C", "D"], + "correct_answer": 0, + "difficulty": "easy" + } + ] +} +``` + +## Extensions and Improvements + +### Beginner Extensions +- Hint system for difficult questions +- Achievement badges and rewards +- Question favorites and bookmarks +- Simple quiz creation tool + +### Intermediate Extensions +- Multiplayer quiz competitions +- Adaptive difficulty adjustment +- Integration with external quiz APIs +- Mobile app version + +### Advanced Extensions +- AI-powered question generation +- Speech recognition for answers +- Virtual reality quiz environments +- Learning management system integration + +## Common Issues and Solutions + +**Issue**: Questions not loading from files +**Solution**: Check file paths, JSON syntax, and error handling + +**Issue**: Timer not working correctly +**Solution**: Use proper threading and time management + +**Issue**: Scores not calculating properly +**Solution**: Debug scoring logic and validate question data + +**Issue**: GUI freezing during quiz +**Solution**: Use proper event handling and avoid blocking operations + +## Learning Outcomes + +After completing this project, you'll understand: +- Object-oriented programming design patterns +- File operations and data serialization +- Game logic and state management +- User interface design and interaction +- Threading and timing operations +- Data analysis and statistics + +## File Structure + +``` +quiz_game/ +ā”œā”€ā”€ models/ +│ ā”œā”€ā”€ question.py # Question class +│ ā”œā”€ā”€ quiz.py # Quiz class +│ └── game.py # Main game logic +ā”œā”€ā”€ data/ +│ ā”œā”€ā”€ quizzes/ # Quiz JSON files +│ │ ā”œā”€ā”€ python.json +│ │ ā”œā”€ā”€ history.json +│ │ └── science.json +│ └── scores.json # High scores +ā”œā”€ā”€ ui/ +│ ā”œā”€ā”€ cli_interface.py # Command-line interface +│ └── gui_interface.py # Graphical interface +ā”œā”€ā”€ utils/ +│ ā”œā”€ā”€ timer.py # Timer functionality +│ ā”œā”€ā”€ statistics.py # Analytics and stats +│ └── file_handler.py # File operations +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your quiz game: +1. Create quiz content for your favorite subjects +2. Challenge friends and family to play +3. Add your own creative features +4. Share quizzes with the community +5. Try the Server project next for web-based applications + +Excellent work on building an engaging educational tool! \ No newline at end of file diff --git a/Projects/Intermediate/WebScraper/README.md b/Projects/Intermediate/WebScraper/README.md index 5156461..8237ad8 100644 --- a/Projects/Intermediate/WebScraper/README.md +++ b/Projects/Intermediate/WebScraper/README.md @@ -1 +1,403 @@ -# Web Scraper Project\n\nBuild a web scraping tool to extract data from websites and save it in structured formats.\n\n## Project Overview\n\n**What you'll build**: A web scraper that can extract specific data from websites, handle different page structures, and save results in various formats.\n\n**What you'll learn**:\n- HTTP requests and response handling\n- HTML parsing and navigation\n- Data extraction and cleaning\n- Working with external libraries\n- Error handling and retry logic\n- Ethical scraping practices\n\n## Project Features\n\n### Core Features\n- Send HTTP requests to websites\n- Parse HTML content\n- Extract specific data elements\n- Save data to files (CSV, JSON)\n- Handle basic error conditions\n- Simple progress tracking\n\n### Advanced Features\n- Handle JavaScript-rendered content\n- Manage sessions and cookies\n- Implement rate limiting and delays\n- Handle different file formats\n- Batch processing of multiple URLs\n- Data validation and cleaning\n\n## Implementation Guide\n\n### Phase 1: Basic Web Requests\n**Time**: 2-3 hours\n\nStart with simple HTTP requests:\n- Make requests to websites\n- Parse HTML with BeautifulSoup\n- Extract basic text content\n- Save to text files\n\n**Key concepts**: HTTP requests, HTML parsing, file operations\n\n### Phase 2: Structured Data Extraction\n**Time**: 3-4 hours\n\nExtract specific data:\n- Target specific HTML elements\n- Extract multiple data points\n- Structure data in dictionaries/lists\n- Save to CSV and JSON formats\n\n**Key concepts**: CSS selectors, data structures, file formats\n\n### Phase 3: Error Handling and Robustness\n**Time**: 3-4 hours\n\nMake scraper more reliable:\n- Handle network errors\n- Implement retry logic\n- Add rate limiting\n- Validate extracted data\n\n**Key concepts**: Exception handling, retry mechanisms, validation\n\n### Phase 4: Advanced Features\n**Time**: 4-5 hours\n\nAdd sophisticated functionality:\n- Handle dynamic content (Selenium)\n- Process multiple pages\n- Implement data cleaning\n- Create configurable scrapers\n\n**Key concepts**: Browser automation, configuration management, data processing\n\n## Getting Started\n\n### Required Libraries\n```bash\npip install requests beautifulsoup4 lxml pandas selenium\n```\n\n### Basic Setup\n```python\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport json\nimport time\nfrom urllib.parse import urljoin, urlparse\n\nclass WebScraper:\n def __init__(self, base_url, headers=None):\n self.base_url = base_url\n self.session = requests.Session()\n self.headers = headers or {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'\n }\n self.session.headers.update(self.headers)\n```\n\n## Core Functionality\n\n### Making HTTP Requests\n```python\ndef fetch_page(self, url, timeout=10):\n try:\n response = self.session.get(url, timeout=timeout)\n response.raise_for_status() # Raise exception for bad status codes\n return response\n except requests.RequestException as e:\n print(f\"Error fetching {url}: {e}\")\n return None\n```\n\n### HTML Parsing\n```python\ndef parse_html(self, html_content):\n return BeautifulSoup(html_content, 'html.parser')\n\ndef extract_data(self, soup, selectors):\n data = {}\n for key, selector in selectors.items():\n elements = soup.select(selector)\n if elements:\n data[key] = [elem.get_text(strip=True) for elem in elements]\n else:\n data[key] = []\n return data\n```\n\n## Example Scrapers\n\n### News Article Scraper\n```python\nclass NewsArticleScraper(WebScraper):\n def __init__(self):\n super().__init__(\"https://example-news-site.com\")\n self.selectors = {\n 'title': 'h1.article-title',\n 'author': '.author-name',\n 'date': '.publish-date',\n 'content': '.article-content p'\n }\n \n def scrape_article(self, article_url):\n response = self.fetch_page(article_url)\n if not response:\n return None\n \n soup = self.parse_html(response.text)\n return self.extract_data(soup, self.selectors)\n```\n\n### Product Information Scraper\n```python\nclass ProductScraper(WebScraper):\n def __init__(self):\n super().__init__(\"https://example-store.com\")\n self.selectors = {\n 'name': '.product-title',\n 'price': '.price',\n 'rating': '.rating',\n 'description': '.product-description'\n }\n \n def scrape_products(self, category_url):\n products = []\n response = self.fetch_page(category_url)\n if not response:\n return products\n \n soup = self.parse_html(response.text)\n product_links = soup.select('.product-link')\n \n for link in product_links:\n product_url = urljoin(self.base_url, link.get('href'))\n product_data = self.scrape_product(product_url)\n if product_data:\n products.append(product_data)\n time.sleep(1) # Rate limiting\n \n return products\n```\n\n## Data Storage and Export\n\n### Save to CSV\n```python\ndef save_to_csv(self, data, filename):\n if not data:\n return\n \n with open(filename, 'w', newline='', encoding='utf-8') as csvfile:\n fieldnames = data[0].keys()\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(data)\n```\n\n### Save to JSON\n```python\ndef save_to_json(self, data, filename):\n with open(filename, 'w', encoding='utf-8') as jsonfile:\n json.dump(data, jsonfile, indent=2, ensure_ascii=False)\n```\n\n## Error Handling and Best Practices\n\n### Retry Logic\n```python\ndef fetch_with_retry(self, url, max_retries=3, delay=1):\n for attempt in range(max_retries):\n try:\n response = self.fetch_page(url)\n if response:\n return response\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n if attempt < max_retries - 1:\n time.sleep(delay * (2 ** attempt)) # Exponential backoff\n return None\n```\n\n### Rate Limiting\n```python\nclass RateLimiter:\n def __init__(self, delay=1):\n self.delay = delay\n self.last_request = 0\n \n def wait(self):\n elapsed = time.time() - self.last_request\n if elapsed < self.delay:\n time.sleep(self.delay - elapsed)\n self.last_request = time.time()\n```\n\n### Respecting robots.txt\n```python\nimport urllib.robotparser\n\ndef can_fetch(self, url):\n rp = urllib.robotparser.RobotFileParser()\n rp.set_url(urljoin(url, '/robots.txt'))\n rp.read()\n return rp.can_fetch(self.headers.get('User-Agent', '*'), url)\n```\n\n## Advanced Features\n\n### JavaScript Rendering with Selenium\n```python\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass JavaScriptScraper:\n def __init__(self):\n self.driver = webdriver.Chrome() # Requires ChromeDriver\n \n def scrape_dynamic_content(self, url, wait_selector):\n self.driver.get(url)\n wait = WebDriverWait(self.driver, 10)\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, wait_selector)))\n return self.driver.page_source\n \n def close(self):\n self.driver.quit()\n```\n\n### Configuration-Driven Scraping\n```python\nscraper_config = {\n \"name\": \"news_scraper\",\n \"base_url\": \"https://example-news.com\",\n \"selectors\": {\n \"title\": \"h1.title\",\n \"content\": \".article-body p\"\n },\n \"rate_limit\": 2,\n \"output_format\": \"json\"\n}\n\nclass ConfigurableScraper:\n def __init__(self, config):\n self.config = config\n self.scraper = WebScraper(config['base_url'])\n self.rate_limiter = RateLimiter(config.get('rate_limit', 1))\n```\n\n## Testing Your Scraper\n\n### Test Targets\n- Start with simple, static websites\n- Test with different HTML structures\n- Handle missing elements gracefully\n- Test rate limiting and error handling\n- Validate extracted data\n\n### Sample Test Sites\n- http://quotes.toscrape.com/ (beginner-friendly)\n- https://books.toscrape.com/ (practice site)\n- https://httpbin.org/ (HTTP testing)\n\n## Ethical Considerations\n\n### Best Practices\n- Always check robots.txt\n- Respect rate limits and don't overload servers\n- Use appropriate User-Agent headers\n- Don't scrape copyrighted content without permission\n- Consider using official APIs when available\n\n### Legal Considerations\n- Review website terms of service\n- Understand copyright and data protection laws\n- Consider fair use principles\n- Respect website owners' wishes\n\n## Extensions and Improvements\n\n### Beginner Extensions\n- Email alert when new content is found\n- Simple data analysis and visualization\n- Scheduled scraping with cron jobs\n- Basic duplicate detection\n\n### Intermediate Extensions\n- Distributed scraping with multiple workers\n- Database storage for large datasets\n- Web interface for configuration\n- Integration with data analysis tools\n\n### Advanced Extensions\n- Machine learning for content classification\n- Proxy rotation for large-scale scraping\n- Real-time scraping with websockets\n- Cloud deployment and scaling\n\n## Common Issues and Solutions\n\n**Issue**: Scraper gets blocked by anti-bot measures\n**Solution**: Rotate User-Agents, use proxies, implement longer delays\n\n**Issue**: JavaScript content not loading\n**Solution**: Use Selenium or similar browser automation tools\n\n**Issue**: Data extraction returns empty results\n**Solution**: Inspect HTML structure, update selectors, handle dynamic content\n\n**Issue**: Memory usage grows too large\n**Solution**: Process data in batches, use generators, clear variables\n\n## Learning Outcomes\n\nAfter completing this project, you'll understand:\n- HTTP protocol and web communication\n- HTML structure and parsing techniques\n- Error handling and retry strategies\n- Data extraction and cleaning methods\n- Ethical considerations in web scraping\n- Working with external libraries and APIs\n\n## File Structure\n\n```\nweb_scraper/\nā”œā”€ā”€ scrapers/\n│ ā”œā”€ā”€ base_scraper.py # Base scraper class\n│ ā”œā”€ā”€ news_scraper.py # News website scraper\n│ └── product_scraper.py # E-commerce scraper\nā”œā”€ā”€ utils/\n│ ā”œā”€ā”€ rate_limiter.py # Rate limiting utilities\n│ ā”œā”€ā”€ data_cleaner.py # Data cleaning functions\n│ └── file_handler.py # File operations\nā”œā”€ā”€ config/\n│ ā”œā”€ā”€ scrapers.json # Scraper configurations\n│ └── settings.py # Global settings\nā”œā”€ā”€ data/\n│ ā”œā”€ā”€ raw/ # Raw scraped data\n│ └── processed/ # Cleaned data\nā”œā”€ā”€ logs/\n│ └── scraper.log # Scraping logs\n└── README.md # Project documentation\n```\n\n## Next Steps\n\nOnce you've completed your web scraper:\n1. Practice on different types of websites\n2. Build scrapers for your specific needs\n3. Learn about data analysis with pandas\n4. Explore API alternatives to scraping\n5. Try the Quiz Game project next for more interactive programming\n\nGreat job on building a powerful data collection tool! \ No newline at end of file +# Web Scraper Project + +Build a web scraping tool to extract data from websites and save it in structured formats. + +## Project Overview + +**What you'll build**: A web scraper that can extract specific data from websites, handle different page structures, and save results in various formats. + +**What you'll learn**: +- HTTP requests and response handling +- HTML parsing and navigation +- Data extraction and cleaning +- Working with external libraries +- Error handling and retry logic +- Ethical scraping practices + +## Project Features + +### Core Features +- Send HTTP requests to websites +- Parse HTML content +- Extract specific data elements +- Save data to files (CSV, JSON) +- Handle basic error conditions +- Simple progress tracking + +### Advanced Features +- Handle JavaScript-rendered content +- Manage sessions and cookies +- Implement rate limiting and delays +- Handle different file formats +- Batch processing of multiple URLs +- Data validation and cleaning + +## Implementation Guide + +### Phase 1: Basic Web Requests +**Time**: 2-3 hours + +Start with simple HTTP requests: +- Make requests to websites +- Parse HTML with BeautifulSoup +- Extract basic text content +- Save to text files + +**Key concepts**: HTTP requests, HTML parsing, file operations + +### Phase 2: Structured Data Extraction +**Time**: 3-4 hours + +Extract specific data: +- Target specific HTML elements +- Extract multiple data points +- Structure data in dictionaries/lists +- Save to CSV and JSON formats + +**Key concepts**: CSS selectors, data structures, file formats + +### Phase 3: Error Handling and Robustness +**Time**: 3-4 hours + +Make scraper more reliable: +- Handle network errors +- Implement retry logic +- Add rate limiting +- Validate extracted data + +**Key concepts**: Exception handling, retry mechanisms, validation + +### Phase 4: Advanced Features +**Time**: 4-5 hours + +Add sophisticated functionality: +- Handle dynamic content (Selenium) +- Process multiple pages +- Implement data cleaning +- Create configurable scrapers + +**Key concepts**: Browser automation, configuration management, data processing + +## Getting Started + +### Required Libraries +```bash +pip install requests beautifulsoup4 lxml pandas selenium +``` + +### Basic Setup +```python +import requests +from bs4 import BeautifulSoup +import csv +import json +import time +from urllib.parse import urljoin, urlparse + +class WebScraper: + def __init__(self, base_url, headers=None): + self.base_url = base_url + self.session = requests.Session() + self.headers = headers or { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' + } + self.session.headers.update(self.headers) +``` + +## Core Functionality + +### Making HTTP Requests +```python +def fetch_page(self, url, timeout=10): + try: + response = self.session.get(url, timeout=timeout) + response.raise_for_status() # Raise exception for bad status codes + return response + except requests.RequestException as e: + print(f"Error fetching {url}: {e}") + return None +``` + +### HTML Parsing +```python +def parse_html(self, html_content): + return BeautifulSoup(html_content, 'html.parser') + +def extract_data(self, soup, selectors): + data = {} + for key, selector in selectors.items(): + elements = soup.select(selector) + if elements: + data[key] = [elem.get_text(strip=True) for elem in elements] + else: + data[key] = [] + return data +``` + +## Example Scrapers + +### News Article Scraper +```python +class NewsArticleScraper(WebScraper): + def __init__(self): + super().__init__("https://example-news-site.com") + self.selectors = { + 'title': 'h1.article-title', + 'author': '.author-name', + 'date': '.publish-date', + 'content': '.article-content p' + } + + def scrape_article(self, article_url): + response = self.fetch_page(article_url) + if not response: + return None + + soup = self.parse_html(response.text) + return self.extract_data(soup, self.selectors) +``` + +### Product Information Scraper +```python +class ProductScraper(WebScraper): + def __init__(self): + super().__init__("https://example-store.com") + self.selectors = { + 'name': '.product-title', + 'price': '.price', + 'rating': '.rating', + 'description': '.product-description' + } + + def scrape_products(self, category_url): + products = [] + response = self.fetch_page(category_url) + if not response: + return products + + soup = self.parse_html(response.text) + product_links = soup.select('.product-link') + + for link in product_links: + product_url = urljoin(self.base_url, link.get('href')) + product_data = self.scrape_product(product_url) + if product_data: + products.append(product_data) + time.sleep(1) # Rate limiting + + return products +``` + +## Data Storage and Export + +### Save to CSV +```python +def save_to_csv(self, data, filename): + if not data: + return + + with open(filename, 'w', newline='', encoding='utf-8') as csvfile: + fieldnames = data[0].keys() + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(data) +``` + +### Save to JSON +```python +def save_to_json(self, data, filename): + with open(filename, 'w', encoding='utf-8') as jsonfile: + json.dump(data, jsonfile, indent=2, ensure_ascii=False) +``` + +## Error Handling and Best Practices + +### Retry Logic +```python +def fetch_with_retry(self, url, max_retries=3, delay=1): + for attempt in range(max_retries): + try: + response = self.fetch_page(url) + if response: + return response + except Exception as e: + print(f"Attempt {attempt + 1} failed: {e}") + if attempt < max_retries - 1: + time.sleep(delay * (2 ** attempt)) # Exponential backoff + return None +``` + +### Rate Limiting +```python +class RateLimiter: + def __init__(self, delay=1): + self.delay = delay + self.last_request = 0 + + def wait(self): + elapsed = time.time() - self.last_request + if elapsed < self.delay: + time.sleep(self.delay - elapsed) + self.last_request = time.time() +``` + +### Respecting robots.txt +```python +import urllib.robotparser + +def can_fetch(self, url): + rp = urllib.robotparser.RobotFileParser() + rp.set_url(urljoin(url, '/robots.txt')) + rp.read() + return rp.can_fetch(self.headers.get('User-Agent', '*'), url) +``` + +## Advanced Features + +### JavaScript Rendering with Selenium +```python +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC + +class JavaScriptScraper: + def __init__(self): + self.driver = webdriver.Chrome() # Requires ChromeDriver + + def scrape_dynamic_content(self, url, wait_selector): + self.driver.get(url) + wait = WebDriverWait(self.driver, 10) + wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, wait_selector))) + return self.driver.page_source + + def close(self): + self.driver.quit() +``` + +### Configuration-Driven Scraping +```python +scraper_config = { + "name": "news_scraper", + "base_url": "https://example-news.com", + "selectors": { + "title": "h1.title", + "content": ".article-body p" + }, + "rate_limit": 2, + "output_format": "json" +} + +class ConfigurableScraper: + def __init__(self, config): + self.config = config + self.scraper = WebScraper(config['base_url']) + self.rate_limiter = RateLimiter(config.get('rate_limit', 1)) +``` + +## Testing Your Scraper + +### Test Targets +- Start with simple, static websites +- Test with different HTML structures +- Handle missing elements gracefully +- Test rate limiting and error handling +- Validate extracted data + +### Sample Test Sites +- http://quotes.toscrape.com/ (beginner-friendly) +- https://books.toscrape.com/ (practice site) +- https://httpbin.org/ (HTTP testing) + +## Ethical Considerations + +### Best Practices +- Always check robots.txt +- Respect rate limits and don't overload servers +- Use appropriate User-Agent headers +- Don't scrape copyrighted content without permission +- Consider using official APIs when available + +### Legal Considerations +- Review website terms of service +- Understand copyright and data protection laws +- Consider fair use principles +- Respect website owners' wishes + +## Extensions and Improvements + +### Beginner Extensions +- Email alert when new content is found +- Simple data analysis and visualization +- Scheduled scraping with cron jobs +- Basic duplicate detection + +### Intermediate Extensions +- Distributed scraping with multiple workers +- Database storage for large datasets +- Web interface for configuration +- Integration with data analysis tools + +### Advanced Extensions +- Machine learning for content classification +- Proxy rotation for large-scale scraping +- Real-time scraping with websockets +- Cloud deployment and scaling + +## Common Issues and Solutions + +**Issue**: Scraper gets blocked by anti-bot measures +**Solution**: Rotate User-Agents, use proxies, implement longer delays + +**Issue**: JavaScript content not loading +**Solution**: Use Selenium or similar browser automation tools + +**Issue**: Data extraction returns empty results +**Solution**: Inspect HTML structure, update selectors, handle dynamic content + +**Issue**: Memory usage grows too large +**Solution**: Process data in batches, use generators, clear variables + +## Learning Outcomes + +After completing this project, you'll understand: +- HTTP protocol and web communication +- HTML structure and parsing techniques +- Error handling and retry strategies +- Data extraction and cleaning methods +- Ethical considerations in web scraping +- Working with external libraries and APIs + +## File Structure + +``` +web_scraper/ +ā”œā”€ā”€ scrapers/ +│ ā”œā”€ā”€ base_scraper.py # Base scraper class +│ ā”œā”€ā”€ news_scraper.py # News website scraper +│ └── product_scraper.py # E-commerce scraper +ā”œā”€ā”€ utils/ +│ ā”œā”€ā”€ rate_limiter.py # Rate limiting utilities +│ ā”œā”€ā”€ data_cleaner.py # Data cleaning functions +│ └── file_handler.py # File operations +ā”œā”€ā”€ config/ +│ ā”œā”€ā”€ scrapers.json # Scraper configurations +│ └── settings.py # Global settings +ā”œā”€ā”€ data/ +│ ā”œā”€ā”€ raw/ # Raw scraped data +│ └── processed/ # Cleaned data +ā”œā”€ā”€ logs/ +│ └── scraper.log # Scraping logs +└── README.md # Project documentation +``` + +## Next Steps + +Once you've completed your web scraper: +1. Practice on different types of websites +2. Build scrapers for your specific needs +3. Learn about data analysis with pandas +4. Explore API alternatives to scraping +5. Try the Quiz Game project next for more interactive programming + +Great job on building a powerful data collection tool! \ No newline at end of file diff --git a/Projects/README.md b/Projects/README.md index fe6c73d..72cbb2f 100644 --- a/Projects/README.md +++ b/Projects/README.md @@ -18,17 +18,17 @@ Welcome to the Python Projects section! These projects are designed to help you | Project | Key Concepts | |---------|-------------| -| [Contact Book](ContactBook/) | Classes, file persistence, data validation | -| [Expense Tracker](ExpenseTracker/) | Data analysis, file handling, date/time operations | -| [Web Scraper](WebScraper/) | HTTP requests, HTML parsing, data processing | -| [Quiz Game](QuizGame/) | Object-oriented programming, JSON handling | +| [Contact Book](./Intermediate/ContactBook/README.md) | Classes, file persistence, data validation | +| [Expense Tracker](./Intermediate/ExpenseTracker/README.md) | Data analysis, file handling, date/time operations | +| [Web Scraper](./Intermediate/WebScraper/README.md) | HTTP requests, HTML parsing, data processing | +| [Quiz Game](./Intermediate/QuizGame/README.md) | Object-oriented programming, JSON handling | ### Advanced Level Projects | Project | Key Concepts | |---------|-------------| -| [Server](Server/) | Web frameworks, HTTP protocols, databases | -| [Data Analysis Dashboard](DataDashboard/) | Data science libraries, visualization, statistics | +| [Server](./Advanced/Server/README.md) | Web frameworks, HTTP protocols, databases | +| [Data Analysis Dashboard](./Advanced/DataDashboard/README.md) | Data science libraries, visualization, statistics | ## Getting Started