From 9168b4c4e32d2b0e4e2a30f2c4f241569b15430f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 9 Jan 2026 04:53:54 +0000 Subject: [PATCH 1/2] Initial plan From 8d1ce5fcad397c83c7eb78771db61c597288fc44 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 9 Jan 2026 05:01:10 +0000 Subject: [PATCH 2/2] Create complete beginner-friendly Python learning repository with comprehensive content Co-authored-by: karan7307 <217415028+karan7307@users.noreply.github.com> --- .gitignore | 52 +++ 01_Basics/01_variables_and_datatypes.py | 162 ++++++++ 01_Basics/02_input_output.py | 179 ++++++++ 01_Basics/03_operators.py | 227 ++++++++++ 02_Conditions/01_if_else_statements.py | 294 +++++++++++++ 02_Conditions/02_nested_conditions.py | 291 +++++++++++++ 03_Loops/01_for_loops.py | 313 ++++++++++++++ 03_Loops/02_while_loops.py | 370 +++++++++++++++++ 04_Functions/01_functions_basics.py | 414 +++++++++++++++++++ 05_File_Handling/01_file_operations.py | 369 +++++++++++++++++ 06_Mini_Projects/01_calculator.py | 182 ++++++++ 06_Mini_Projects/02_number_guessing_game.py | 219 ++++++++++ 06_Mini_Projects/03_student_grade_manager.py | 326 +++++++++++++++ README.md | 118 +++++- 14 files changed, 3514 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 01_Basics/01_variables_and_datatypes.py create mode 100644 01_Basics/02_input_output.py create mode 100644 01_Basics/03_operators.py create mode 100644 02_Conditions/01_if_else_statements.py create mode 100644 02_Conditions/02_nested_conditions.py create mode 100644 03_Loops/01_for_loops.py create mode 100644 03_Loops/02_while_loops.py create mode 100644 04_Functions/01_functions_basics.py create mode 100644 05_File_Handling/01_file_operations.py create mode 100644 06_Mini_Projects/01_calculator.py create mode 100644 06_Mini_Projects/02_number_guessing_game.py create mode 100644 06_Mini_Projects/03_student_grade_manager.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f42c72e --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# Virtual environments +venv/ +ENV/ +env/ +.venv + +# IDEs +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS files +.DS_Store +Thumbs.db + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Temporary files +*.log +*.tmp +tmp/ diff --git a/01_Basics/01_variables_and_datatypes.py b/01_Basics/01_variables_and_datatypes.py new file mode 100644 index 0000000..19c351b --- /dev/null +++ b/01_Basics/01_variables_and_datatypes.py @@ -0,0 +1,162 @@ +""" +VARIABLES AND DATA TYPES IN PYTHON +=================================== + +What are Variables? +------------------- +Variables are containers that store data values. +Think of them as labeled boxes where you can keep different types of information. + +Python has several built-in data types: +1. Integer (int) - Whole numbers +2. Float - Decimal numbers +3. String (str) - Text +4. Boolean (bool) - True or False +5. List - Collection of items +6. Dictionary (dict) - Key-value pairs +""" + +# ============================================ +# NUMBERS (Integers and Floats) +# ============================================ + +# Integer - whole numbers without decimal points +age = 20 +print("Age:", age) +print("Type of age:", type(age)) # type() tells us what kind of data it is + +# Float - numbers with decimal points +height = 5.9 +print("\nHeight:", height) +print("Type of height:", type(height)) + +# You can do math with numbers +students = 30 +present = 28 +absent = students - present +print("\nTotal students:", students) +print("Present:", present) +print("Absent:", absent) + + +# ============================================ +# STRINGS (Text) +# ============================================ + +# Strings are text enclosed in quotes (single or double) +name = "Alice" +greeting = 'Hello' +print("\n" + greeting + ", " + name + "!") + +# You can combine (concatenate) strings with + +first_name = "John" +last_name = "Doe" +full_name = first_name + " " + last_name +print("Full name:", full_name) + +# String length +message = "Python is fun!" +print("Message:", message) +print("Length of message:", len(message)) + + +# ============================================ +# BOOLEANS (True or False) +# ============================================ + +# Booleans represent truth values +is_student = True +has_graduated = False + +print("\nIs student?", is_student) +print("Has graduated?", has_graduated) + +# Booleans are often used in conditions +is_learning_python = True +if is_learning_python: + print("Keep practicing!") + + +# ============================================ +# LISTS (Collections) +# ============================================ + +# Lists store multiple items in a single variable +fruits = ["apple", "banana", "orange", "mango"] +print("\nFruits list:", fruits) +print("First fruit:", fruits[0]) # Lists start counting from 0 +print("Second fruit:", fruits[1]) +print("Number of fruits:", len(fruits)) + +# Lists with numbers +scores = [85, 90, 78, 92, 88] +print("\nScores:", scores) +print("Highest score:", max(scores)) +print("Lowest score:", min(scores)) + + +# ============================================ +# DICTIONARIES (Key-Value Pairs) +# ============================================ + +# Dictionaries store data in key-value pairs +student_info = { + "name": "Emma", + "age": 21, + "grade": "A", + "is_active": True +} + +print("\nStudent Information:") +print("Name:", student_info["name"]) +print("Age:", student_info["age"]) +print("Grade:", student_info["grade"]) + + +# ============================================ +# TYPE CONVERSION +# ============================================ + +# You can convert between different data types +number_as_string = "100" +actual_number = int(number_as_string) # Convert string to integer +print("\nString '100' converted to integer:", actual_number) +print("Now we can do math: 100 + 50 =", actual_number + 50) + +# Convert integer to string +score = 95 +score_text = str(score) +message = "Your score is " + score_text +print(message) + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "="*50) +print("PRACTICE PROBLEMS") +print("="*50) + +""" +Try these exercises: + +1. Create a variable called 'city' and assign your city name to it. + Then print it. + +2. Create two number variables and store your age and a friend's age. + Calculate and print the age difference. + +3. Create a list of 5 favorite movies and print the list. + Then print only the first and last movie. + +4. Create a dictionary to store information about your favorite book: + title, author, year, and pages. + Print each piece of information. + +5. Create a string variable with a number like "25", convert it to + an integer, multiply by 2, and print the result. +""" + +print("\nTry solving the practice problems above!") +print("Write your solutions in a new file or below this code.") diff --git a/01_Basics/02_input_output.py b/01_Basics/02_input_output.py new file mode 100644 index 0000000..465c460 --- /dev/null +++ b/01_Basics/02_input_output.py @@ -0,0 +1,179 @@ +""" +INPUT AND OUTPUT IN PYTHON +========================== + +Input: Getting data FROM the user +Output: Showing data TO the user +""" + +# ============================================ +# OUTPUT - Printing to the screen +# ============================================ + +print("Hello, World!") # Basic print statement +print() # Empty line for spacing + +# Printing multiple items +print("Python", "is", "awesome!") + +# Printing with variables +name = "Sarah" +print("Welcome,", name) + +# Using f-strings (formatted strings) - Easy and modern way +age = 19 +print(f"Hello! My name is {name} and I am {age} years old.") + +# Printing with .format() method +city = "New York" +print("I live in {}.".format(city)) + +# Printing numbers and calculations +x = 10 +y = 20 +print(f"{x} + {y} = {x + y}") + + +# ============================================ +# INPUT - Getting data from the user +# ============================================ + +# Basic input - input() always returns a string +print("\n" + "="*50) +print("Let's get some information from you!") +print("="*50 + "\n") + +# Getting user's name +user_name = input("What is your name? ") +print(f"Nice to meet you, {user_name}!") + +# Getting user's age (need to convert to integer) +user_age = input("How old are you? ") +print(f"You are {user_age} years old.") + +# Converting input to integer for calculations +user_age_number = int(user_age) +years_to_30 = 30 - user_age_number +if years_to_30 > 0: + print(f"You will be 30 years old in {years_to_30} years!") +elif years_to_30 == 0: + print("You are exactly 30 years old!") +else: + print(f"You turned 30 about {abs(years_to_30)} years ago!") + + +# ============================================ +# SIMPLE INPUT/OUTPUT PROGRAMS +# ============================================ + +print("\n" + "="*50) +print("PROGRAM 1: GREETING PROGRAM") +print("="*50 + "\n") + +# Get user information +first_name = input("Enter your first name: ") +favorite_color = input("What's your favorite color? ") +favorite_number = input("What's your favorite number? ") + +# Display personalized message +print(f"\nHello {first_name}!") +print(f"Your favorite color is {favorite_color}.") +print(f"Your favorite number is {favorite_number}.") +print("Thank you for sharing!") + + +print("\n" + "="*50) +print("PROGRAM 2: SIMPLE CALCULATOR") +print("="*50 + "\n") + +# Get two numbers from user +num1 = input("Enter first number: ") +num2 = input("Enter second number: ") + +# Convert strings to numbers +number1 = float(num1) # Using float to handle decimals +number2 = float(num2) + +# Perform calculations +addition = number1 + number2 +subtraction = number1 - number2 +multiplication = number1 * number2 +division = number1 / number2 + +# Display results +print(f"\n{number1} + {number2} = {addition}") +print(f"{number1} - {number2} = {subtraction}") +print(f"{number1} × {number2} = {multiplication}") +print(f"{number1} ÷ {number2} = {division}") + + +print("\n" + "="*50) +print("PROGRAM 3: AREA CALCULATOR") +print("="*50 + "\n") + +# Calculate area of a rectangle +length = float(input("Enter length of rectangle: ")) +width = float(input("Enter width of rectangle: ")) + +area = length * width +perimeter = 2 * (length + width) + +print(f"\nArea of rectangle: {area}") +print(f"Perimeter of rectangle: {perimeter}") + + +# ============================================ +# FORMATTED OUTPUT - Making output look nice +# ============================================ + +print("\n" + "="*50) +print("FORMATTED OUTPUT EXAMPLES") +print("="*50 + "\n") + +# Aligning text +print(f"{'Item':<15} {'Price':>10}") # <15 means left-align in 15 spaces +print(f"{'Apple':<15} {'$2.50':>10}") +print(f"{'Banana':<15} {'$1.25':>10}") +print(f"{'Orange':<15} {'$3.00':>10}") + +# Formatting decimal numbers +pi = 3.14159265359 +print(f"\nValue of Pi: {pi}") +print(f"Pi rounded to 2 decimals: {pi:.2f}") # .2f means 2 decimal places + +price = 19.5 +print(f"Price: ${price:.2f}") # Ensures two decimal places + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "="*50) +print("PRACTICE PROBLEMS") +print("="*50) + +""" +Try these exercises: + +1. Write a program that asks for your name and your friend's name, + then prints "Hello [your name] and [friend's name]!" + +2. Create a program that asks for two numbers and displays their sum, + difference, product, and quotient. + +3. Write a program that asks for your birth year and calculates your age + (assuming current year is 2024). + +4. Create a program that asks for temperature in Celsius and converts + it to Fahrenheit using the formula: F = (C × 9/5) + 32 + +5. Write a program that asks for your name, favorite hobby, and how many + hours you spend on it per week. Then print a nice summary message. + +6. Create a simple shopping program that asks for item name, quantity, + and price per item, then calculates and displays the total cost. +""" + +print("\nTry solving the practice problems above!") +print("Create a new Python file and write your solutions there.") diff --git a/01_Basics/03_operators.py b/01_Basics/03_operators.py new file mode 100644 index 0000000..276cbc6 --- /dev/null +++ b/01_Basics/03_operators.py @@ -0,0 +1,227 @@ +""" +OPERATORS IN PYTHON +=================== + +Operators are special symbols that perform operations on variables and values. +Python has several types of operators: +1. Arithmetic Operators - For math operations +2. Comparison Operators - For comparing values +3. Logical Operators - For combining conditions +4. Assignment Operators - For assigning values +""" + +# ============================================ +# ARITHMETIC OPERATORS +# ============================================ + +print("=" * 50) +print("ARITHMETIC OPERATORS") +print("=" * 50 + "\n") + +a = 15 +b = 4 + +print(f"a = {a}, b = {b}\n") + +# Addition +print(f"Addition: {a} + {b} = {a + b}") + +# Subtraction +print(f"Subtraction: {a} - {b} = {a - b}") + +# Multiplication +print(f"Multiplication: {a} × {b} = {a * b}") + +# Division (always returns float) +print(f"Division: {a} ÷ {b} = {a / b}") + +# Floor Division (returns integer, rounds down) +print(f"Floor Division: {a} ÷÷ {b} = {a // b}") + +# Modulus (remainder after division) +print(f"Modulus: {a} % {b} = {a % b}") + +# Exponentiation (power) +print(f"Exponentiation: {a} ^ {b} = {a ** b}") + + +# ============================================ +# COMPARISON OPERATORS +# ============================================ + +print("\n" + "=" * 50) +print("COMPARISON OPERATORS") +print("=" * 50 + "\n") + +x = 10 +y = 20 + +print(f"x = {x}, y = {y}\n") + +# Equal to +print(f"Is x equal to y? {x} == {y} : {x == y}") + +# Not equal to +print(f"Is x not equal to y? {x} != {y} : {x != y}") + +# Greater than +print(f"Is x greater than y? {x} > {y} : {x > y}") + +# Less than +print(f"Is x less than y? {x} < {y} : {x < y}") + +# Greater than or equal to +print(f"Is x greater than or equal to y? {x} >= {y} : {x >= y}") + +# Less than or equal to +print(f"Is x less than or equal to y? {x} <= {y} : {x <= y}") + + +# ============================================ +# LOGICAL OPERATORS +# ============================================ + +print("\n" + "=" * 50) +print("LOGICAL OPERATORS") +print("=" * 50 + "\n") + +# Logical operators are used to combine conditions +age = 22 +has_license = True +has_car = False + +# AND - Both conditions must be True +print(f"Age: {age}, Has License: {has_license}, Has Car: {has_car}\n") +print(f"Can drive? (age >= 18 AND has_license): {age >= 18 and has_license}") +print(f"Can drive own car? (has_license AND has_car): {has_license and has_car}") + +# OR - At least one condition must be True +is_weekend = True +is_holiday = False +print(f"\nIs Weekend: {is_weekend}, Is Holiday: {is_holiday}") +print(f"Can relax? (is_weekend OR is_holiday): {is_weekend or is_holiday}") + +# NOT - Reverses the boolean value +is_raining = False +print(f"\nIs it raining? {is_raining}") +print(f"Is it NOT raining? {not is_raining}") + + +# ============================================ +# ASSIGNMENT OPERATORS +# ============================================ + +print("\n" + "=" * 50) +print("ASSIGNMENT OPERATORS") +print("=" * 50 + "\n") + +# Simple assignment +score = 50 +print(f"Initial score: {score}") + +# Add and assign +score += 10 # Same as: score = score + 10 +print(f"After += 10: {score}") + +# Subtract and assign +score -= 5 # Same as: score = score - 5 +print(f"After -= 5: {score}") + +# Multiply and assign +score *= 2 # Same as: score = score * 2 +print(f"After *= 2: {score}") + +# Divide and assign +score /= 4 # Same as: score = score / 4 +print(f"After /= 4: {score}") + + +# ============================================ +# PRACTICAL EXAMPLES +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICAL EXAMPLES") +print("=" * 50 + "\n") + +# Example 1: Calculate total bill with tip +bill_amount = 100 +tip_percentage = 15 +tip = bill_amount * (tip_percentage / 100) +total = bill_amount + tip + +print("RESTAURANT BILL CALCULATOR") +print(f"Bill Amount: ${bill_amount}") +print(f"Tip ({tip_percentage}%): ${tip}") +print(f"Total to pay: ${total}") + + +# Example 2: Check if number is even or odd +number = 17 +is_even = (number % 2 == 0) +print(f"\nIs {number} an even number? {is_even}") + + +# Example 3: Check eligibility for discount +print("\nDISCOUNT ELIGIBILITY CHECKER") +purchase_amount = 150 +is_member = True +has_coupon = False + +# Gets discount if purchase > 100 AND (is member OR has coupon) +eligible_for_discount = purchase_amount > 100 and (is_member or has_coupon) +print(f"Purchase Amount: ${purchase_amount}") +print(f"Is Member: {is_member}") +print(f"Has Coupon: {has_coupon}") +print(f"Eligible for discount: {eligible_for_discount}") + + +# Example 4: Temperature checker +print("\nTEMPERATURE CHECKER") +temperature = 28 +is_hot = temperature > 30 +is_cold = temperature < 15 +is_comfortable = not is_hot and not is_cold + +print(f"Temperature: {temperature}°C") +print(f"Is it hot? {is_hot}") +print(f"Is it cold? {is_cold}") +print(f"Is it comfortable? {is_comfortable}") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a program that takes two numbers and prints whether the first + number is greater than, less than, or equal to the second number. + +2. Create a program that calculates the area and perimeter of a circle + given its radius. (Area = π × r², Perimeter = 2 × π × r) + Use 3.14159 for π. + +3. Write a program to check if a student passes an exam. A student passes if: + - Score is >= 40 AND + - Attendance is >= 75% + +4. Create a simple program that converts kilometers to miles. + (1 kilometer = 0.621371 miles) + +5. Write a program that checks if a year is a leap year. + A year is a leap year if: + - It is divisible by 4 AND + - (Not divisible by 100 OR divisible by 400) + +6. Create a program that calculates the discount amount and final price. + If purchase > $100, give 10% discount, otherwise 5% discount. +""" + +print("\nTry solving the practice problems above!") +print("Practice makes perfect! Happy coding!") diff --git a/02_Conditions/01_if_else_statements.py b/02_Conditions/01_if_else_statements.py new file mode 100644 index 0000000..0ea49a9 --- /dev/null +++ b/02_Conditions/01_if_else_statements.py @@ -0,0 +1,294 @@ +""" +IF-ELSE STATEMENTS IN PYTHON +============================= + +Conditional statements allow your program to make decisions. +They execute different code based on whether conditions are True or False. + +Basic Structure: + if condition: + # code to run if condition is True + elif another_condition: + # code to run if another_condition is True + else: + # code to run if all conditions are False +""" + +# ============================================ +# SIMPLE IF STATEMENT +# ============================================ + +print("=" * 50) +print("SIMPLE IF STATEMENT") +print("=" * 50 + "\n") + +age = 18 +if age >= 18: + print("You are an adult!") + print("You can vote!") + +print() # Empty line + +# Another example +temperature = 35 +if temperature > 30: + print("It's hot outside! Drink plenty of water.") + + +# ============================================ +# IF-ELSE STATEMENT +# ============================================ + +print("\n" + "=" * 50) +print("IF-ELSE STATEMENT") +print("=" * 50 + "\n") + +score = 75 + +if score >= 50: + print(f"Score: {score}") + print("Result: PASS ✓") +else: + print(f"Score: {score}") + print("Result: FAIL ✗") + + +# Example 2: Check if number is even or odd +number = 17 + +if number % 2 == 0: + print(f"\n{number} is an even number") +else: + print(f"\n{number} is an odd number") + + +# ============================================ +# IF-ELIF-ELSE STATEMENT +# ============================================ + +print("\n" + "=" * 50) +print("IF-ELIF-ELSE STATEMENT") +print("=" * 50 + "\n") + +# Grade calculator +marks = 85 + +print(f"Marks: {marks}") + +if marks >= 90: + print("Grade: A+ (Excellent!)") +elif marks >= 80: + print("Grade: A (Very Good!)") +elif marks >= 70: + print("Grade: B (Good)") +elif marks >= 60: + print("Grade: C (Average)") +elif marks >= 50: + print("Grade: D (Pass)") +else: + print("Grade: F (Fail)") + + +# Example 2: Traffic light system +print("\n") +traffic_light = "yellow" + +if traffic_light == "red": + print("STOP! 🔴") +elif traffic_light == "yellow": + print("SLOW DOWN! 🟡") +elif traffic_light == "green": + print("GO! 🟢") +else: + print("Invalid traffic light color!") + + +# ============================================ +# NESTED IF STATEMENTS +# ============================================ + +print("\n" + "=" * 50) +print("NESTED IF STATEMENTS") +print("=" * 50 + "\n") + +# Movie ticket price calculator +age = 25 +is_student = True + +print(f"Age: {age}, Student: {is_student}") + +if age < 12: + price = 5 + print("Ticket Price: $5 (Child)") +elif age >= 60: + price = 7 + print("Ticket Price: $7 (Senior)") +else: + # Nested if for adult tickets + if is_student: + price = 8 + print("Ticket Price: $8 (Student)") + else: + price = 12 + print("Ticket Price: $12 (Adult)") + + +# ============================================ +# MULTIPLE CONDITIONS (AND, OR) +# ============================================ + +print("\n" + "=" * 50) +print("MULTIPLE CONDITIONS") +print("=" * 50 + "\n") + +# Example 1: Check if person can drive +age = 20 +has_license = True + +if age >= 18 and has_license: + print("You can drive! ✓") +else: + print("You cannot drive.") + if age < 18: + print("Reason: You are under 18") + if not has_license: + print("Reason: You don't have a license") + + +# Example 2: Weekend or Holiday checker +print() +day = "Sunday" +is_holiday = False + +if day == "Saturday" or day == "Sunday" or is_holiday: + print("Yay! It's time to relax! 🎉") +else: + print("It's a working day. Stay productive! 💼") + + +# ============================================ +# PRACTICAL PROGRAMS +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: LOGIN SYSTEM") +print("=" * 50 + "\n") + +# Simple login checker +correct_username = "admin" +correct_password = "python123" + +username = "admin" +password = "python123" + +if username == correct_username and password == correct_password: + print("✓ Login successful! Welcome!") +else: + print("✗ Login failed! Invalid credentials.") + + +print("\n" + "=" * 50) +print("PROGRAM 2: DISCOUNT CALCULATOR") +print("=" * 50 + "\n") + +purchase_amount = 150 +is_member = True + +print(f"Purchase Amount: ${purchase_amount}") +print(f"Membership: {is_member}") + +if purchase_amount >= 200: + discount = 20 +elif purchase_amount >= 100 and is_member: + discount = 15 +elif purchase_amount >= 100: + discount = 10 +elif purchase_amount >= 50: + discount = 5 +else: + discount = 0 + +discount_amount = purchase_amount * (discount / 100) +final_price = purchase_amount - discount_amount + +print(f"Discount: {discount}%") +print(f"Discount Amount: ${discount_amount}") +print(f"Final Price: ${final_price}") + + +print("\n" + "=" * 50) +print("PROGRAM 3: SIMPLE CALCULATOR") +print("=" * 50 + "\n") + +num1 = 10 +num2 = 5 +operation = "+" + +print(f"Number 1: {num1}") +print(f"Number 2: {num2}") +print(f"Operation: {operation}\n") + +if operation == "+": + result = num1 + num2 + print(f"Result: {num1} + {num2} = {result}") +elif operation == "-": + result = num1 - num2 + print(f"Result: {num1} - {num2} = {result}") +elif operation == "*": + result = num1 * num2 + print(f"Result: {num1} × {num2} = {result}") +elif operation == "/": + if num2 != 0: + result = num1 / num2 + print(f"Result: {num1} ÷ {num2} = {result}") + else: + print("Error: Cannot divide by zero!") +else: + print("Error: Invalid operation!") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a program that checks if a number is positive, negative, or zero. + +2. Create a program that takes a person's age and tells them which category + they belong to: + - 0-12: Child + - 13-19: Teenager + - 20-59: Adult + - 60+: Senior + +3. Write a program that checks if a triangle is valid. A triangle is valid if + the sum of any two sides is greater than the third side. + (Check for all three combinations) + +4. Create a BMI calculator that categorizes the result: + - BMI < 18.5: Underweight + - BMI 18.5-24.9: Normal weight + - BMI 25-29.9: Overweight + - BMI >= 30: Obese + Formula: BMI = weight(kg) / (height(m) × height(m)) + +5. Write a program that determines if a student gets admission to a college. + Admission requirements: + - Math score >= 80 AND + - Science score >= 75 AND + - English score >= 70 + +6. Create a simple menu system for a restaurant with at least 5 items. + Based on the choice, display the item name and price. + +7. Write a program to find the largest of three numbers. +""" + +print("\nTry solving the practice problems above!") +print("Remember: Practice is the key to mastering programming!") diff --git a/02_Conditions/02_nested_conditions.py b/02_Conditions/02_nested_conditions.py new file mode 100644 index 0000000..a1948aa --- /dev/null +++ b/02_Conditions/02_nested_conditions.py @@ -0,0 +1,291 @@ +""" +NESTED CONDITIONS IN PYTHON +============================ + +Nested conditions means having if-else statements inside other if-else statements. +This is useful when you need to check multiple conditions in a hierarchical way. +""" + +# ============================================ +# BASIC NESTED IF EXAMPLE +# ============================================ + +print("=" * 50) +print("BASIC NESTED IF") +print("=" * 50 + "\n") + +age = 25 +has_ticket = True + +if age >= 18: + print("You are an adult.") + if has_ticket: + print("You can enter the movie theater! 🎬") + else: + print("Please buy a ticket first.") +else: + print("You are under 18.") + if has_ticket: + print("You need parental guidance to enter.") + else: + print("You need a ticket and parental guidance.") + + +# ============================================ +# SCHOOL GRADING SYSTEM WITH ATTENDANCE +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: ADVANCED GRADING SYSTEM") +print("=" * 50 + "\n") + +marks = 85 +attendance = 82 + +print(f"Marks: {marks}") +print(f"Attendance: {attendance}%\n") + +# First check attendance +if attendance >= 75: + print("✓ Attendance requirement met") + + # Then check marks + if marks >= 90: + grade = "A+" + print(f"Grade: {grade} - Outstanding!") + elif marks >= 80: + grade = "A" + print(f"Grade: {grade} - Excellent!") + elif marks >= 70: + grade = "B" + print(f"Grade: {grade} - Very Good!") + elif marks >= 60: + grade = "C" + print(f"Grade: {grade} - Good") + elif marks >= 50: + grade = "D" + print(f"Grade: {grade} - Pass") + else: + grade = "F" + print(f"Grade: {grade} - Fail") +else: + print("✗ Attendance requirement NOT met") + print(f"You need at least 75% attendance, you have {attendance}%") + print("Result: DETAINED (Cannot appear in exam)") + + +# ============================================ +# LOAN ELIGIBILITY CHECKER +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 2: LOAN ELIGIBILITY CHECKER") +print("=" * 50 + "\n") + +age = 30 +monthly_income = 50000 +credit_score = 750 +has_existing_loan = False + +print(f"Age: {age}") +print(f"Monthly Income: ${monthly_income}") +print(f"Credit Score: {credit_score}") +print(f"Has Existing Loan: {has_existing_loan}\n") + +# Check age eligibility +if age >= 21 and age <= 60: + print("✓ Age requirement met") + + # Check income + if monthly_income >= 30000: + print("✓ Income requirement met") + + # Check credit score + if credit_score >= 700: + print("✓ Credit score is good") + + # Check existing loans + if not has_existing_loan: + print("✓ No existing loans\n") + print("🎉 LOAN APPROVED!") + print("You can borrow up to $500,000") + else: + print("⚠ You have an existing loan\n") + print("LOAN APPROVED with conditions") + print("You can borrow up to $200,000") + else: + print(f"✗ Credit score too low (need 700+, you have {credit_score})\n") + print("LOAN REJECTED") + else: + print(f"✗ Income too low (need $30,000+, you have ${monthly_income})\n") + print("LOAN REJECTED") +else: + print(f"✗ Age must be between 21 and 60 (you are {age})\n") + print("LOAN REJECTED") + + +# ============================================ +# SHIPPING COST CALCULATOR +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 3: SHIPPING COST CALCULATOR") +print("=" * 50 + "\n") + +weight = 5 # in kg +distance = 150 # in km +is_express = False +is_fragile = True + +print(f"Package Weight: {weight} kg") +print(f"Distance: {distance} km") +print(f"Express Delivery: {is_express}") +print(f"Fragile Item: {is_fragile}\n") + +# Calculate base cost by weight +if weight <= 1: + base_cost = 50 +elif weight <= 5: + base_cost = 100 +elif weight <= 10: + base_cost = 200 +else: + base_cost = 300 + +print(f"Base cost: ${base_cost}") + +# Add distance charges +if distance > 100: + distance_charge = 50 + print(f"Distance charge: ${distance_charge}") +else: + distance_charge = 0 + print(f"Distance charge: ${distance_charge}") + +# Calculate total +total_cost = base_cost + distance_charge + +# Add express charges +if is_express: + express_charge = total_cost * 0.5 # 50% extra + print(f"Express delivery charge (50%): ${express_charge}") + total_cost += express_charge + +# Add fragile handling charges +if is_fragile: + fragile_charge = 25 + print(f"Fragile handling charge: ${fragile_charge}") + total_cost += fragile_charge + +print(f"\nTOTAL SHIPPING COST: ${total_cost}") + + +# ============================================ +# STUDENT SCHOLARSHIP PROGRAM +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 4: SCHOLARSHIP ELIGIBILITY") +print("=" * 50 + "\n") + +percentage = 92 +family_income = 25000 +sports_achievement = True +extra_curricular = True + +print(f"Percentage: {percentage}%") +print(f"Family Income: ${family_income}") +print(f"Sports Achievement: {sports_achievement}") +print(f"Extra-Curricular Activities: {extra_curricular}\n") + +scholarship_amount = 0 + +# Check academic performance +if percentage >= 90: + print("✓ Excellent Academic Performance") + scholarship_amount = 5000 + + # Check family income + if family_income < 50000: + print("✓ Low family income - Additional support") + scholarship_amount += 3000 + + # Check sports + if sports_achievement: + print("✓ Sports Achievement Bonus") + scholarship_amount += 2000 + + # Check extra-curricular + if extra_curricular: + print("✓ Extra-Curricular Bonus") + scholarship_amount += 1000 + +elif percentage >= 80: + print("✓ Good Academic Performance") + scholarship_amount = 3000 + + if family_income < 50000: + print("✓ Low family income - Additional support") + scholarship_amount += 2000 + +elif percentage >= 70: + print("✓ Average Academic Performance") + scholarship_amount = 1000 + +else: + print("✗ Does not meet academic requirements") + +print(f"\nTOTAL SCHOLARSHIP AMOUNT: ${scholarship_amount}") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Create a water bill calculator: + - First 100 units: $0.50 per unit + - Next 100 units: $0.75 per unit + - Above 200 units: $1.00 per unit + - If bill > $150, add 10% tax + - If bill > $200, add additional 5% surcharge + +2. Write a college admission system that checks: + - Entrance exam score (must be >= 70) + - If qualified, check marks: + * >= 90: Direct admission + $2000 scholarship + * >= 80: Direct admission + $1000 scholarship + * >= 70: Admission with interview + - If not qualified, suggest improvement areas + +3. Create a movie ticket booking system: + - Check age for appropriate content rating + - Check day (weekday/weekend for different prices) + - Check showtime (matinee/evening/night) + - Apply member discount if applicable + - Calculate final price with all factors + +4. Design a temperature alert system: + - If temp > 35: Heat warning + * If temp > 40: Severe heat warning + * If temp > 45: Extreme heat danger + - If temp < 10: Cold warning + * If temp < 5: Severe cold warning + * If temp < 0: Freezing danger + - Else: Normal temperature + +5. Build a restaurant bill calculator: + - Different tax rates for dine-in (10%) and takeaway (5%) + - Service charge (10%) only for dine-in + - If bill > $100, give 10% discount + - If customer is a member, give additional 5% discount +""" + +print("\nTry solving the practice problems above!") +print("Nested conditions help solve complex real-world problems!") diff --git a/03_Loops/01_for_loops.py b/03_Loops/01_for_loops.py new file mode 100644 index 0000000..5b9082e --- /dev/null +++ b/03_Loops/01_for_loops.py @@ -0,0 +1,313 @@ +""" +FOR LOOPS IN PYTHON +=================== + +A for loop is used to iterate over a sequence (like a list, string, or range). +It repeats a block of code for each item in the sequence. + +Basic Structure: + for variable in sequence: + # code to repeat +""" + +# ============================================ +# BASIC FOR LOOP WITH RANGE +# ============================================ + +print("=" * 50) +print("BASIC FOR LOOP") +print("=" * 50 + "\n") + +# Print numbers from 1 to 5 +print("Numbers from 1 to 5:") +for i in range(1, 6): # range(start, stop) - stop is not included + print(i) + +print() + +# Print numbers from 0 to 4 +print("Numbers from 0 to 4:") +for i in range(5): # range(stop) starts from 0 + print(i) + + +# ============================================ +# FOR LOOP WITH STEP +# ============================================ + +print("\n" + "=" * 50) +print("FOR LOOP WITH STEP") +print("=" * 50 + "\n") + +# Print even numbers from 2 to 10 +print("Even numbers from 2 to 10:") +for i in range(2, 11, 2): # range(start, stop, step) + print(i) + +print() + +# Count down from 10 to 1 +print("Countdown from 10 to 1:") +for i in range(10, 0, -1): # negative step for counting down + print(i) +print("Blast off! 🚀") + + +# ============================================ +# FOR LOOP WITH LISTS +# ============================================ + +print("\n" + "=" * 50) +print("FOR LOOP WITH LISTS") +print("=" * 50 + "\n") + +# Loop through a list of fruits +fruits = ["apple", "banana", "orange", "mango", "grape"] + +print("My favorite fruits:") +for fruit in fruits: + print(f"- {fruit}") + +print() + +# Loop through a list of numbers +scores = [85, 92, 78, 90, 88] + +print("Student scores:") +for score in scores: + print(f"Score: {score}") + + +# ============================================ +# FOR LOOP WITH STRINGS +# ============================================ + +print("\n" + "=" * 50) +print("FOR LOOP WITH STRINGS") +print("=" * 50 + "\n") + +# Loop through each character in a string +word = "Python" + +print(f"Letters in '{word}':") +for letter in word: + print(letter) + + +# ============================================ +# FOR LOOP WITH CALCULATIONS +# ============================================ + +print("\n" + "=" * 50) +print("CALCULATIONS WITH FOR LOOPS") +print("=" * 50 + "\n") + +# Sum of numbers from 1 to 10 +total = 0 +for i in range(1, 11): + total += i # Add each number to total +print(f"Sum of numbers from 1 to 10: {total}") + +print() + +# Calculate factorial +number = 5 +factorial = 1 +for i in range(1, number + 1): + factorial *= i +print(f"Factorial of {number}: {factorial}") + +print() + +# Calculate average of scores +scores = [85, 90, 78, 92, 88] +total = 0 +for score in scores: + total += score +average = total / len(scores) +print(f"Scores: {scores}") +print(f"Average score: {average}") + + +# ============================================ +# NESTED FOR LOOPS +# ============================================ + +print("\n" + "=" * 50) +print("NESTED FOR LOOPS") +print("=" * 50 + "\n") + +# Print a pattern +print("Pattern 1:") +for i in range(1, 6): + for j in range(i): + print("*", end=" ") + print() # New line after each row + +print() + +# Multiplication table +print("Multiplication Table (1-5):") +for i in range(1, 6): + for j in range(1, 6): + print(f"{i}×{j}={i*j:2d}", end=" ") + print() # New line after each row + + +# ============================================ +# FOR LOOP WITH ENUMERATE +# ============================================ + +print("\n" + "=" * 50) +print("FOR LOOP WITH ENUMERATE") +print("=" * 50 + "\n") + +# enumerate gives you both index and value +subjects = ["Math", "Science", "English", "History"] + +print("My subjects:") +for index, subject in enumerate(subjects, start=1): + print(f"{index}. {subject}") + + +# ============================================ +# PRACTICAL PROGRAMS +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: GRADE CALCULATOR") +print("=" * 50 + "\n") + +students = ["Alice", "Bob", "Charlie", "Diana", "Eve"] +marks = [85, 92, 78, 88, 95] + +print("STUDENT REPORT CARD") +print("-" * 50) + +for i in range(len(students)): + name = students[i] + mark = marks[i] + + if mark >= 90: + grade = "A+" + elif mark >= 80: + grade = "A" + elif mark >= 70: + grade = "B" + else: + grade = "C" + + print(f"{name:12} | Marks: {mark:3d} | Grade: {grade}") + + +print("\n" + "=" * 50) +print("PROGRAM 2: FIND MAXIMUM AND MINIMUM") +print("=" * 50 + "\n") + +numbers = [45, 78, 23, 91, 34, 67, 89] + +print(f"Numbers: {numbers}") + +# Find maximum +maximum = numbers[0] +for num in numbers: + if num > maximum: + maximum = num + +# Find minimum +minimum = numbers[0] +for num in numbers: + if num < minimum: + minimum = num + +print(f"Maximum: {maximum}") +print(f"Minimum: {minimum}") + + +print("\n" + "=" * 50) +print("PROGRAM 3: SIMPLE MENU SYSTEM") +print("=" * 50 + "\n") + +menu_items = ["Pizza", "Burger", "Pasta", "Salad", "Ice Cream"] +prices = [12.99, 8.99, 10.99, 6.99, 4.99] + +print("RESTAURANT MENU") +print("-" * 50) + +for i in range(len(menu_items)): + print(f"{i+1}. {menu_items[i]:15} ${prices[i]:.2f}") + + +print("\n" + "=" * 50) +print("PROGRAM 4: COUNT VOWELS") +print("=" * 50 + "\n") + +sentence = "Python is amazing" +vowels = "aeiouAEIOU" +vowel_count = 0 + +print(f"Sentence: {sentence}") + +for char in sentence: + if char in vowels: + vowel_count += 1 + +print(f"Number of vowels: {vowel_count}") + + +print("\n" + "=" * 50) +print("PROGRAM 5: MULTIPLICATION TABLE") +print("=" * 50 + "\n") + +number = 7 + +print(f"Multiplication Table of {number}") +print("-" * 30) + +for i in range(1, 11): + result = number * i + print(f"{number} × {i:2d} = {result:3d}") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a program that prints all even numbers from 1 to 50. + +2. Create a program that finds the sum of all odd numbers from 1 to 100. + +3. Write a program that reverses a string using a for loop. + Example: "hello" should become "olleh" + +4. Create a program that counts how many times each vowel appears in a sentence. + +5. Write a program that prints the Fibonacci sequence up to 10 terms. + (0, 1, 1, 2, 3, 5, 8, 13, 21, 34...) + +6. Create a program that checks if a number is prime using a for loop. + +7. Write a program that creates a list of squares of numbers from 1 to 10. + +8. Create a program that finds all numbers divisible by 3 and 5 between 1 and 100. + +9. Write a program that prints the following pattern: + 1 + 1 2 + 1 2 3 + 1 2 3 4 + 1 2 3 4 5 + +10. Create a program that calculates compound interest for different years: + Principal = $1000, Rate = 5%, Years = 1 to 10 +""" + +print("\nTry solving the practice problems above!") +print("The more you practice loops, the better you'll become!") diff --git a/03_Loops/02_while_loops.py b/03_Loops/02_while_loops.py new file mode 100644 index 0000000..d013da6 --- /dev/null +++ b/03_Loops/02_while_loops.py @@ -0,0 +1,370 @@ +""" +WHILE LOOPS IN PYTHON +===================== + +A while loop repeats a block of code as long as a condition is True. +It's useful when you don't know in advance how many times to loop. + +Basic Structure: + while condition: + # code to repeat + # update condition to eventually become False +""" + +# ============================================ +# BASIC WHILE LOOP +# ============================================ + +print("=" * 50) +print("BASIC WHILE LOOP") +print("=" * 50 + "\n") + +# Count from 1 to 5 +count = 1 +print("Counting from 1 to 5:") +while count <= 5: + print(count) + count += 1 # Important: update the variable! + +print() + +# Count down from 5 to 1 +count = 5 +print("Counting down from 5 to 1:") +while count > 0: + print(count) + count -= 1 +print("Done!") + + +# ============================================ +# WHILE LOOP WITH USER INPUT +# ============================================ + +print("\n" + "=" * 50) +print("WHILE LOOP WITH INPUT VALIDATION") +print("=" * 50 + "\n") + +# Keep asking until valid input (simulated) +attempts = 0 +max_attempts = 3 +password = "" + +print("Password must be at least 6 characters") +while attempts < max_attempts and len(password) < 6: + password = "abc" # Simulated input + attempts += 1 + + if len(password) < 6: + print(f"Attempt {attempts}: Password too short! Try again.") + else: + print(f"Attempt {attempts}: Password accepted!") + break + +if len(password) < 6: + print("Maximum attempts reached!") + + +# ============================================ +# WHILE LOOP WITH CALCULATIONS +# ============================================ + +print("\n" + "=" * 50) +print("CALCULATIONS WITH WHILE LOOPS") +print("=" * 50 + "\n") + +# Sum of numbers from 1 to 10 +number = 1 +total = 0 + +while number <= 10: + total += number + number += 1 + +print(f"Sum of numbers from 1 to 10: {total}") + +print() + +# Calculate factorial using while loop +n = 5 +factorial = 1 +i = 1 + +while i <= n: + factorial *= i + i += 1 + +print(f"Factorial of {n}: {factorial}") + + +# ============================================ +# BREAK AND CONTINUE +# ============================================ + +print("\n" + "=" * 50) +print("BREAK AND CONTINUE STATEMENTS") +print("=" * 50 + "\n") + +# BREAK - exits the loop immediately +print("Using BREAK:") +count = 1 +while count <= 10: + if count == 6: + print("Breaking at 6!") + break + print(count) + count += 1 + +print() + +# CONTINUE - skips current iteration, continues with next +print("Using CONTINUE:") +count = 0 +while count < 10: + count += 1 + if count % 2 == 0: # Skip even numbers + continue + print(count) + + +# ============================================ +# INFINITE LOOP WITH BREAK +# ============================================ + +print("\n" + "=" * 50) +print("INFINITE LOOP WITH BREAK") +print("=" * 50 + "\n") + +# Menu system (simulated) +print("Simple Calculator") +choice = 0 + +while True: # Infinite loop + choice += 1 + + if choice == 1: + print(f"Choice {choice}: Addition selected") + elif choice == 2: + print(f"Choice {choice}: Subtraction selected") + elif choice == 3: + print(f"Choice {choice}: Exit selected") + print("Thank you for using the calculator!") + break # Exit the infinite loop + + if choice > 2: # Safety break for simulation + break + + +# ============================================ +# NESTED WHILE LOOPS +# ============================================ + +print("\n" + "=" * 50) +print("NESTED WHILE LOOPS") +print("=" * 50 + "\n") + +# Print a pattern +print("Pattern using nested while loops:") +i = 1 +while i <= 5: + j = 1 + while j <= i: + print("*", end=" ") + j += 1 + print() + i += 1 + + +# ============================================ +# PRACTICAL PROGRAMS +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: NUMBER GUESSING GAME") +print("=" * 50 + "\n") + +secret_number = 7 +guess = 0 +attempts = 0 +max_attempts = 5 + +print(f"Guess the number between 1 and 10!") +print(f"You have {max_attempts} attempts.\n") + +while attempts < max_attempts and guess != secret_number: + attempts += 1 + # Simulated guesses + if attempts == 1: + guess = 5 + elif attempts == 2: + guess = 8 + elif attempts == 3: + guess = 7 + + print(f"Attempt {attempts}: Guessed {guess}") + + if guess == secret_number: + print(f"🎉 Congratulations! You guessed it in {attempts} attempts!") + elif guess < secret_number: + print("Too low! Try a higher number.") + else: + print("Too high! Try a lower number.") + +if guess != secret_number: + print(f"\nGame Over! The secret number was {secret_number}") + + +print("\n" + "=" * 50) +print("PROGRAM 2: SUM OF DIGITS") +print("=" * 50 + "\n") + +number = 12345 +sum_digits = 0 +temp = number + +print(f"Number: {number}") + +while temp > 0: + digit = temp % 10 # Get last digit + sum_digits += digit + temp = temp // 10 # Remove last digit + +print(f"Sum of digits: {sum_digits}") + + +print("\n" + "=" * 50) +print("PROGRAM 3: REVERSE A NUMBER") +print("=" * 50 + "\n") + +number = 12345 +reversed_number = 0 +temp = number + +while temp > 0: + digit = temp % 10 + reversed_number = reversed_number * 10 + digit + temp = temp // 10 + +print(f"Original number: {number}") +print(f"Reversed number: {reversed_number}") + + +print("\n" + "=" * 50) +print("PROGRAM 4: COMPOUND INTEREST CALCULATOR") +print("=" * 50 + "\n") + +principal = 1000 +rate = 5 # 5% per year +years = 0 +target = 2000 + +print(f"Initial amount: ${principal}") +print(f"Interest rate: {rate}%") +print(f"Target amount: ${target}\n") + +amount = principal +while amount < target: + years += 1 + interest = amount * (rate / 100) + amount += interest + print(f"Year {years}: ${amount:.2f}") + +print(f"\nIt takes {years} years to reach ${target}") + + +print("\n" + "=" * 50) +print("PROGRAM 5: COUNTDOWN TIMER") +print("=" * 50 + "\n") + +seconds = 10 +print(f"Countdown from {seconds} seconds:") + +while seconds > 0: + print(f"{seconds}...") + seconds -= 1 + +print("Time's up! ⏰") + + +print("\n" + "=" * 50) +print("PROGRAM 6: FIND GCD (GREATEST COMMON DIVISOR)") +print("=" * 50 + "\n") + +# Using Euclidean algorithm +num1 = 48 +num2 = 18 + +print(f"Finding GCD of {num1} and {num2}\n") + +a = num1 +b = num2 + +while b != 0: + temp = b + b = a % b + a = temp + print(f"a = {a}, b = {b}") + +print(f"\nGCD of {num1} and {num2} is: {a}") + + +# ============================================ +# FOR vs WHILE - When to Use Which? +# ============================================ + +print("\n" + "=" * 50) +print("FOR vs WHILE LOOPS") +print("=" * 50 + "\n") + +print("Use FOR loop when:") +print("- You know how many times to loop") +print("- You're iterating over a sequence (list, string, range)") +print("- Example: Print numbers 1 to 10") + +print("\nUse WHILE loop when:") +print("- You don't know how many times to loop in advance") +print("- You loop until a condition becomes False") +print("- Example: Keep asking for input until valid") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a program that prints all numbers from 1 to 100 that are divisible by 7. + +2. Create a program that finds the sum of all even numbers from 1 to 50. + +3. Write a program to check if a number is a palindrome (reads same forwards and backwards). + Example: 121, 12321 are palindromes + +4. Create a program that finds the factorial of a number using a while loop. + +5. Write a program that finds all prime numbers between 1 and 50. + +6. Create a program that converts a decimal number to binary using a while loop. + +7. Write a program that implements a simple ATM system: + - Display menu (Check Balance, Withdraw, Deposit, Exit) + - Keep running until user selects Exit + - Validate withdrawal amount + +8. Create a program that finds the nth Fibonacci number using a while loop. + +9. Write a program that keeps asking for numbers and calculates their sum. + Stop when the user enters 0. + +10. Create a program that simulates a dice rolling game: + - Roll until you get a 6 + - Count how many rolls it took +""" + +print("\nTry solving the practice problems above!") +print("While loops are powerful for handling uncertain iterations!") diff --git a/04_Functions/01_functions_basics.py b/04_Functions/01_functions_basics.py new file mode 100644 index 0000000..f4bc346 --- /dev/null +++ b/04_Functions/01_functions_basics.py @@ -0,0 +1,414 @@ +""" +FUNCTIONS IN PYTHON +=================== + +Functions are reusable blocks of code that perform specific tasks. +They help organize code, avoid repetition, and make programs easier to read. + +Basic Structure: + def function_name(parameters): + # code to execute + return result # optional +""" + +# ============================================ +# SIMPLE FUNCTIONS +# ============================================ + +print("=" * 50) +print("SIMPLE FUNCTIONS") +print("=" * 50 + "\n") + +# Function without parameters +def greet(): + """Prints a greeting message""" + print("Hello! Welcome to Python!") + +# Call the function +greet() + +print() + +# Function with a simple task +def print_line(): + """Prints a decorative line""" + print("-" * 40) + +print_line() +print("This is between lines") +print_line() + + +# ============================================ +# FUNCTIONS WITH PARAMETERS +# ============================================ + +print("\n" + "=" * 50) +print("FUNCTIONS WITH PARAMETERS") +print("=" * 50 + "\n") + +# Function with one parameter +def greet_person(name): + """Greets a person by name""" + print(f"Hello, {name}! Welcome!") + +greet_person("Alice") +greet_person("Bob") + +print() + +# Function with multiple parameters +def introduce(name, age, city): + """Introduces a person with details""" + print(f"My name is {name}.") + print(f"I am {age} years old.") + print(f"I live in {city}.") + +print("Introduction 1:") +introduce("Sarah", 22, "New York") + +print("\nIntroduction 2:") +introduce("John", 25, "London") + + +# ============================================ +# FUNCTIONS WITH RETURN VALUES +# ============================================ + +print("\n" + "=" * 50) +print("FUNCTIONS WITH RETURN VALUES") +print("=" * 50 + "\n") + +# Function that returns a value +def add_numbers(a, b): + """Adds two numbers and returns the result""" + result = a + b + return result + +# Use the returned value +sum1 = add_numbers(5, 3) +sum2 = add_numbers(10, 20) + +print(f"5 + 3 = {sum1}") +print(f"10 + 20 = {sum2}") + +print() + +# Function with calculation +def calculate_area(length, width): + """Calculates area of a rectangle""" + area = length * width + return area + +rectangle_area = calculate_area(10, 5) +print(f"Area of rectangle (10 × 5): {rectangle_area}") + + +# ============================================ +# FUNCTIONS WITH DEFAULT PARAMETERS +# ============================================ + +print("\n" + "=" * 50) +print("FUNCTIONS WITH DEFAULT PARAMETERS") +print("=" * 50 + "\n") + +def greet_with_message(name, message="Good morning"): + """Greets with a custom or default message""" + print(f"{message}, {name}!") + +# Using default parameter +greet_with_message("Alice") + +# Overriding default parameter +greet_with_message("Bob", "Good evening") + +print() + +def calculate_power(base, exponent=2): + """Calculates power with default exponent 2 (square)""" + return base ** exponent + +print(f"5 squared: {calculate_power(5)}") +print(f"2 to the power 3: {calculate_power(2, 3)}") + + +# ============================================ +# FUNCTIONS WITH MULTIPLE RETURN VALUES +# ============================================ + +print("\n" + "=" * 50) +print("FUNCTIONS WITH MULTIPLE RETURN VALUES") +print("=" * 50 + "\n") + +def calculate_rectangle(length, width): + """Calculates both area and perimeter""" + area = length * width + perimeter = 2 * (length + width) + return area, perimeter + +# Unpack multiple return values +rect_area, rect_perimeter = calculate_rectangle(10, 5) +print(f"Rectangle (10 × 5):") +print(f"Area: {rect_area}") +print(f"Perimeter: {rect_perimeter}") + +print() + +def get_student_info(): + """Returns student information""" + name = "Emma" + grade = "A" + score = 92 + return name, grade, score + +student_name, student_grade, student_score = get_student_info() +print(f"Student: {student_name}") +print(f"Grade: {student_grade}") +print(f"Score: {student_score}") + + +# ============================================ +# PRACTICAL FUNCTION EXAMPLES +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICAL FUNCTION EXAMPLES") +print("=" * 50 + "\n") + +# Example 1: Check if number is even +def is_even(number): + """Returns True if number is even, False otherwise""" + return number % 2 == 0 + +print("Is 10 even?", is_even(10)) +print("Is 7 even?", is_even(7)) + +print() + +# Example 2: Find maximum of three numbers +def find_max(a, b, c): + """Returns the maximum of three numbers""" + if a >= b and a >= c: + return a + elif b >= a and b >= c: + return b + else: + return c + +print(f"Maximum of 5, 12, 8: {find_max(5, 12, 8)}") +print(f"Maximum of 20, 15, 25: {find_max(20, 15, 25)}") + +print() + +# Example 3: Calculate discount +def calculate_discount(price, discount_percent): + """Calculates final price after discount""" + discount_amount = price * (discount_percent / 100) + final_price = price - discount_amount + return final_price + +original_price = 100 +discount = 20 +final = calculate_discount(original_price, discount) +print(f"Original price: ${original_price}") +print(f"Discount: {discount}%") +print(f"Final price: ${final}") + + +# ============================================ +# PROGRAM 1: TEMPERATURE CONVERTER +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: TEMPERATURE CONVERTER") +print("=" * 50 + "\n") + +def celsius_to_fahrenheit(celsius): + """Converts Celsius to Fahrenheit""" + fahrenheit = (celsius * 9/5) + 32 + return fahrenheit + +def fahrenheit_to_celsius(fahrenheit): + """Converts Fahrenheit to Celsius""" + celsius = (fahrenheit - 32) * 5/9 + return celsius + +# Test the functions +temp_c = 25 +temp_f = celsius_to_fahrenheit(temp_c) +print(f"{temp_c}°C = {temp_f}°F") + +temp_f2 = 77 +temp_c2 = fahrenheit_to_celsius(temp_f2) +print(f"{temp_f2}°F = {temp_c2:.1f}°C") + + +# ============================================ +# PROGRAM 2: GRADE CALCULATOR +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 2: GRADE CALCULATOR") +print("=" * 50 + "\n") + +def calculate_grade(score): + """Returns grade based on score""" + if score >= 90: + return "A+" + elif score >= 80: + return "A" + elif score >= 70: + return "B" + elif score >= 60: + return "C" + elif score >= 50: + return "D" + else: + return "F" + +def calculate_average(scores): + """Calculates average of a list of scores""" + total = sum(scores) + average = total / len(scores) + return average + +# Test the functions +student_scores = [85, 92, 78, 88, 95] +avg = calculate_average(student_scores) +grade = calculate_grade(avg) + +print(f"Scores: {student_scores}") +print(f"Average: {avg:.2f}") +print(f"Grade: {grade}") + + +# ============================================ +# PROGRAM 3: SIMPLE CALCULATOR +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 3: SIMPLE CALCULATOR") +print("=" * 50 + "\n") + +def add(a, b): + """Returns sum of two numbers""" + return a + b + +def subtract(a, b): + """Returns difference of two numbers""" + return a - b + +def multiply(a, b): + """Returns product of two numbers""" + return a * b + +def divide(a, b): + """Returns quotient of two numbers""" + if b != 0: + return a / b + else: + return "Error: Cannot divide by zero" + +# Use the calculator functions +num1 = 20 +num2 = 5 + +print(f"{num1} + {num2} = {add(num1, num2)}") +print(f"{num1} - {num2} = {subtract(num1, num2)}") +print(f"{num1} × {num2} = {multiply(num1, num2)}") +print(f"{num1} ÷ {num2} = {divide(num1, num2)}") + + +# ============================================ +# PROGRAM 4: PASSWORD VALIDATOR +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 4: PASSWORD VALIDATOR") +print("=" * 50 + "\n") + +def is_strong_password(password): + """Checks if password is strong""" + # Check length + if len(password) < 8: + return False, "Password must be at least 8 characters" + + # Check for digit + has_digit = False + for char in password: + if char.isdigit(): + has_digit = True + break + + if not has_digit: + return False, "Password must contain at least one number" + + # Check for uppercase + has_upper = False + for char in password: + if char.isupper(): + has_upper = True + break + + if not has_upper: + return False, "Password must contain at least one uppercase letter" + + return True, "Password is strong!" + +# Test passwords +test_passwords = ["weak", "Better123", "StrongPass1"] + +for pwd in test_passwords: + is_valid, message = is_strong_password(pwd) + print(f"Password: '{pwd}'") + print(f"Valid: {is_valid} - {message}\n") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a function that checks if a number is prime. + Return True if prime, False otherwise. + +2. Create a function that reverses a string. + Example: reverse("hello") should return "olleh" + +3. Write a function that finds factorial of a number. + +4. Create a function that checks if a string is a palindrome. + (reads same forwards and backwards) + +5. Write a function that calculates simple interest. + Formula: (Principal × Rate × Time) / 100 + +6. Create a function that converts hours to seconds. + +7. Write a function that finds the sum of digits in a number. + Example: sum_digits(123) should return 6 + +8. Create a function that counts vowels in a string. + +9. Write a function that generates the Fibonacci sequence up to n terms. + Return the sequence as a list. + +10. Create a function that checks if a year is a leap year. + Return True if leap year, False otherwise. + +11. Write a function that calculates BMI (Body Mass Index). + BMI = weight(kg) / (height(m))² + Return BMI and category (Underweight/Normal/Overweight/Obese) + +12. Create a function that finds the largest and smallest number in a list. + Return both values. +""" + +print("\nTry solving the practice problems above!") +print("Functions make your code organized and reusable!") diff --git a/05_File_Handling/01_file_operations.py b/05_File_Handling/01_file_operations.py new file mode 100644 index 0000000..1746b6a --- /dev/null +++ b/05_File_Handling/01_file_operations.py @@ -0,0 +1,369 @@ +""" +FILE HANDLING IN PYTHON +======================== + +File handling allows you to work with files - read, write, and manipulate them. +Python makes file operations easy and straightforward. + +Common File Operations: +1. Opening a file +2. Reading from a file +3. Writing to a file +4. Appending to a file +5. Closing a file + +File Modes: +- 'r' : Read mode (default) - Opens file for reading +- 'w' : Write mode - Creates new file or overwrites existing +- 'a' : Append mode - Adds to the end of file +- 'r+': Read and Write mode +""" + +import os + +# ============================================ +# WRITING TO A FILE +# ============================================ + +print("=" * 50) +print("WRITING TO A FILE") +print("=" * 50 + "\n") + +# Create and write to a file +print("Creating a new file and writing to it...") + +file = open("sample.txt", "w") # Open in write mode +file.write("Hello, Python!\n") +file.write("This is a sample file.\n") +file.write("Learning file handling is fun!\n") +file.close() # Always close the file + +print("✓ File 'sample.txt' created and written successfully!") + + +# ============================================ +# READING FROM A FILE +# ============================================ + +print("\n" + "=" * 50) +print("READING FROM A FILE") +print("=" * 50 + "\n") + +# Read entire file +print("Reading the entire file:") +file = open("sample.txt", "r") # Open in read mode +content = file.read() # Read all content +print(content) +file.close() + +print("-" * 50) + +# Read line by line +print("Reading line by line:") +file = open("sample.txt", "r") +lines = file.readlines() # Read all lines into a list +for line in lines: + print(line.strip()) # strip() removes extra newline +file.close() + + +# ============================================ +# USING 'WITH' STATEMENT (RECOMMENDED) +# ============================================ + +print("\n" + "=" * 50) +print("USING 'WITH' STATEMENT") +print("=" * 50 + "\n") + +print("'with' automatically closes the file - safer and cleaner!\n") + +# Writing with 'with' statement +with open("students.txt", "w") as file: + file.write("Student List\n") + file.write("=" * 30 + "\n") + file.write("1. Alice - Grade A\n") + file.write("2. Bob - Grade B\n") + file.write("3. Charlie - Grade A\n") + +print("✓ File 'students.txt' created!") + +# Reading with 'with' statement +print("\nReading 'students.txt':") +with open("students.txt", "r") as file: + content = file.read() + print(content) + + +# ============================================ +# APPENDING TO A FILE +# ============================================ + +print("=" * 50) +print("APPENDING TO A FILE") +print("=" * 50 + "\n") + +# Append adds to the end without deleting existing content +print("Appending new students to the file...") + +with open("students.txt", "a") as file: + file.write("4. Diana - Grade A+\n") + file.write("5. Eve - Grade B+\n") + +print("✓ New students added!") + +print("\nReading updated file:") +with open("students.txt", "r") as file: + print(file.read()) + + +# ============================================ +# READING FILE LINE BY LINE +# ============================================ + +print("=" * 50) +print("READING LINE BY LINE") +print("=" * 50 + "\n") + +print("Processing each line:") +with open("students.txt", "r") as file: + line_number = 1 + for line in file: + print(f"Line {line_number}: {line.strip()}") + line_number += 1 + + +# ============================================ +# CHECKING IF FILE EXISTS +# ============================================ + +print("\n" + "=" * 50) +print("CHECKING IF FILE EXISTS") +print("=" * 50 + "\n") + +if os.path.exists("students.txt"): + print("✓ File 'students.txt' exists!") +else: + print("✗ File 'students.txt' does not exist!") + +if os.path.exists("nonexistent.txt"): + print("✓ File 'nonexistent.txt' exists!") +else: + print("✗ File 'nonexistent.txt' does not exist!") + + +# ============================================ +# PROGRAM 1: SAVE STUDENT RECORDS +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 1: STUDENT RECORDS SYSTEM") +print("=" * 50 + "\n") + +def save_student_record(filename, name, roll_no, grade): + """Saves student record to a file""" + with open(filename, "a") as file: + file.write(f"{roll_no},{name},{grade}\n") + print(f"✓ Record saved: {name} (Roll: {roll_no}, Grade: {grade})") + +def read_student_records(filename): + """Reads and displays all student records""" + if not os.path.exists(filename): + print("No records found!") + return + + print("\nSTUDENT RECORDS:") + print("-" * 50) + print(f"{'Roll No':<10} {'Name':<20} {'Grade':<10}") + print("-" * 50) + + with open(filename, "r") as file: + for line in file: + parts = line.strip().split(",") + if len(parts) == 3: + roll, name, grade = parts + print(f"{roll:<10} {name:<20} {grade:<10}") + +# Save some student records +save_student_record("records.txt", "Alice Johnson", "101", "A") +save_student_record("records.txt", "Bob Smith", "102", "B+") +save_student_record("records.txt", "Charlie Brown", "103", "A-") + +# Read and display records +read_student_records("records.txt") + + +# ============================================ +# PROGRAM 2: WORD COUNTER +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 2: WORD COUNTER") +print("=" * 50 + "\n") + +def count_words_in_file(filename): + """Counts words, lines, and characters in a file""" + if not os.path.exists(filename): + print(f"File '{filename}' not found!") + return + + with open(filename, "r") as file: + content = file.read() + lines = content.split("\n") + words = content.split() + + print(f"File: {filename}") + print(f"Lines: {len(lines)}") + print(f"Words: {len(words)}") + print(f"Characters: {len(content)}") + +# Create a sample file for counting +with open("essay.txt", "w") as file: + file.write("Python is a powerful programming language.\n") + file.write("It is easy to learn and widely used.\n") + file.write("Many companies use Python for development.\n") + +count_words_in_file("essay.txt") + + +# ============================================ +# PROGRAM 3: TO-DO LIST +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 3: TO-DO LIST MANAGER") +print("=" * 50 + "\n") + +def add_task(task): + """Adds a task to todo list""" + with open("todo.txt", "a") as file: + file.write(f"[ ] {task}\n") + print(f"✓ Task added: {task}") + +def show_tasks(): + """Displays all tasks""" + if not os.path.exists("todo.txt"): + print("No tasks yet!") + return + + print("\nYOUR TO-DO LIST:") + print("-" * 50) + with open("todo.txt", "r") as file: + tasks = file.readlines() + if not tasks: + print("No tasks yet!") + else: + for i, task in enumerate(tasks, 1): + print(f"{i}. {task.strip()}") + +# Add some tasks +add_task("Learn Python file handling") +add_task("Practice coding exercises") +add_task("Build a small project") + +# Show all tasks +show_tasks() + + +# ============================================ +# PROGRAM 4: SIMPLE DATABASE +# ============================================ + +print("\n" + "=" * 50) +print("PROGRAM 4: SIMPLE CONTACT DATABASE") +print("=" * 50 + "\n") + +def add_contact(name, phone, email): + """Adds a contact to the database""" + with open("contacts.txt", "a") as file: + file.write(f"{name}|{phone}|{email}\n") + print(f"✓ Contact added: {name}") + +def search_contact(name): + """Searches for a contact by name""" + if not os.path.exists("contacts.txt"): + print("No contacts found!") + return + + found = False + with open("contacts.txt", "r") as file: + for line in file: + parts = line.strip().split("|") + if len(parts) == 3 and parts[0].lower() == name.lower(): + print(f"\nContact Found:") + print(f"Name: {parts[0]}") + print(f"Phone: {parts[1]}") + print(f"Email: {parts[2]}") + found = True + break + + if not found: + print(f"Contact '{name}' not found!") + +# Add contacts +add_contact("Alice", "123-456-7890", "alice@email.com") +add_contact("Bob", "098-765-4321", "bob@email.com") + +# Search for a contact +search_contact("Alice") +search_contact("Charlie") + + +# ============================================ +# CLEANUP (Delete sample files) +# ============================================ + +print("\n" + "=" * 50) +print("CLEANING UP SAMPLE FILES") +print("=" * 50 + "\n") + +sample_files = ["sample.txt", "students.txt", "records.txt", "essay.txt", "todo.txt", "contacts.txt"] + +for filename in sample_files: + if os.path.exists(filename): + os.remove(filename) + print(f"✓ Deleted: {filename}") + + +# ============================================ +# PRACTICE PROBLEMS +# ============================================ + +print("\n" + "=" * 50) +print("PRACTICE PROBLEMS") +print("=" * 50) + +""" +Try these exercises: + +1. Write a program that creates a file and writes your favorite quotes to it. + Then read and display them. + +2. Create a program that reads a file and counts how many times each vowel appears. + +3. Write a program that copies the content of one file to another file. + +4. Create a simple diary application that appends daily entries with timestamps. + +5. Write a program that reads a file containing numbers (one per line) and + calculates their sum and average. + +6. Create a grade book system that: + - Saves student names and marks + - Reads and displays all records + - Calculates class average + +7. Write a program that finds and replaces a word in a file. + +8. Create a program that reads a file and counts the frequency of each word. + +9. Write a program that merges two text files into a third file. + +10. Create a simple inventory management system using file handling: + - Add items (name, quantity, price) + - Display all items + - Update item quantity + - Calculate total inventory value +""" + +print("\nTry solving the practice problems above!") +print("File handling is essential for saving and managing data!") diff --git a/06_Mini_Projects/01_calculator.py b/06_Mini_Projects/01_calculator.py new file mode 100644 index 0000000..24197c3 --- /dev/null +++ b/06_Mini_Projects/01_calculator.py @@ -0,0 +1,182 @@ +""" +MINI PROJECT 1: SIMPLE CALCULATOR +================================== + +A calculator that can perform basic arithmetic operations. +This project uses functions to organize code better. +""" + +def add(x, y): + """Addition""" + return x + y + +def subtract(x, y): + """Subtraction""" + return x - y + +def multiply(x, y): + """Multiplication""" + return x * y + +def divide(x, y): + """Division""" + if y == 0: + return "Error! Division by zero." + return x / y + +def display_menu(): + """Display calculator menu""" + print("\n" + "=" * 50) + print("SIMPLE CALCULATOR") + print("=" * 50) + print("\nOperations:") + print("1. Addition (+)") + print("2. Subtraction (-)") + print("3. Multiplication (×)") + print("4. Division (÷)") + print("5. Exit") + print("=" * 50) + +def calculator(): + """Main calculator function""" + print("Welcome to Simple Calculator!") + + while True: + display_menu() + + choice = input("\nEnter your choice (1-5): ") + + # Exit condition + if choice == '5': + print("\nThank you for using the calculator!") + print("Goodbye! 👋") + break + + # Check if choice is valid + if choice not in ['1', '2', '3', '4']: + print("\n❌ Invalid choice! Please select 1-5.") + continue + + # Get numbers from user + try: + num1 = float(input("\nEnter first number: ")) + num2 = float(input("Enter second number: ")) + except ValueError: + print("\n❌ Invalid input! Please enter numbers only.") + continue + + # Perform calculation based on choice + if choice == '1': + result = add(num1, num2) + operation = "+" + elif choice == '2': + result = subtract(num1, num2) + operation = "-" + elif choice == '3': + result = multiply(num1, num2) + operation = "×" + elif choice == '4': + result = divide(num1, num2) + operation = "÷" + + # Display result + print("\n" + "-" * 50) + print(f"Result: {num1} {operation} {num2} = {result}") + print("-" * 50) + + # Ask if user wants to continue + continue_calc = input("\nDo you want to perform another calculation? (yes/no): ") + if continue_calc.lower() != 'yes': + print("\nThank you for using the calculator!") + print("Goodbye! 👋") + break + +# ============================================ +# DEMONSTRATION MODE +# ============================================ + +def demo_calculator(): + """Demonstrates calculator with sample calculations""" + print("\n" + "=" * 50) + print("CALCULATOR DEMONSTRATION") + print("=" * 50 + "\n") + + # Sample calculations + calculations = [ + (10, 5, "Addition", add, "+"), + (20, 8, "Subtraction", subtract, "-"), + (6, 7, "Multiplication", multiply, "×"), + (100, 4, "Division", divide, "÷"), + ] + + for num1, num2, operation_name, operation_func, symbol in calculations: + result = operation_func(num1, num2) + print(f"{operation_name}: {num1} {symbol} {num2} = {result}") + + # Test division by zero + print(f"\nDivision by zero test: {divide(10, 0)}") + +# Run demonstration +demo_calculator() + +# ============================================ +# HOW TO USE THIS PROGRAM +# ============================================ + +print("\n" + "=" * 50) +print("HOW TO USE") +print("=" * 50) +print(""" +To use the interactive calculator: + +1. Uncomment the line below (remove the #): + # calculator() + +2. Run the program again + +3. Follow the on-screen instructions: + - Choose an operation (1-5) + - Enter two numbers + - View the result + - Decide if you want to continue + +Features: +✓ Handles division by zero +✓ Input validation +✓ User-friendly interface +✓ Option to exit anytime +""") + +# Uncomment the line below to run the interactive calculator: +# calculator() + +print("\n" + "=" * 50) +print("ENHANCEMENT IDEAS") +print("=" * 50) +print(""" +Try adding these features: + +1. More operations: + - Square root + - Power (x^y) + - Modulus (remainder) + - Percentage + +2. Memory functions: + - Store last result + - Recall stored value + +3. History: + - Keep track of all calculations + - Display calculation history + +4. Advanced features: + - Calculate expression: "5 + 3 * 2" + - Scientific calculator functions + - Unit conversions + +5. Better interface: + - Clear screen between operations + - Colorful output + - Save results to file +""") diff --git a/06_Mini_Projects/02_number_guessing_game.py b/06_Mini_Projects/02_number_guessing_game.py new file mode 100644 index 0000000..78972a3 --- /dev/null +++ b/06_Mini_Projects/02_number_guessing_game.py @@ -0,0 +1,219 @@ +""" +MINI PROJECT 2: NUMBER GUESSING GAME +===================================== + +A fun game where the computer picks a random number and you have to guess it! +The game gives hints if your guess is too high or too low. +""" + +import random + +def play_game(): + """Main game function""" + print("\n" + "=" * 50) + print("🎮 WELCOME TO NUMBER GUESSING GAME! 🎮") + print("=" * 50) + print("\nI'm thinking of a number between 1 and 100.") + print("Can you guess what it is?") + print("=" * 50 + "\n") + + # Computer picks a random number + secret_number = random.randint(1, 100) + attempts = 0 + max_attempts = 10 + + print(f"You have {max_attempts} attempts to guess the number.\n") + + # Game loop + while attempts < max_attempts: + attempts += 1 + remaining = max_attempts - attempts + 1 + + # Get player's guess + try: + guess = int(input(f"Attempt {attempts}/{max_attempts} - Enter your guess: ")) + except ValueError: + print("❌ Invalid input! Please enter a number.\n") + attempts -= 1 # Don't count invalid attempts + continue + + # Check if guess is in valid range + if guess < 1 or guess > 100: + print("❌ Please guess a number between 1 and 100!\n") + attempts -= 1 # Don't count invalid attempts + continue + + # Check the guess + if guess == secret_number: + print("\n" + "=" * 50) + print("🎉 CONGRATULATIONS! YOU WON! 🎉") + print("=" * 50) + print(f"You guessed the number in {attempts} attempts!") + print(f"The secret number was: {secret_number}") + + # Calculate score based on attempts + score = ((max_attempts - attempts + 1) * 10) + print(f"Your score: {score} points") + print("=" * 50) + return True + + elif guess < secret_number: + print(f"📈 Too low! Try a higher number.") + if remaining > 0: + print(f"You have {remaining} attempts remaining.\n") + + else: + print(f"📉 Too high! Try a lower number.") + if remaining > 0: + print(f"You have {remaining} attempts remaining.\n") + + # Player ran out of attempts + print("\n" + "=" * 50) + print("😢 GAME OVER!") + print("=" * 50) + print(f"You've used all {max_attempts} attempts.") + print(f"The secret number was: {secret_number}") + print("Better luck next time!") + print("=" * 50) + return False + +def play_multiple_rounds(): + """Play multiple rounds and keep track of score""" + print("\n" + "🌟" * 25) + print("MULTI-ROUND NUMBER GUESSING GAME") + print("🌟" * 25 + "\n") + + total_wins = 0 + total_games = 0 + + while True: + total_games += 1 + won = play_game() + + if won: + total_wins += 1 + + # Ask if player wants to play again + print("\n" + "-" * 50) + play_again = input("Do you want to play again? (yes/no): ") + + if play_again.lower() not in ['yes', 'y']: + break + + # Display final statistics + print("\n" + "=" * 50) + print("GAME STATISTICS") + print("=" * 50) + print(f"Games Played: {total_games}") + print(f"Games Won: {total_wins}") + print(f"Games Lost: {total_games - total_wins}") + + if total_games > 0: + win_percentage = (total_wins / total_games) * 100 + print(f"Win Rate: {win_percentage:.1f}%") + + print("=" * 50) + print("\nThank you for playing! 👋") + +# ============================================ +# DEMONSTRATION MODE +# ============================================ + +def demo_game(): + """Demonstrates the game with automated guesses""" + print("\n" + "=" * 50) + print("GAME DEMONSTRATION (Automated)") + print("=" * 50 + "\n") + + secret_number = 47 # Fixed number for demo + print(f"Secret number: {secret_number}") + print("Watch the computer try to guess it!\n") + + # Simulate guesses + guesses = [50, 25, 37, 43, 45, 47] + + for i, guess in enumerate(guesses, 1): + print(f"Attempt {i}: Guessed {guess}") + + if guess == secret_number: + print(f"✓ Correct! Found it in {i} attempts!\n") + break + elif guess < secret_number: + print(f" → Too low! Try higher.\n") + else: + print(f" → Too high! Try lower.\n") + +# Run demonstration +demo_game() + +# ============================================ +# HOW TO PLAY +# ============================================ + +print("=" * 50) +print("HOW TO PLAY") +print("=" * 50) +print(""" +To play the game: + +1. Uncomment ONE of these lines: + # play_game() # Play single round + # play_multiple_rounds() # Play multiple rounds + +2. Run the program again + +3. Follow the instructions: + - Guess a number between 1 and 100 + - Get hints (too high or too low) + - Try to guess in as few attempts as possible! + +Scoring: +- Fewer attempts = Higher score +- Each remaining attempt is worth 10 points +""") + +# Uncomment one of these lines to play: +# play_game() # Single round +# play_multiple_rounds() # Multiple rounds with statistics + +# ============================================ +# ENHANCEMENT IDEAS +# ============================================ + +print("\n" + "=" * 50) +print("ENHANCEMENT IDEAS") +print("=" * 50) +print(""" +Try adding these features: + +1. Difficulty Levels: + - Easy: 1-50, 15 attempts + - Medium: 1-100, 10 attempts + - Hard: 1-200, 7 attempts + +2. Hints System: + - "Hot/Warm/Cold" based on proximity + - Reveal if number is even or odd + - Show range narrowing (e.g., "between 30-60") + +3. Time Challenge: + - Add timer for each guess + - Bonus points for quick guesses + +4. Two-Player Mode: + - Players take turns guessing + - First to guess wins + +5. Save High Scores: + - Keep track of best scores + - Save to a file + - Display leaderboard + +6. Advanced Features: + - Multiple number ranges + - Guess decimals + - Binary search hints + - Sound effects (using libraries) +""") + +print("\n🎮 Have fun coding and playing! 🎮\n") diff --git a/06_Mini_Projects/03_student_grade_manager.py b/06_Mini_Projects/03_student_grade_manager.py new file mode 100644 index 0000000..5bc8d8f --- /dev/null +++ b/06_Mini_Projects/03_student_grade_manager.py @@ -0,0 +1,326 @@ +""" +MINI PROJECT 3: STUDENT GRADE MANAGER +====================================== + +A simple system to manage student grades. +You can add students, view records, calculate averages, and more! +""" + +# Store students in a list of dictionaries +students = [] + +def display_menu(): + """Display main menu""" + print("\n" + "=" * 50) + print("📚 STUDENT GRADE MANAGER 📚") + print("=" * 50) + print("\n1. Add New Student") + print("2. View All Students") + print("3. Search Student") + print("4. Calculate Class Average") + print("5. Find Top Performer") + print("6. Display Grade Distribution") + print("7. Exit") + print("=" * 50) + +def add_student(): + """Add a new student""" + print("\n" + "-" * 50) + print("ADD NEW STUDENT") + print("-" * 50) + + name = input("Enter student name: ") + + try: + math = float(input("Enter Math score (0-100): ")) + science = float(input("Enter Science score (0-100): ")) + english = float(input("Enter English score (0-100): ")) + + # Validate scores + if not all(0 <= score <= 100 for score in [math, science, english]): + print("❌ Scores must be between 0 and 100!") + return + + # Calculate average and grade + average = (math + science + english) / 3 + grade = calculate_grade(average) + + # Create student record + student = { + 'name': name, + 'math': math, + 'science': science, + 'english': english, + 'average': average, + 'grade': grade + } + + students.append(student) + print(f"\n✓ Student '{name}' added successfully!") + print(f" Average: {average:.2f}, Grade: {grade}") + + except ValueError: + print("❌ Invalid input! Please enter numbers for scores.") + +def calculate_grade(average): + """Calculate letter grade from average""" + if average >= 90: + return "A+" + elif average >= 80: + return "A" + elif average >= 70: + return "B" + elif average >= 60: + return "C" + elif average >= 50: + return "D" + else: + return "F" + +def view_all_students(): + """Display all student records""" + if not students: + print("\n❌ No students in the system yet!") + return + + print("\n" + "=" * 80) + print("ALL STUDENT RECORDS") + print("=" * 80) + print(f"{'Name':<20} {'Math':<8} {'Science':<8} {'English':<8} {'Average':<10} {'Grade':<8}") + print("-" * 80) + + for student in students: + print(f"{student['name']:<20} {student['math']:<8.1f} {student['science']:<8.1f} " + f"{student['english']:<8.1f} {student['average']:<10.2f} {student['grade']:<8}") + + print("-" * 80) + print(f"Total Students: {len(students)}") + +def search_student(): + """Search for a student by name""" + if not students: + print("\n❌ No students in the system yet!") + return + + name = input("\nEnter student name to search: ") + + found = False + for student in students: + if student['name'].lower() == name.lower(): + print("\n" + "-" * 50) + print("STUDENT FOUND") + print("-" * 50) + print(f"Name: {student['name']}") + print(f"Math: {student['math']:.1f}") + print(f"Science: {student['science']:.1f}") + print(f"English: {student['english']:.1f}") + print(f"Average: {student['average']:.2f}") + print(f"Grade: {student['grade']}") + print("-" * 50) + found = True + break + + if not found: + print(f"\n❌ Student '{name}' not found!") + +def calculate_class_average(): + """Calculate and display class average""" + if not students: + print("\n❌ No students in the system yet!") + return + + total_avg = sum(student['average'] for student in students) + class_avg = total_avg / len(students) + + print("\n" + "-" * 50) + print("CLASS STATISTICS") + print("-" * 50) + print(f"Total Students: {len(students)}") + print(f"Class Average: {class_avg:.2f}") + print(f"Class Grade: {calculate_grade(class_avg)}") + print("-" * 50) + +def find_top_performer(): + """Find and display the top performing student""" + if not students: + print("\n❌ No students in the system yet!") + return + + top_student = max(students, key=lambda x: x['average']) + + print("\n" + "-" * 50) + print("🏆 TOP PERFORMER 🏆") + print("-" * 50) + print(f"Name: {top_student['name']}") + print(f"Average: {top_student['average']:.2f}") + print(f"Grade: {top_student['grade']}") + print("-" * 50) + +def display_grade_distribution(): + """Show distribution of grades""" + if not students: + print("\n❌ No students in the system yet!") + return + + # Count each grade + grade_count = {} + for student in students: + grade = student['grade'] + grade_count[grade] = grade_count.get(grade, 0) + 1 + + print("\n" + "-" * 50) + print("GRADE DISTRIBUTION") + print("-" * 50) + + for grade in ['A+', 'A', 'B', 'C', 'D', 'F']: + count = grade_count.get(grade, 0) + percentage = (count / len(students)) * 100 if students else 0 + bar = "█" * count + print(f"{grade:<5} : {bar} ({count} students - {percentage:.1f}%)") + + print("-" * 50) + +def main(): + """Main program function""" + print("\n🎓 Welcome to Student Grade Manager! 🎓") + + while True: + display_menu() + + choice = input("\nEnter your choice (1-7): ") + + if choice == '1': + add_student() + elif choice == '2': + view_all_students() + elif choice == '3': + search_student() + elif choice == '4': + calculate_class_average() + elif choice == '5': + find_top_performer() + elif choice == '6': + display_grade_distribution() + elif choice == '7': + print("\n" + "=" * 50) + print("Thank you for using Student Grade Manager!") + print("Goodbye! 👋") + print("=" * 50 + "\n") + break + else: + print("\n❌ Invalid choice! Please select 1-7.") + + input("\nPress Enter to continue...") + +# ============================================ +# DEMONSTRATION MODE +# ============================================ + +def demo(): + """Demonstrate the system with sample data""" + print("\n" + "=" * 50) + print("DEMONSTRATION MODE") + print("=" * 50 + "\n") + + # Add sample students + sample_students = [ + {'name': 'Alice Johnson', 'math': 92, 'science': 88, 'english': 90}, + {'name': 'Bob Smith', 'math': 78, 'science': 82, 'english': 75}, + {'name': 'Charlie Brown', 'math': 95, 'science': 93, 'english': 91}, + {'name': 'Diana Prince', 'math': 85, 'science': 87, 'english': 89}, + {'name': 'Eve Wilson', 'math': 72, 'science': 70, 'english': 74}, + ] + + print("Adding sample students...\n") + for student_data in sample_students: + average = (student_data['math'] + student_data['science'] + student_data['english']) / 3 + grade = calculate_grade(average) + + student = { + 'name': student_data['name'], + 'math': student_data['math'], + 'science': student_data['science'], + 'english': student_data['english'], + 'average': average, + 'grade': grade + } + + students.append(student) + print(f"✓ Added: {student['name']}") + + # Show various features + view_all_students() + calculate_class_average() + find_top_performer() + display_grade_distribution() + +# Run demonstration +demo() + +# ============================================ +# HOW TO USE +# ============================================ + +print("\n" + "=" * 50) +print("HOW TO USE") +print("=" * 50) +print(""" +To use the interactive system: + +1. Uncomment the line below (remove the #): + # main() + +2. Run the program again + +3. Follow the menu options: + - Add students with their scores + - View all records + - Search for specific students + - See statistics and analytics + +Note: Currently showing demonstration with sample data. +""") + +# Uncomment the line below to run the interactive program: +# main() + +# ============================================ +# ENHANCEMENT IDEAS +# ============================================ + +print("\n" + "=" * 50) +print("ENHANCEMENT IDEAS") +print("=" * 50) +print(""" +Try adding these features: + +1. More Features: + - Edit student records + - Delete student records + - Add more subjects + - Calculate subject-wise averages + +2. File Operations: + - Save data to a file + - Load data from a file + - Export to CSV format + - Import from CSV + +3. Advanced Analytics: + - Median and mode calculations + - Standard deviation + - Subject-wise rankings + - Progress tracking over time + +4. Better Interface: + - Colored output + - Sorting options (by name, grade, etc.) + - Filter students by grade + - Generate report cards + +5. Validations: + - Prevent duplicate student names + - Confirm before deleting + - Undo last operation + - Data backup +""") diff --git a/README.md b/README.md index 7677c98..ccfeb65 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,116 @@ -# Python -This repository is created for learning Python programming, covering basics, practice problems, and simple examples. +# 🐍 Python Learning Repository + +Welcome to the **Python Learning Repository**! This is a beginner-friendly guide designed to help you learn Python programming from scratch. Whether you're a student, self-learner, or someone starting their coding journey, this repository is perfect for you! + +## 📖 What is Python? + +Python is a powerful, easy-to-learn programming language that's perfect for beginners. It's used in: +- Web Development +- Data Science and Machine Learning +- Automation +- Game Development +- And much more! + +Python's simple and readable syntax makes it one of the most popular programming languages in the world. + +## 🎯 Purpose of This Repository + +This repository is created for: +- **Learning Python** from the ground up +- **Practicing** programming concepts with hands-on examples +- **College assignments** and coursework +- **Building** a strong foundation in programming +- **Improving** coding skills through practice problems + +## 📚 Topics Covered + +This repository is organized into easy-to-follow sections: + +1. **Basics** - Variables, data types, operators, input/output +2. **Conditions** - If-else statements, conditional logic +3. **Loops** - For loops, while loops, loop control +4. **Functions** - Creating and using functions, parameters, return values +5. **File Handling** - Reading and writing files +6. **Mini Projects** - Small programs to practice your skills + +## 🚀 How to Run Python Files + +### Step 1: Install Python +- Download Python from [python.org](https://www.python.org/downloads/) +- Make sure to check "Add Python to PATH" during installation + +### Step 2: Verify Installation +Open your terminal or command prompt and type: +```bash +python --version +``` +or +```bash +python3 --version +``` + +### Step 3: Run a Python File +Navigate to the folder containing the Python file and run: +```bash +python filename.py +``` +or +```bash +python3 filename.py +``` + +## 🔧 Python Version + +This repository uses **Python 3.x** (Python 3.6 or higher recommended) + +## 👥 Who Is This For? + +This repository is perfect for: +- **Complete Beginners** who have never coded before +- **Students** learning Python in school or college +- **Self-Learners** who want to teach themselves programming +- **Anyone** who wants to practice Python basics + +## 📂 Repository Structure + +``` +Python/ +│ +├── 01_Basics/ # Fundamental Python concepts +├── 02_Conditions/ # If-else and conditional statements +├── 03_Loops/ # For loops and while loops +├── 04_Functions/ # Functions and code reusability +├── 05_File_Handling/ # Working with files +└── 06_Mini_Projects/ # Small practice projects +``` + +## 💡 How to Use This Repository + +1. **Start with Basics** - Begin with the `01_Basics` folder +2. **Read the Code** - Each file has comments explaining what the code does +3. **Run the Programs** - Try running each program yourself +4. **Modify the Code** - Experiment by changing values and logic +5. **Practice Problems** - Solve the practice problems included in the files +6. **Build Projects** - Once comfortable, try the mini projects + +## 🌟 Tips for Learning + +- **Practice Daily** - Even 30 minutes a day makes a big difference +- **Type the Code** - Don't just read, type it out yourself +- **Make Mistakes** - Errors are part of learning, don't be afraid! +- **Experiment** - Try changing the code to see what happens +- **Ask Questions** - If stuck, search online or ask for help + +## 📝 Contributing + +This is a learning repository. Feel free to add your own examples or improvements! + +## 📧 Contact + +If you have questions or suggestions, feel free to open an issue or reach out! + +--- + +**Happy Coding! 🎉** + +Start your Python journey today and remember: Every expert was once a beginner!