diff --git a/01_Variables_and_Data_Types/01_basic_variables.py b/01_Variables_and_Data_Types/01_basic_variables.py new file mode 100644 index 0000000..a67d83d --- /dev/null +++ b/01_Variables_and_Data_Types/01_basic_variables.py @@ -0,0 +1,47 @@ +""" +Basic Variables in Python +========================== +This program demonstrates how to create and use variables in Python. +Variables are containers for storing data values. +""" + +# Creating variables with different data types +name = "Alice" # String variable +age = 20 # Integer variable +height = 5.6 # Float variable +is_student = True # Boolean variable + +# Printing variables +print("=== Student Information ===") +print("Name:", name) +print("Age:", age) +print("Height:", height, "feet") +print("Is Student:", is_student) + +# You can change variable values +print("\n=== After one year ===") +age = age + 1 # Increasing age by 1 +print("Age:", age) + +# Multiple variables in one line +x, y, z = 10, 20, 30 +print("\n=== Multiple Variables ===") +print("x =", x) +print("y =", y) +print("z =", z) + +# Same value to multiple variables +a = b = c = 100 +print("\n=== Same Value to Multiple Variables ===") +print("a =", a) +print("b =", b) +print("c =", c) + +# Variable naming rules demonstration +student_name = "Bob" # Good: descriptive and uses snake_case +_private_var = 42 # Good: starts with underscore (convention for private) +# 2nd_student = "Charlie" # Bad: cannot start with number (commented out) + +print("\n=== Variable Naming ===") +print("Student Name:", student_name) +print("Private Variable:", _private_var) diff --git a/01_Variables_and_Data_Types/02_numbers.py b/01_Variables_and_Data_Types/02_numbers.py new file mode 100644 index 0000000..4201d4b --- /dev/null +++ b/01_Variables_and_Data_Types/02_numbers.py @@ -0,0 +1,56 @@ +""" +Working with Numbers in Python +=============================== +This program demonstrates integer and float operations. +""" + +# Integer examples +num1 = 10 +num2 = 3 + +print("=== Integer Operations ===") +print("Number 1:", num1) +print("Number 2:", num2) +print("Addition:", num1 + num2) +print("Subtraction:", num1 - num2) +print("Multiplication:", num1 * num2) +print("Division:", num1 / num2) # Returns float +print("Floor Division:", num1 // num2) # Returns integer (rounds down) +print("Modulus (Remainder):", num1 % num2) +print("Power:", num1 ** num2) # 10 to the power of 3 + +# Float examples +price1 = 19.99 +price2 = 5.50 + +print("\n=== Float Operations ===") +print("Price 1: $", price1) +print("Price 2: $", price2) +print("Total Price: $", price1 + price2) +print("Average Price: $", (price1 + price2) / 2) + +# Mixed operations (int and float) +quantity = 5 # Integer +price_per_item = 12.50 # Float +total = quantity * price_per_item + +print("\n=== Shopping Bill ===") +print("Quantity:", quantity) +print("Price per item: $", price_per_item) +print("Total amount: $", total) + +# Useful number functions +number = -42.7 + +print("\n=== Number Functions ===") +print("Original number:", number) +print("Absolute value:", abs(number)) # Removes negative sign +print("Rounded value:", round(number)) # Rounds to nearest integer +print("Rounded to 1 decimal:", round(number, 1)) + +# Finding max and min +a, b, c = 15, 28, 9 +print("\n=== Max and Min ===") +print("Numbers:", a, b, c) +print("Maximum:", max(a, b, c)) +print("Minimum:", min(a, b, c)) diff --git a/01_Variables_and_Data_Types/03_strings.py b/01_Variables_and_Data_Types/03_strings.py new file mode 100644 index 0000000..147350c --- /dev/null +++ b/01_Variables_and_Data_Types/03_strings.py @@ -0,0 +1,85 @@ +""" +Working with Strings in Python +=============================== +This program demonstrates string operations and methods. +""" + +# Creating strings +name = "Alice" +message = 'Hello World' +multiline = """This is a +multi-line +string""" + +print("=== Basic Strings ===") +print("Name:", name) +print("Message:", message) +print("Multiline String:") +print(multiline) + +# String concatenation (joining) +first_name = "John" +last_name = "Doe" +full_name = first_name + " " + last_name + +print("\n=== String Concatenation ===") +print("First Name:", first_name) +print("Last Name:", last_name) +print("Full Name:", full_name) + +# String repetition +laugh = "ha" +print("\n=== String Repetition ===") +print("Laugh:", laugh * 5) # Prints "hahahahaha" + +# String length +sentence = "Python is fun" +print("\n=== String Length ===") +print("Sentence:", sentence) +print("Length:", len(sentence)) + +# Accessing characters (indexing) +word = "Python" +print("\n=== String Indexing ===") +print("Word:", word) +print("First character:", word[0]) # P +print("Second character:", word[1]) # y +print("Last character:", word[-1]) # n +print("Second last:", word[-2]) # o + +# String slicing +text = "Hello World" +print("\n=== String Slicing ===") +print("Original text:", text) +print("First 5 characters:", text[0:5]) # Hello +print("From index 6 to end:", text[6:]) # World +print("Last 5 characters:", text[-5:]) # World + +# Useful string methods +sample = " python programming " +print("\n=== String Methods ===") +print("Original:", "[" + sample + "]") +print("Uppercase:", sample.upper()) +print("Lowercase:", sample.lower()) +print("Capitalized:", sample.capitalize()) +print("Stripped (remove spaces):", "[" + sample.strip() + "]") +print("Replace:", sample.replace("python", "Python")) + +# Checking string content +email = "student@example.com" +print("\n=== String Checks ===") +print("Email:", email) +print("Contains '@':", "@" in email) +print("Starts with 'student':", email.startswith("student")) +print("Ends with '.com':", email.endswith(".com")) + +# String formatting +name = "Alice" +age = 20 +print("\n=== String Formatting ===") +# Method 1: f-strings (recommended) +print(f"My name is {name} and I am {age} years old.") +# Method 2: format() method +print("My name is {} and I am {} years old.".format(name, age)) +# Method 3: % operator (old style) +print("My name is %s and I am %d years old." % (name, age)) diff --git a/01_Variables_and_Data_Types/04_lists.py b/01_Variables_and_Data_Types/04_lists.py new file mode 100644 index 0000000..87bd414 --- /dev/null +++ b/01_Variables_and_Data_Types/04_lists.py @@ -0,0 +1,88 @@ +""" +Working with Lists in Python +============================= +This program demonstrates list operations and methods. +Lists are ordered, mutable collections that can contain different data types. +""" + +# Creating lists +fruits = ["apple", "banana", "orange"] +numbers = [1, 2, 3, 4, 5] +mixed = [1, "hello", 3.14, True] +empty_list = [] + +print("=== Creating Lists ===") +print("Fruits:", fruits) +print("Numbers:", numbers) +print("Mixed types:", mixed) +print("Empty list:", empty_list) + +# Accessing list elements +print("\n=== Accessing Elements ===") +print("First fruit:", fruits[0]) +print("Second fruit:", fruits[1]) +print("Last fruit:", fruits[-1]) + +# List length +print("\n=== List Length ===") +print("Number of fruits:", len(fruits)) + +# Adding elements to list +fruits.append("grape") # Add at the end +print("\n=== Adding Elements ===") +print("After append:", fruits) + +fruits.insert(1, "mango") # Insert at specific position +print("After insert at position 1:", fruits) + +# Removing elements from list +fruits.remove("banana") # Remove specific item +print("\n=== Removing Elements ===") +print("After removing banana:", fruits) + +last_fruit = fruits.pop() # Remove and return last item +print("Popped item:", last_fruit) +print("After pop:", fruits) + +# List slicing +numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +print("\n=== List Slicing ===") +print("Original list:", numbers) +print("First 5 elements:", numbers[0:5]) +print("Elements from index 5:", numbers[5:]) +print("Last 3 elements:", numbers[-3:]) +print("Every second element:", numbers[::2]) + +# List operations +list1 = [1, 2, 3] +list2 = [4, 5, 6] +print("\n=== List Operations ===") +print("List 1:", list1) +print("List 2:", list2) +print("Concatenation:", list1 + list2) +print("Repetition:", list1 * 3) + +# Useful list methods +numbers = [3, 1, 4, 1, 5, 9, 2, 6] +print("\n=== List Methods ===") +print("Original list:", numbers) +print("Count of 1:", numbers.count(1)) +print("Index of 4:", numbers.index(4)) + +numbers.sort() # Sort in ascending order +print("Sorted list:", numbers) + +numbers.reverse() # Reverse the list +print("Reversed list:", numbers) + +# Checking if item exists in list +shopping_list = ["milk", "bread", "eggs", "butter"] +print("\n=== Checking Items ===") +print("Shopping list:", shopping_list) +print("Is 'milk' in list?", "milk" in shopping_list) +print("Is 'cheese' in list?", "cheese" in shopping_list) + +# List comprehension (advanced but useful) +squares = [x**2 for x in range(1, 6)] +print("\n=== List Comprehension ===") +print("Squares of 1-5:", squares) diff --git a/01_Variables_and_Data_Types/05_tuples.py b/01_Variables_and_Data_Types/05_tuples.py new file mode 100644 index 0000000..4029ab0 --- /dev/null +++ b/01_Variables_and_Data_Types/05_tuples.py @@ -0,0 +1,96 @@ +""" +Working with Tuples in Python +============================== +This program demonstrates tuple operations. +Tuples are ordered, immutable collections (cannot be changed after creation). +""" + +# Creating tuples +coordinates = (10, 20) +rgb_color = (255, 0, 0) +mixed_tuple = (1, "hello", 3.14, True) +single_item = (42,) # Note: comma is required for single item +empty_tuple = () + +print("=== Creating Tuples ===") +print("Coordinates:", coordinates) +print("RGB Color:", rgb_color) +print("Mixed tuple:", mixed_tuple) +print("Single item tuple:", single_item) +print("Empty tuple:", empty_tuple) + +# Accessing tuple elements +point = (100, 200, 300) +print("\n=== Accessing Elements ===") +print("Point:", point) +print("X coordinate:", point[0]) +print("Y coordinate:", point[1]) +print("Z coordinate:", point[2]) +print("Last element:", point[-1]) + +# Tuple length +print("\n=== Tuple Length ===") +print("Length of point:", len(point)) + +# Tuple unpacking +x, y, z = point +print("\n=== Tuple Unpacking ===") +print("x =", x) +print("y =", y) +print("z =", z) + +# Why use tuples? They are immutable +print("\n=== Immutability Demo ===") +print("Original coordinates:", coordinates) +# coordinates[0] = 30 # This would cause an error! +print("Tuples cannot be changed after creation") + +# Tuple methods (only 2 methods since tuples are immutable) +numbers = (1, 2, 3, 2, 4, 2, 5) +print("\n=== Tuple Methods ===") +print("Numbers:", numbers) +print("Count of 2:", numbers.count(2)) +print("Index of 4:", numbers.index(4)) + +# Tuple operations +tuple1 = (1, 2, 3) +tuple2 = (4, 5, 6) +print("\n=== Tuple Operations ===") +print("Tuple 1:", tuple1) +print("Tuple 2:", tuple2) +print("Concatenation:", tuple1 + tuple2) +print("Repetition:", tuple1 * 3) + +# Converting between lists and tuples +my_list = [1, 2, 3, 4, 5] +my_tuple = tuple(my_list) +back_to_list = list(my_tuple) + +print("\n=== List and Tuple Conversion ===") +print("Original list:", my_list) +print("Converted to tuple:", my_tuple) +print("Back to list:", back_to_list) + +# Practical use case: returning multiple values from a function +def get_student_info(): + """Returns student information as a tuple""" + name = "Alice" + age = 20 + grade = "A" + return (name, age, grade) # Or just: return name, age, grade + +print("\n=== Practical Use Case ===") +student_data = get_student_info() +print("Student data (tuple):", student_data) + +# Unpacking the returned tuple +student_name, student_age, student_grade = get_student_info() +print(f"Name: {student_name}, Age: {student_age}, Grade: {student_grade}") + +# When to use tuples vs lists? +print("\n=== When to Use Tuples ===") +print("Use tuples when:") +print(" 1. Data should not change (coordinates, RGB values)") +print(" 2. Returning multiple values from a function") +print(" 3. Using as dictionary keys (lists can't be keys)") +print(" 4. Slightly faster than lists") diff --git a/01_Variables_and_Data_Types/06_dictionaries.py b/01_Variables_and_Data_Types/06_dictionaries.py new file mode 100644 index 0000000..2026a3b --- /dev/null +++ b/01_Variables_and_Data_Types/06_dictionaries.py @@ -0,0 +1,124 @@ +""" +Working with Dictionaries in Python +==================================== +This program demonstrates dictionary operations. +Dictionaries store data in key-value pairs. +""" + +# Creating dictionaries +student = { + "name": "Alice", + "age": 20, + "grade": "A", + "subjects": ["Math", "Science", "English"] +} + +empty_dict = {} + +print("=== Creating Dictionaries ===") +print("Student:", student) +print("Empty dictionary:", empty_dict) + +# Accessing values +print("\n=== Accessing Values ===") +print("Student name:", student["name"]) +print("Student age:", student["age"]) +print("Student subjects:", student["subjects"]) + +# Using get() method (safer - doesn't error if key doesn't exist) +print("\n=== Using get() Method ===") +print("Grade:", student.get("grade")) +print("City:", student.get("city", "Not specified")) # Default value + +# Adding and modifying entries +student["city"] = "New York" # Add new key-value pair +student["age"] = 21 # Modify existing value + +print("\n=== After Adding/Modifying ===") +print("Student:", student) + +# Removing entries +del student["city"] # Remove specific key +print("\n=== After Deleting City ===") +print("Student:", student) + +removed_grade = student.pop("grade") # Remove and return value +print("\n=== After Popping Grade ===") +print("Removed grade:", removed_grade) +print("Student:", student) + +# Dictionary methods +person = { + "name": "Bob", + "age": 25, + "job": "Engineer" +} + +print("\n=== Dictionary Methods ===") +print("All keys:", person.keys()) +print("All values:", person.values()) +print("All items:", person.items()) + +# Looping through dictionary +print("\n=== Looping Through Dictionary ===") +for key in person: + print(f"{key}: {person[key]}") + +print("\nUsing items():") +for key, value in person.items(): + print(f"{key}: {value}") + +# Checking if key exists +print("\n=== Checking Keys ===") +print("Is 'name' in dictionary?", "name" in person) +print("Is 'salary' in dictionary?", "salary" in person) + +# Nested dictionaries (dictionary inside dictionary) +classroom = { + "student1": {"name": "Alice", "grade": "A"}, + "student2": {"name": "Bob", "grade": "B"}, + "student3": {"name": "Charlie", "grade": "A"} +} + +print("\n=== Nested Dictionary ===") +print("Classroom:", classroom) +print("Student1 name:", classroom["student1"]["name"]) +print("Student2 grade:", classroom["student2"]["grade"]) + +# Dictionary comprehension +squares_dict = {x: x**2 for x in range(1, 6)} +print("\n=== Dictionary Comprehension ===") +print("Squares dictionary:", squares_dict) + +# Copying dictionaries +original = {"a": 1, "b": 2} +copied = original.copy() + +print("\n=== Copying Dictionary ===") +print("Original:", original) +print("Copied:", copied) + +# Merging dictionaries +dict1 = {"a": 1, "b": 2} +dict2 = {"c": 3, "d": 4} +merged = {**dict1, **dict2} # Python 3.5+ + +print("\n=== Merging Dictionaries ===") +print("Dictionary 1:", dict1) +print("Dictionary 2:", dict2) +print("Merged:", merged) + +# Practical example: Phone book +phone_book = { + "Alice": "555-1234", + "Bob": "555-5678", + "Charlie": "555-9012" +} + +print("\n=== Phone Book Example ===") +print("Alice's number:", phone_book["Alice"]) +print("All contacts:", phone_book) + +# Adding a new contact +phone_book["Diana"] = "555-3456" +print("After adding Diana:", phone_book) diff --git a/01_Variables_and_Data_Types/07_type_conversion.py b/01_Variables_and_Data_Types/07_type_conversion.py new file mode 100644 index 0000000..c3105e2 --- /dev/null +++ b/01_Variables_and_Data_Types/07_type_conversion.py @@ -0,0 +1,116 @@ +""" +Type Conversion in Python +========================== +This program demonstrates how to convert between different data types. +""" + +# Checking data types +name = "Alice" +age = 20 +height = 5.6 +is_student = True + +print("=== Checking Data Types ===") +print(f"name = {name}, type = {type(name)}") +print(f"age = {age}, type = {type(age)}") +print(f"height = {height}, type = {type(height)}") +print(f"is_student = {is_student}, type = {type(is_student)}") + +# Converting to integer +float_number = 3.14 +string_number = "42" + +print("\n=== Converting to Integer ===") +print(f"int(3.14) = {int(float_number)}") # Removes decimal part +print(f"int('42') = {int(string_number)}") # String to integer +print(f"int(True) = {int(True)}") # Boolean to integer +print(f"int(False) = {int(False)}") + +# Converting to float +integer_number = 10 +string_float = "3.14" + +print("\n=== Converting to Float ===") +print(f"float(10) = {float(integer_number)}") +print(f"float('3.14') = {float(string_float)}") +print(f"float(True) = {float(True)}") + +# Converting to string +number = 42 +pi = 3.14159 +flag = True + +print("\n=== Converting to String ===") +print(f"str(42) = '{str(number)}'") +print(f"str(3.14159) = '{str(pi)}'") +print(f"str(True) = '{str(flag)}'") + +# Converting to boolean +print("\n=== Converting to Boolean ===") +print(f"bool(1) = {bool(1)}") # Non-zero numbers are True +print(f"bool(0) = {bool(0)}") # Zero is False +print(f"bool('hello') = {bool('hello')}") # Non-empty strings are True +print(f"bool('') = {bool('')}") # Empty string is False +print(f"bool([1,2,3]) = {bool([1,2,3])}") # Non-empty list is True +print(f"bool([]) = {bool([])}") # Empty list is False + +# Converting between list, tuple, and set +my_list = [1, 2, 3, 4, 5] +my_tuple = (1, 2, 3, 4, 5) +my_set = {1, 2, 3, 4, 5} + +print("\n=== Converting Collections ===") +print("Original list:", my_list) +print("List to tuple:", tuple(my_list)) +print("List to set:", set(my_list)) + +print("\nOriginal tuple:", my_tuple) +print("Tuple to list:", list(my_tuple)) +print("Tuple to set:", set(my_tuple)) + +# Practical example: User input (always comes as string) +print("\n=== Practical Example: User Input ===") +print("User input always comes as a string!") +print("If you need a number, you must convert it.") + +# Example (without actual input for demo) +user_input_demo = "25" # Simulating input() +print(f"Input: '{user_input_demo}' (type: {type(user_input_demo)})") +age = int(user_input_demo) +print(f"Converted: {age} (type: {type(age)})") + +# Common mistakes and how to avoid them +print("\n=== Common Type Conversion Mistakes ===") + +# Mistake 1: Trying to convert invalid strings +try: + result = int("hello") +except ValueError as e: + print(f"Error: Can't convert 'hello' to int - {e}") + +# Mistake 2: Not considering decimal points +try: + result = int("3.14") +except ValueError as e: + print(f"Error: Can't convert '3.14' directly to int - {e}") + print("Solution: Convert to float first, then to int") + result = int(float("3.14")) + print(f"int(float('3.14')) = {result}") + +# Safe conversion with error handling +def safe_int_conversion(value): + """Safely convert a value to integer""" + try: + return int(value) + except ValueError: + print(f"Cannot convert '{value}' to integer!") + return None + +print("\n=== Safe Conversion Examples ===") +print(f"safe_int_conversion('42') = {safe_int_conversion('42')}") +print(f"safe_int_conversion('hello') = {safe_int_conversion('hello')}") + +# ASCII conversions +print("\n=== ASCII Conversions ===") +print(f"ord('A') = {ord('A')}") # Character to ASCII code +print(f"chr(65) = '{chr(65)}'") # ASCII code to character diff --git a/01_Variables_and_Data_Types/README.md b/01_Variables_and_Data_Types/README.md new file mode 100644 index 0000000..c195852 --- /dev/null +++ b/01_Variables_and_Data_Types/README.md @@ -0,0 +1,76 @@ +# Variables and Data Types πŸ“¦ + +## What are Variables? + +Variables are like containers that store data. Think of them as labeled boxes where you can keep different types of information. + +## Basic Data Types in Python + +### 1. **Integers (int)** +Whole numbers without decimal points +```python +age = 25 +year = 2024 +``` + +### 2. **Float** +Numbers with decimal points +```python +price = 19.99 +temperature = 36.5 +``` + +### 3. **String (str)** +Text data enclosed in quotes +```python +name = "Alice" +message = 'Hello World' +``` + +### 4. **Boolean (bool)** +True or False values +```python +is_student = True +has_passed = False +``` + +### 5. **List** +Ordered collection of items (mutable) +```python +fruits = ["apple", "banana", "orange"] +numbers = [1, 2, 3, 4, 5] +``` + +### 6. **Tuple** +Ordered collection of items (immutable) +```python +coordinates = (10, 20) +rgb_color = (255, 0, 0) +``` + +### 7. **Dictionary** +Key-value pairs +```python +student = {"name": "John", "age": 20, "grade": "A"} +``` + +## Examples in This Folder + +1. **01_basic_variables.py** - Introduction to variables +2. **02_numbers.py** - Working with integers and floats +3. **03_strings.py** - String operations and methods +4. **04_lists.py** - Creating and manipulating lists +5. **05_tuples.py** - Understanding tuples +6. **06_dictionaries.py** - Working with dictionaries +7. **07_type_conversion.py** - Converting between data types + +## Tips for Beginners + +- Variable names should be descriptive (e.g., `student_name` instead of `x`) +- Use lowercase with underscores for variable names (snake_case) +- Variables cannot start with numbers +- Python is case-sensitive (`Name` and `name` are different) + +## Practice + +Try running each example file and modify the values to see different results! diff --git a/02_Input_Output/01_basic_input_output.py b/02_Input_Output/01_basic_input_output.py new file mode 100644 index 0000000..f01516d --- /dev/null +++ b/02_Input_Output/01_basic_input_output.py @@ -0,0 +1,68 @@ +""" +Basic Input and Output in Python +================================= +This program demonstrates how to take input from users and display output. +""" + +# Simple output using print() +print("=== Basic Output ===") +print("Hello, World!") +print("Welcome to Python programming!") + +# Print multiple items +print("\n=== Multiple Items in Print ===") +print("My name is", "Alice", "and I am", 20, "years old") + +# Print with different separators +print("\n=== Custom Separator ===") +print("apple", "banana", "orange", sep=" | ") +print("2024", "01", "15", sep="-") + +# Print without newline (using end parameter) +print("\n=== Custom End Character ===") +print("Loading", end="...") +print("Done!") + +# Taking simple input +print("\n=== Taking User Input ===") +name = input("What is your name? ") +print("Hello,", name, "! Nice to meet you!") + +# Input comes as string by default +print("\n=== Input Type ===") +user_input = input("Enter something: ") +print("You entered:", user_input) +print("Type of input:", type(user_input)) + +# Creating interactive programs +print("\n=== Interactive Greeting Program ===") +user_name = input("Enter your name: ") +age = input("Enter your age: ") +city = input("Enter your city: ") + +print("\n--- Your Information ---") +print("Name:", user_name) +print("Age:", age) +print("City:", city) + +# Using input in strings +print("\n=== Using Input in Sentences ===") +favorite_color = input("What is your favorite color? ") +print("Wow!", favorite_color, "is a beautiful color!") + +# Multiple print statements vs single print +print("\n=== Different Print Styles ===") +# Style 1: Multiple prints +print("First line") +print("Second line") +print("Third line") + +# Style 2: Single print with \n (newline character) +print("\nFirst line\nSecond line\nThird line") + +# Printing special characters +print("\n=== Special Characters ===") +print("This is a tab:\tSee the space?") +print("This is a quote: \"Hello\"") +print("This is a backslash: \\") +print("This prints on\ntwo lines") diff --git a/02_Input_Output/02_formatted_output.py b/02_Input_Output/02_formatted_output.py new file mode 100644 index 0000000..74e7313 --- /dev/null +++ b/02_Input_Output/02_formatted_output.py @@ -0,0 +1,103 @@ +""" +Formatted Output in Python +=========================== +This program demonstrates different ways to format output for better presentation. +""" + +# Basic string formatting +name = "Alice" +age = 20 +grade = 85.5 + +print("=== Old Style Formatting (%) ===") +print("Name: %s, Age: %d, Grade: %.2f" % (name, age, grade)) + +print("\n=== Format Method ===") +print("Name: {}, Age: {}, Grade: {}".format(name, age, grade)) +print("Name: {0}, Age: {1}, Grade: {2}".format(name, age, grade)) +print("Grade: {2}, Name: {0}, Age: {1}".format(name, age, grade)) + +# F-strings (Python 3.6+) - Most recommended! +print("\n=== F-Strings (Recommended) ===") +print(f"Name: {name}, Age: {age}, Grade: {grade}") + +# Formatting numbers +pi = 3.14159265359 +large_number = 1234567890 + +print("\n=== Number Formatting ===") +print(f"Pi with 2 decimals: {pi:.2f}") +print(f"Pi with 4 decimals: {pi:.4f}") +print(f"Large number with commas: {large_number:,}") +print(f"Percentage: {0.856:.2%}") + +# Alignment and padding +print("\n=== Text Alignment ===") +print(f"{'Left':<10}|") # Left aligned (10 characters) +print(f"{'Right':>10}|") # Right aligned +print(f"{'Center':^10}|") # Center aligned + +# Creating tables +print("\n=== Creating a Simple Table ===") +print(f"{'Name':<15} {'Age':>5} {'Grade':>8}") +print("-" * 30) +print(f"{'Alice':<15} {20:>5} {85.5:>8.2f}") +print(f"{'Bob':<15} {22:>5} {90.0:>8.2f}") +print(f"{'Charlie':<15} {19:>5} {78.3:>8.2f}") + +# Expressions in f-strings +a = 10 +b = 20 + +print("\n=== Expressions in F-Strings ===") +print(f"a = {a}, b = {b}") +print(f"Sum: {a + b}") +print(f"Product: {a * b}") +print(f"Average: {(a + b) / 2}") + +# Multi-line formatted output +print("\n=== Receipt Example ===") +item1 = "Notebook" +price1 = 12.50 +quantity1 = 3 + +item2 = "Pen" +price2 = 2.25 +quantity2 = 5 + +print("=" * 40) +print(" " * 12 + "RECEIPT") +print("=" * 40) +print(f"{'Item':<20} {'Qty':>5} {'Price':>10}") +print("-" * 40) +print(f"{item1:<20} {quantity1:>5} ${price1 * quantity1:>9.2f}") +print(f"{item2:<20} {quantity2:>5} ${price2 * quantity2:>9.2f}") +print("-" * 40) +total = (price1 * quantity1) + (price2 * quantity2) +print(f"{'TOTAL:':<20} {' ':>5} ${total:>9.2f}") +print("=" * 40) + +# Conditional formatting +score = 85 +status = "Pass" if score >= 50 else "Fail" + +print("\n=== Conditional Formatting ===") +print(f"Score: {score}, Status: {status}") +print(f"Grade: {'A' if score >= 90 else 'B' if score >= 80 else 'C'}") + +# Pretty printing lists and dictionaries +student = {"name": "Alice", "age": 20, "grade": "A"} +subjects = ["Math", "Science", "English"] + +print("\n=== Formatting Collections ===") +print(f"Student info: {student}") +print(f"Subjects: {subjects}") +print(f"Subjects as string: {', '.join(subjects)}") + +# Progress bar example (visual formatting) +print("\n=== Progress Bar Example ===") +progress = 75 +bar_length = 20 +filled = int(bar_length * progress / 100) +bar = "β–ˆ" * filled + "-" * (bar_length - filled) +print(f"Progress: [{bar}] {progress}%") diff --git a/02_Input_Output/03_number_input.py b/02_Input_Output/03_number_input.py new file mode 100644 index 0000000..745de20 --- /dev/null +++ b/02_Input_Output/03_number_input.py @@ -0,0 +1,106 @@ +""" +Taking Numeric Input in Python +=============================== +This program demonstrates how to take and use numeric input from users. +Remember: input() always returns a string, so we need to convert it! +""" + +# Taking integer input +print("=== Taking Integer Input ===") +age = input("Enter your age: ") +print(f"You entered: {age} (type: {type(age)})") + +# Convert string to integer +age = int(age) +print(f"After conversion: {age} (type: {type(age)})") + +# Now we can do math with it +next_year_age = age + 1 +print(f"Next year you will be {next_year_age} years old") + +# Taking float input +print("\n=== Taking Float Input ===") +height = float(input("Enter your height in feet: ")) +print(f"Your height is {height} feet") +height_in_inches = height * 12 +print(f"That's {height_in_inches} inches!") + +# Simple calculator +print("\n=== Simple Calculator ===") +num1 = float(input("Enter first number: ")) +num2 = float(input("Enter second number: ")) + +print(f"\nResults:") +print(f"{num1} + {num2} = {num1 + num2}") +print(f"{num1} - {num2} = {num1 - num2}") +print(f"{num1} * {num2} = {num1 * num2}") +print(f"{num1} / {num2} = {num1 / num2}") + +# Taking input and doing calculations +print("\n=== Rectangle Area Calculator ===") +length = float(input("Enter length of rectangle: ")) +width = float(input("Enter width of rectangle: ")) +area = length * width +perimeter = 2 * (length + width) + +print(f"\nRectangle Properties:") +print(f"Length: {length}") +print(f"Width: {width}") +print(f"Area: {area}") +print(f"Perimeter: {perimeter}") + +# Temperature converter +print("\n=== Temperature Converter (Celsius to Fahrenheit) ===") +celsius = float(input("Enter temperature in Celsius: ")) +fahrenheit = (celsius * 9/5) + 32 +print(f"{celsius}Β°C is equal to {fahrenheit}Β°F") + +# Taking input with error handling +print("\n=== Safe Number Input ===") +try: + number = int(input("Enter a whole number: ")) + print(f"You entered: {number}") + print(f"Double of your number: {number * 2}") +except ValueError: + print("Error: Please enter a valid whole number!") + +# Shopping bill calculator +print("\n=== Shopping Bill Calculator ===") +item_name = input("Enter item name: ") +price = float(input("Enter price per item: $")) +quantity = int(input("Enter quantity: ")) + +total = price * quantity +tax = total * 0.1 # 10% tax +final_total = total + tax + +print(f"\n--- Bill ---") +print(f"Item: {item_name}") +print(f"Price: ${price:.2f}") +print(f"Quantity: {quantity}") +print(f"Subtotal: ${total:.2f}") +print(f"Tax (10%): ${tax:.2f}") +print(f"Total: ${final_total:.2f}") + +# Age calculator +print("\n=== Age Calculator ===") +current_year = 2024 +birth_year = int(input("Enter your birth year: ")) +age = current_year - birth_year +print(f"You are approximately {age} years old") + +# BMI Calculator +print("\n=== BMI Calculator ===") +weight = float(input("Enter your weight in kg: ")) +height_m = float(input("Enter your height in meters: ")) +bmi = weight / (height_m ** 2) + +print(f"\nYour BMI: {bmi:.2f}") +if bmi < 18.5: + print("Category: Underweight") +elif bmi < 25: + print("Category: Normal weight") +elif bmi < 30: + print("Category: Overweight") +else: + print("Category: Obese") diff --git a/02_Input_Output/04_multiple_inputs.py b/02_Input_Output/04_multiple_inputs.py new file mode 100644 index 0000000..222bc83 --- /dev/null +++ b/02_Input_Output/04_multiple_inputs.py @@ -0,0 +1,137 @@ +""" +Taking Multiple Inputs in Python +================================= +This program demonstrates different ways to take multiple inputs from users. +""" + +# Taking multiple inputs one by one +print("=== Multiple Inputs One by One ===") +first_name = input("Enter your first name: ") +last_name = input("Enter your last name: ") +age = int(input("Enter your age: ")) + +print(f"\nHello, {first_name} {last_name}!") +print(f"You are {age} years old.") + +# Taking multiple inputs in one line (space-separated) +print("\n=== Multiple Inputs in One Line ===") +print("Enter three numbers separated by spaces:") +numbers = input().split() # Returns a list of strings +print("You entered:", numbers) + +# Convert to integers +num1, num2, num3 = int(numbers[0]), int(numbers[1]), int(numbers[2]) +print(f"Sum: {num1 + num2 + num3}") + +# Better way: using map() +print("\n=== Using map() for Conversion ===") +print("Enter three numbers separated by spaces:") +a, b, c = map(int, input().split()) +print(f"Numbers: {a}, {b}, {c}") +print(f"Average: {(a + b + c) / 3}") + +# Taking multiple floats +print("\n=== Multiple Float Inputs ===") +print("Enter three decimal numbers separated by spaces:") +x, y, z = map(float, input().split()) +print(f"Numbers: {x}, {y}, {z}") +print(f"Maximum: {max(x, y, z)}") +print(f"Minimum: {min(x, y, z)}") + +# Student information collection +print("\n=== Student Information Form ===") +name = input("Enter student name: ") +roll_number = int(input("Enter roll number: ")) +marks1 = float(input("Enter marks in Subject 1: ")) +marks2 = float(input("Enter marks in Subject 2: ")) +marks3 = float(input("Enter marks in Subject 3: ")) + +total_marks = marks1 + marks2 + marks3 +average = total_marks / 3 + +print("\n--- Student Report ---") +print(f"Name: {name}") +print(f"Roll Number: {roll_number}") +print(f"Marks: {marks1}, {marks2}, {marks3}") +print(f"Total: {total_marks}") +print(f"Average: {average:.2f}") + +# Taking a list of items +print("\n=== Shopping List ===") +print("Enter items separated by commas:") +items = input().split(",") +# Remove extra spaces from each item +items = [item.strip() for item in items] + +print("\nYour shopping list:") +for i, item in enumerate(items, 1): + print(f"{i}. {item}") + +# Yes/No input +print("\n=== Yes/No Input ===") +response = input("Do you like Python? (yes/no): ").lower() +if response == "yes" or response == "y": + print("Great! Keep learning!") +elif response == "no" or response == "n": + print("Give it more time, you'll love it!") +else: + print("Please answer yes or no") + +# Menu-based input +print("\n=== Menu Selection ===") +print("Choose an operation:") +print("1. Addition") +print("2. Subtraction") +print("3. Multiplication") +print("4. Division") +choice = int(input("Enter your choice (1-4): ")) + +if 1 <= choice <= 4: + num1 = float(input("Enter first number: ")) + num2 = float(input("Enter second number: ")) + + if choice == 1: + print(f"Result: {num1 + num2}") + elif choice == 2: + print(f"Result: {num1 - num2}") + elif choice == 3: + print(f"Result: {num1 * num2}") + elif choice == 4: + if num2 != 0: + print(f"Result: {num1 / num2}") + else: + print("Error: Division by zero!") +else: + print("Invalid choice!") + +# Personal information collector +print("\n=== Personal Information ===") +data = {} +data['name'] = input("Full Name: ") +data['email'] = input("Email: ") +data['phone'] = input("Phone Number: ") +data['address'] = input("Address: ") + +print("\n--- Information Summary ---") +for key, value in data.items(): + print(f"{key.capitalize()}: {value}") + +# Quiz program +print("\n=== Quick Quiz ===") +score = 0 + +question1 = input("What is the capital of France? ").lower() +if question1 == "paris": + print("Correct!") + score += 1 +else: + print("Wrong! The answer is Paris.") + +question2 = input("What is 5 + 7? ") +if question2 == "12": + print("Correct!") + score += 1 +else: + print("Wrong! The answer is 12.") + +print(f"\nYour score: {score}/2") diff --git a/02_Input_Output/README.md b/02_Input_Output/README.md new file mode 100644 index 0000000..580e7d6 --- /dev/null +++ b/02_Input_Output/README.md @@ -0,0 +1,47 @@ +# Input and Output in Python πŸ’¬ + +## What is Input/Output? + +**Input**: Getting data from the user +**Output**: Displaying data to the user + +## Taking Input + +Python uses the `input()` function to take input from users. All input comes as a **string** by default. + +```python +name = input("Enter your name: ") +print("Hello,", name) +``` + +## Displaying Output + +Python uses the `print()` function to display output. + +```python +print("Hello, World!") +``` + +## Important Points + +1. **input() always returns a string** - Convert it if you need numbers +2. **print() can display multiple items** - Separate with commas +3. **Use formatting** for better-looking output + +## Examples in This Folder + +1. **01_basic_input_output.py** - Simple input and output +2. **02_formatted_output.py** - Different ways to format output +3. **03_number_input.py** - Taking and using numeric input +4. **04_multiple_inputs.py** - Getting multiple inputs from user + +## Tips for Beginners + +- Always add a prompt message in input() to tell users what to enter +- Remember to convert input to int or float if you need to do math +- Use f-strings (f"...") for easy string formatting +- The print() function automatically adds a new line at the end + +## Practice + +Try running each example and experiment with different inputs! diff --git a/03_Conditional_Statements/01_basic_if_else.py b/03_Conditional_Statements/01_basic_if_else.py new file mode 100644 index 0000000..628712e --- /dev/null +++ b/03_Conditional_Statements/01_basic_if_else.py @@ -0,0 +1,131 @@ +""" +Basic if-else Statements in Python +=================================== +This program demonstrates how to use if and else statements to make decisions. +""" + +# Simple if statement +print("=== Simple if Statement ===") +age = 20 + +if age >= 18: + print("You are an adult") + print("You can vote!") + +print("This line always executes\n") + +# if-else statement +print("=== if-else Statement ===") +temperature = 25 + +if temperature > 30: + print("It's hot outside!") +else: + print("The weather is pleasant.") + +# Checking even or odd +print("\n=== Even or Odd Checker ===") +number = 7 + +if number % 2 == 0: + print(f"{number} is even") +else: + print(f"{number} is odd") + +# Comparison operators +print("\n=== Comparison Operators ===") +a = 10 +b = 20 + +print(f"a = {a}, b = {b}") +print(f"a == b: {a == b}") # Equal to +print(f"a != b: {a != b}") # Not equal to +print(f"a > b: {a > b}") # Greater than +print(f"a < b: {a < b}") # Less than +print(f"a >= b: {a >= b}") # Greater than or equal to +print(f"a <= b: {a <= b}") # Less than or equal to + +# Using comparisons in if statements +print("\n=== Grade Pass/Fail ===") +marks = 75 + +if marks >= 50: + print(f"Marks: {marks}") + print("Result: PASS βœ“") +else: + print(f"Marks: {marks}") + print("Result: FAIL βœ—") + +# String comparison +print("\n=== String Comparison ===") +password = "python123" +user_input = "python123" + +if user_input == password: + print("Password correct! Access granted.") +else: + print("Wrong password! Access denied.") + +# Checking if a number is positive or negative +print("\n=== Positive/Negative Checker ===") +num = -5 + +if num >= 0: + print(f"{num} is positive or zero") +else: + print(f"{num} is negative") + +# Age category checker +print("\n=== Age Category ===") +person_age = 15 + +if person_age >= 18: + print("Category: Adult") + print("Can drive, vote, and watch adult movies") +else: + print("Category: Minor") + print("Cannot drive or vote yet") + +# Boolean variables in conditions +print("\n=== Boolean in Conditions ===") +is_raining = True + +if is_raining: + print("Take an umbrella!") +else: + print("No need for an umbrella.") + +# Discount eligibility +print("\n=== Discount Checker ===") +purchase_amount = 1500 +minimum_for_discount = 1000 + +if purchase_amount >= minimum_for_discount: + discount = purchase_amount * 0.1 + final_amount = purchase_amount - discount + print(f"Purchase amount: ${purchase_amount}") + print(f"Discount (10%): ${discount}") + print(f"Final amount: ${final_amount}") +else: + print(f"Purchase amount: ${purchase_amount}") + print("No discount available") + print(f"Final amount: ${purchase_amount}") + +# Membership check +print("\n=== Membership Checker ===") +has_membership = False + +if has_membership: + print("Welcome back, member! Enjoy 20% off.") +else: + print("Sign up for membership to get discounts!") + +# Interactive example +print("\n=== Interactive Age Checker ===") +user_age = int(input("Enter your age: ")) + +if user_age >= 18: + print("You are eligible to vote!") +else: + years_left = 18 - user_age + print(f"You need to wait {years_left} more year(s) to vote.") diff --git a/03_Conditional_Statements/02_elif_statement.py b/03_Conditional_Statements/02_elif_statement.py new file mode 100644 index 0000000..e2a02ff --- /dev/null +++ b/03_Conditional_Statements/02_elif_statement.py @@ -0,0 +1,178 @@ +""" +elif (else-if) Statement in Python +=================================== +This program demonstrates how to use elif for multiple conditions. +""" + +# Basic elif example +print("=== Traffic Light System ===") +light = "yellow" + +if light == "red": + print("STOP") +elif light == "yellow": + print("SLOW DOWN") +elif light == "green": + print("GO") +else: + print("Invalid light color") + +# Grade calculator +print("\n=== Grade Calculator ===") +marks = 85 + +if marks >= 90: + grade = "A" +elif marks >= 80: + grade = "B" +elif marks >= 70: + grade = "C" +elif marks >= 60: + grade = "D" +elif marks >= 50: + grade = "E" +else: + grade = "F" + +print(f"Marks: {marks}") +print(f"Grade: {grade}") + +# Age category checker (more detailed) +print("\n=== Detailed Age Categories ===") +age = 25 + +if age < 0: + print("Invalid age!") +elif age <= 2: + print("Category: Infant") +elif age <= 12: + print("Category: Child") +elif age <= 19: + print("Category: Teenager") +elif age <= 59: + print("Category: Adult") +else: + print("Category: Senior Citizen") + +# BMI category +print("\n=== BMI Category Calculator ===") +bmi = 23.5 + +if bmi < 18.5: + category = "Underweight" + suggestion = "You should eat more nutritious food" +elif bmi < 25: + category = "Normal weight" + suggestion = "Keep maintaining your healthy lifestyle!" +elif bmi < 30: + category = "Overweight" + suggestion = "Consider regular exercise and balanced diet" +else: + category = "Obese" + suggestion = "Please consult a doctor for health advice" + +print(f"BMI: {bmi}") +print(f"Category: {category}") +print(f"Suggestion: {suggestion}") + +# Temperature advisory +print("\n=== Temperature Advisory ===") +temp = 28 + +if temp < 0: + print("Freezing! Stay indoors.") +elif temp < 15: + print("Cold. Wear warm clothes.") +elif temp < 25: + print("Pleasant weather. Enjoy!") +elif temp < 35: + print("Warm. Stay hydrated.") +else: + print("Very hot! Avoid going out.") + +# Discount based on purchase amount +print("\n=== Discount Calculator ===") +amount = 2500 + +if amount >= 5000: + discount_percent = 20 +elif amount >= 3000: + discount_percent = 15 +elif amount >= 1000: + discount_percent = 10 +elif amount >= 500: + discount_percent = 5 +else: + discount_percent = 0 + +discount = amount * discount_percent / 100 +final_amount = amount - discount + +print(f"Purchase amount: ${amount}") +print(f"Discount: {discount_percent}%") +print(f"Discount amount: ${discount}") +print(f"Final amount: ${final_amount}") + +# Day of week +print("\n=== Day of Week ===") +day = 3 + +if day == 1: + print("Monday - Start of the work week") +elif day == 2: + print("Tuesday") +elif day == 3: + print("Wednesday - Mid-week") +elif day == 4: + print("Thursday") +elif day == 5: + print("Friday - Last working day!") +elif day == 6: + print("Saturday - Weekend!") +elif day == 7: + print("Sunday - Weekend!") +else: + print("Invalid day number!") + +# Ticket pricing based on age +print("\n=== Movie Ticket Pricing ===") +visitor_age = 8 + +if visitor_age < 3: + price = 0 + category = "Free (Infant)" +elif visitor_age < 12: + price = 5 + category = "Child ticket" +elif visitor_age < 18: + price = 8 + category = "Teen ticket" +elif visitor_age < 60: + price = 12 + category = "Adult ticket" +else: + price = 6 + category = "Senior citizen ticket" + +print(f"Age: {visitor_age}") +print(f"Category: {category}") +print(f"Ticket price: ${price}") + +# Interactive grade calculator +print("\n=== Interactive Grade Calculator ===") +score = int(input("Enter your marks (0-100): ")) + +if score > 100 or score < 0: + print("Invalid marks! Please enter between 0 and 100.") +elif score >= 90: + print("Grade: A - Excellent!") +elif score >= 80: + print("Grade: B - Very Good!") +elif score >= 70: + print("Grade: C - Good!") +elif score >= 60: + print("Grade: D - Satisfactory") +elif score >= 50: + print("Grade: E - Pass") +else: + print("Grade: F - Fail") diff --git a/03_Conditional_Statements/03_nested_conditions.py b/03_Conditional_Statements/03_nested_conditions.py new file mode 100644 index 0000000..2982cc0 --- /dev/null +++ b/03_Conditional_Statements/03_nested_conditions.py @@ -0,0 +1,168 @@ +""" +Nested Conditional Statements in Python +======================================== +This program demonstrates conditions inside conditions (nested if statements). +""" + +# Basic nested if +print("=== Basic Nested if ===") +age = 25 +has_license = True + +if age >= 18: + print("Age requirement met") + if has_license: + print("You can drive!") + else: + print("You need a driving license") +else: + print("You are too young to drive") + +# Nested if-else with multiple levels +print("\n=== Login System ===") +username = "admin" +password = "pass123" +user_input = "admin" +pass_input = "pass123" + +if user_input == username: + print("Username correct") + if pass_input == password: + print("Password correct") + print("Login successful! βœ“") + else: + print("Wrong password! βœ—") +else: + print("Username not found! βœ—") + +# Eligibility for scholarship +print("\n=== Scholarship Eligibility ===") +marks = 85 +family_income = 30000 +has_sports = True + +if marks >= 80: + print("Academic requirement met") + if family_income < 50000: + print("Income requirement met") + if has_sports: + print("Sports quota bonus!") + print("Scholarship: $5000") + else: + print("Scholarship: $3000") + else: + print("Family income too high for scholarship") +else: + print("Marks not sufficient for scholarship") + +# Voting eligibility with detailed checks +print("\n=== Voting Eligibility Checker ===") +age = 20 +is_citizen = True +has_id = True + +if age >= 18: + print("Age: Eligible") + if is_citizen: + print("Citizenship: Verified") + if has_id: + print("ID: Verified") + print("\nβœ“ You can vote!") + else: + print("ID: Not found") + print("\nβœ— Please bring a valid ID to vote") + else: + print("Citizenship: Not verified") + print("\nβœ— Only citizens can vote") +else: + years_left = 18 - age + print(f"Age: Not eligible (wait {years_left} more years)") + +# Admission process +print("\n=== College Admission System ===") +entrance_score = 450 +interview_score = 85 +has_recommendation = True + +if entrance_score >= 400: + print("Entrance exam: PASSED") + if interview_score >= 80: + print("Interview: PASSED") + if has_recommendation: + print("Recommendation letter: YES") + print("\nπŸŽ“ Admission Status: ACCEPTED with Honors") + else: + print("Recommendation letter: NO") + print("\nπŸŽ“ Admission Status: ACCEPTED") + else: + print("Interview: FAILED") + print(f"Score: {interview_score}/100 (minimum required: 80)") + print("\n❌ Admission Status: REJECTED") +else: + print("Entrance exam: FAILED") + print(f"Score: {entrance_score}/500 (minimum required: 400)") + print("\n❌ Admission Status: REJECTED") + +# Shopping discount with membership +print("\n=== Advanced Shopping Discount ===") +purchase_amount = 1500 +is_member = True +first_time = False + +if purchase_amount >= 1000: + if is_member: + if first_time: + discount = purchase_amount * 0.25 # 25% for first time members + print("Discount: 25% (Member + First Purchase)") + else: + discount = purchase_amount * 0.20 # 20% for regular members + print("Discount: 20% (Regular Member)") + else: + discount = purchase_amount * 0.10 # 10% for non-members + print("Discount: 10% (Non-member)") +else: + if is_member: + discount = purchase_amount * 0.05 # 5% for members on small purchases + print("Discount: 5% (Member - small purchase)") + else: + discount = 0 # No discount + print("No discount available") + +final_amount = purchase_amount - discount +print(f"\nPurchase amount: ${purchase_amount}") +print(f"Discount amount: ${discount}") +print(f"Final amount: ${final_amount}") + +# Exam result with detailed feedback +print("\n=== Exam Result System ===") +theory_marks = 75 +practical_marks = 80 +attendance = 85 + +if theory_marks >= 50: + print("Theory: PASS") + if practical_marks >= 50: + print("Practical: PASS") + if attendance >= 75: + print("Attendance: Sufficient") + average = (theory_marks + practical_marks) / 2 + print(f"\nOverall Average: {average}") + + if average >= 90: + print("Result: DISTINCTION ⭐⭐⭐") + elif average >= 75: + print("Result: FIRST CLASS ⭐⭐") + elif average >= 60: + print("Result: SECOND CLASS ⭐") + else: + print("Result: PASS βœ“") + else: + print("Attendance: Insufficient") + print(f"Attendance: {attendance}% (minimum required: 75%)") + print("\nResult: DETAINED") + else: + print("Practical: FAIL") + print("\nResult: FAIL in Practical") +else: + print("Theory: FAIL") + print("\nResult: FAIL in Theory") diff --git a/03_Conditional_Statements/04_logical_operators.py b/03_Conditional_Statements/04_logical_operators.py new file mode 100644 index 0000000..ba9cc67 --- /dev/null +++ b/03_Conditional_Statements/04_logical_operators.py @@ -0,0 +1,188 @@ +""" +Logical Operators in Python +============================ +This program demonstrates using and, or, not operators in conditions. +""" + +# AND operator - both conditions must be True +print("=== AND Operator ===") +age = 25 +has_license = True + +if age >= 18 and has_license: + print("You can drive a car!") +else: + print("You cannot drive") + +# More AND examples +print("\n=== Login with AND ===") +username = "admin" +password = "1234" + +if username == "admin" and password == "1234": + print("Login successful!") +else: + print("Invalid credentials") + +# OR operator - at least one condition must be True +print("\n=== OR Operator ===") +day = "Sunday" + +if day == "Saturday" or day == "Sunday": + print("It's the weekend! πŸŽ‰") +else: + print("It's a weekday πŸ“š") + +# More OR examples +print("\n=== Emergency Contact OR ===") +relationship = "parent" + +if relationship == "parent" or relationship == "guardian" or relationship == "spouse": + print("Valid emergency contact") +else: + print("Please provide a close family member") + +# NOT operator - reverses the condition +print("\n=== NOT Operator ===") +is_raining = False + +if not is_raining: + print("You don't need an umbrella") +else: + print("Take an umbrella!") + +# Combining AND, OR +print("\n=== Combining AND, OR ===") +age = 22 +student = True +employed = False + +if (age < 25 and student) or employed: + print("Eligible for discount") +else: + print("Not eligible for discount") + +# Scholarship eligibility +print("\n=== Scholarship Eligibility ===") +marks = 85 +income = 40000 + +if marks >= 80 and income < 50000: + print("Eligible for scholarship!") +else: + print("Not eligible for scholarship") + +# Voting eligibility with logical operators +print("\n=== Voting Eligibility ===") +age = 20 +is_citizen = True +has_criminal_record = False + +if age >= 18 and is_citizen and not has_criminal_record: + print("You are eligible to vote! βœ“") +else: + print("You are not eligible to vote") + +# Weekend or holiday +print("\n=== Day Off Checker ===") +day = "Saturday" +is_holiday = False + +if day == "Saturday" or day == "Sunday" or is_holiday: + print("You have the day off! 😊") +else: + print("It's a working day") + +# Movie rating system +print("\n=== Movie Access Control ===") +age = 16 +has_parent = True +movie_rating = "R" + +if movie_rating == "G": + print("Everyone can watch") +elif movie_rating == "PG" and (age >= 13 or has_parent): + print("You can watch this movie") +elif movie_rating == "R" and age >= 18: + print("You can watch this movie") +elif movie_rating == "R" and age >= 13 and has_parent: + print("You can watch with parental guidance") +else: + print("You cannot watch this movie") + +# Exam pass conditions +print("\n=== Exam Pass Criteria ===") +theory = 65 +practical = 70 +attendance = 80 + +if (theory >= 50 and practical >= 50) and attendance >= 75: + print("Result: PASS βœ“") + print("Congratulations!") +else: + print("Result: FAIL βœ—") + if theory < 50: + print("Failed in theory") + if practical < 50: + print("Failed in practical") + if attendance < 75: + print("Insufficient attendance") + +# Login attempt validation +print("\n=== Login Validation ===") +username = "user123" +password = "pass456" +account_active = True +attempts_left = 3 + +if username == "user123" and password == "pass456": + if account_active and attempts_left > 0: + print("Login successful!") + elif not account_active: + print("Account is deactivated") + else: + print("Too many failed attempts") +else: + print("Invalid username or password") + +# Discount eligibility +print("\n=== Discount Eligibility ===") +purchase_amount = 1200 +is_member = True +has_coupon = False + +if purchase_amount >= 1000 or (is_member and purchase_amount >= 500): + print("Base discount: 10%") + if has_coupon: + print("Additional coupon discount: 5%") + print("Total discount: 15%") + else: + print("Total discount: 10%") +else: + print("No discount available") + +# Temperature comfort check +print("\n=== Temperature Comfort ===") +temperature = 24 +humidity = 60 + +if (temperature >= 20 and temperature <= 26) and humidity < 70: + print("Weather is comfortable! 😊") +elif temperature < 20: + print("It's cold!") +elif temperature > 26: + print("It's hot!") +else: + print("High humidity makes it uncomfortable") + +# Interactive example +print("\n=== Interactive Age & License Check ===") +user_age = int(input("Enter your age: ")) +has_driving_license = input("Do you have a driving license? (yes/no): ").lower() + +if user_age >= 18 and (has_driving_license == "yes" or has_driving_license == "y"): + print("You are allowed to drive!") +elif user_age >= 18 and (has_driving_license == "no" or has_driving_license == "n"): + print("You are old enough but need a license") +else: + print("You are too young to drive") diff --git a/03_Conditional_Statements/05_practical_examples.py b/03_Conditional_Statements/05_practical_examples.py new file mode 100644 index 0000000..fdee178 --- /dev/null +++ b/03_Conditional_Statements/05_practical_examples.py @@ -0,0 +1,215 @@ +""" +Practical Examples of Conditional Statements +============================================= +This program contains real-world applications of if-else statements. +""" + +# Example 1: Simple Calculator +print("=== SIMPLE CALCULATOR ===") +try: + num1 = float(input("Enter first number: ")) + operator = input("Enter operator (+, -, *, /): ") + num2 = float(input("Enter second number: ")) +except ValueError: + print("Error: Please enter valid numbers!") + num1, operator, num2 = 10, "+", 5 # Default values for demonstration + print(f"Using default values: {num1} {operator} {num2}") + +if operator == "+": + result = num1 + num2 + print(f"{num1} + {num2} = {result}") +elif operator == "-": + result = num1 - num2 + print(f"{num1} - {num2} = {result}") +elif operator == "*": + result = num1 * num2 + print(f"{num1} * {num2} = {result}") +elif operator == "/": + if num2 != 0: + result = num1 / num2 + print(f"{num1} / {num2} = {result}") + else: + print("Error: Division by zero!") +else: + print("Invalid operator!") + +# Example 2: Grade Calculator +print("\n=== GRADE CALCULATOR ===") +try: + marks = int(input("Enter your marks (0-100): ")) +except (ValueError, EOFError): + marks = 85 # Default value for demonstration + print(f"Using default value: {marks}") + +if marks > 100 or marks < 0: + print("Invalid marks! Please enter between 0 and 100.") +else: + if marks >= 90: + grade = "A" + remark = "Outstanding!" + elif marks >= 80: + grade = "B" + remark = "Excellent!" + elif marks >= 70: + grade = "C" + remark = "Good!" + elif marks >= 60: + grade = "D" + remark = "Satisfactory" + elif marks >= 50: + grade = "E" + remark = "Pass" + else: + grade = "F" + remark = "Fail" + + print(f"Marks: {marks}") + print(f"Grade: {grade}") + print(f"Remark: {remark}") + +# Example 3: Leap Year Checker +print("\n=== LEAP YEAR CHECKER ===") +try: + year = int(input("Enter a year: ")) +except (ValueError, EOFError): + year = 2024 # Default value for demonstration + print(f"Using default value: {year}") + +if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): + print(f"{year} is a leap year! πŸŽ‰") +else: + print(f"{year} is not a leap year.") + +# Example 4: Electricity Bill Calculator +print("\n=== ELECTRICITY BILL CALCULATOR ===") +try: + units = int(input("Enter units consumed: ")) +except (ValueError, EOFError): + units = 250 # Default value for demonstration + print(f"Using default value: {units} units") + +if units <= 100: + bill = units * 0 + print("First 100 units are free!") +elif units <= 200: + bill = (units - 100) * 2.50 +elif units <= 300: + bill = (100 * 2.50) + ((units - 200) * 4.00) +else: + bill = (100 * 2.50) + (100 * 4.00) + ((units - 300) * 6.50) + +print(f"Units consumed: {units}") +print(f"Total bill: ${bill:.2f}") + +# Example 5: Triangle Type Checker +print("\n=== TRIANGLE TYPE CHECKER ===") +try: + side1 = float(input("Enter first side: ")) + side2 = float(input("Enter second side: ")) + side3 = float(input("Enter third side: ")) +except (ValueError, EOFError): + side1, side2, side3 = 5, 5, 5 # Default values for demonstration + print(f"Using default values: {side1}, {side2}, {side3}") + +if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2: + print("Valid triangle!") + if side1 == side2 == side3: + print("Type: Equilateral Triangle") + elif side1 == side2 or side2 == side3 or side1 == side3: + print("Type: Isosceles Triangle") + else: + print("Type: Scalene Triangle") +else: + print("Invalid triangle! Sum of any two sides must be greater than the third.") + +# Example 6: Largest of Three Numbers +print("\n=== LARGEST OF THREE NUMBERS ===") +try: + a = int(input("Enter first number: ")) + b = int(input("Enter second number: ")) + c = int(input("Enter third number: ")) +except (ValueError, EOFError): + a, b, c = 10, 25, 15 # Default values for demonstration + print(f"Using default values: {a}, {b}, {c}") + +if a >= b and a >= c: + largest = a +elif b >= a and b >= c: + largest = b +else: + largest = c + +print(f"The largest number is: {largest}") + +# Example 7: Ticket Booking System +print("\n=== MOVIE TICKET BOOKING ===") +try: + age = int(input("Enter your age: ")) + movie_time = input("Enter show time (morning/afternoon/evening): ").lower() +except (ValueError, EOFError): + age, movie_time = 25, "morning" # Default values for demonstration + print(f"Using default values: age={age}, time={movie_time}") + +# Calculate base price +if age < 3: + base_price = 0 +elif age < 12: + base_price = 100 +elif age < 60: + base_price = 200 +else: + base_price = 150 + +# Apply time-based discount +if movie_time == "morning": + discount = base_price * 0.20 + print("Morning show discount: 20%") +elif movie_time == "afternoon": + discount = base_price * 0.10 + print("Afternoon show discount: 10%") +else: + discount = 0 + print("No time discount for evening shows") + +final_price = base_price - discount +print(f"\nBase price: ${base_price}") +print(f"Discount: ${discount}") +print(f"Final ticket price: ${final_price}") + +# Example 8: Password Strength Checker +print("\n=== PASSWORD STRENGTH CHECKER ===") +try: + password = input("Enter a password: ") +except EOFError: + password = "Test123" # Default value for demonstration + print(f"Using default password: {password}") +length = len(password) + +has_upper = any(c.isupper() for c in password) +has_lower = any(c.islower() for c in password) +has_digit = any(c.isdigit() for c in password) + +if length < 6: + strength = "Very Weak" + message = "Password is too short!" +elif length < 8: + if has_upper and has_lower: + strength = "Weak" + message = "Add numbers for better security" + else: + strength = "Very Weak" + message = "Use both uppercase and lowercase" +else: + if has_upper and has_lower and has_digit: + strength = "Strong" + message = "Great password! βœ“" + elif (has_upper and has_lower) or (has_digit and (has_upper or has_lower)): + strength = "Medium" + message = "Consider adding more variety" + else: + strength = "Weak" + message = "Use uppercase, lowercase, and numbers" + +print(f"Password length: {length}") +print(f"Strength: {strength}") +print(f"Message: {message}") diff --git a/03_Conditional_Statements/README.md b/03_Conditional_Statements/README.md new file mode 100644 index 0000000..d2ac170 --- /dev/null +++ b/03_Conditional_Statements/README.md @@ -0,0 +1,68 @@ +# Conditional Statements in Python πŸ”€ + +## What are Conditional Statements? + +Conditional statements allow your program to make decisions and execute different code based on conditions. They are like "if this happens, then do that" logic. + +## Types of Conditional Statements + +### 1. **if statement** +Executes code only if the condition is True +```python +if age >= 18: + print("You are an adult") +``` + +### 2. **if-else statement** +Executes one block if True, another if False +```python +if age >= 18: + print("You are an adult") +else: + print("You are a minor") +``` + +### 3. **if-elif-else statement** +Tests multiple conditions +```python +if score >= 90: + print("Grade A") +elif score >= 80: + print("Grade B") +else: + print("Grade C") +``` + +## Comparison Operators + +- `==` : Equal to +- `!=` : Not equal to +- `>` : Greater than +- `<` : Less than +- `>=` : Greater than or equal to +- `<=` : Less than or equal to + +## Logical Operators + +- `and` : Both conditions must be True +- `or` : At least one condition must be True +- `not` : Reverses the condition + +## Examples in This Folder + +1. **01_basic_if_else.py** - Simple if-else conditions +2. **02_elif_statement.py** - Multiple conditions with elif +3. **03_nested_conditions.py** - Conditions inside conditions +4. **04_logical_operators.py** - Using and, or, not +5. **05_practical_examples.py** - Real-world applications + +## Tips for Beginners + +- Use proper indentation (4 spaces) - it's required in Python! +- Conditions must evaluate to True or False +- Use `==` for comparison, not `=` (which is for assignment) +- Test your conditions with different values + +## Practice + +Run each example and try modifying the conditions to see different outcomes! diff --git a/04_Loops/01_basic_for_loop.py b/04_Loops/01_basic_for_loop.py new file mode 100644 index 0000000..02a131e --- /dev/null +++ b/04_Loops/01_basic_for_loop.py @@ -0,0 +1,123 @@ +""" +Basic for Loop in Python +========================= +This program demonstrates how to use for loops to repeat code. +""" + +# Simple for loop +print("=== Simple for Loop ===") +for i in range(5): + print(f"Iteration {i}") + +# Looping through a list +print("\n=== Looping Through a List ===") +fruits = ["apple", "banana", "orange", "grape"] +for fruit in fruits: + print(f"I like {fruit}") + +# Looping through a string +print("\n=== Looping Through a String ===") +word = "Python" +for char in word: + print(char) + +# Counting from 1 to 10 +print("\n=== Counting 1 to 10 ===") +for number in range(1, 11): + print(number, end=" ") +print() # New line + +# Printing even numbers +print("\n=== Even Numbers (0-20) ===") +for num in range(0, 21, 2): + print(num, end=" ") +print() + +# Using loop with index +print("\n=== List with Index ===") +colors = ["red", "green", "blue", "yellow"] +for i in range(len(colors)): + print(f"Index {i}: {colors[i]}") + +# enumerate() - Better way to get index and value +print("\n=== Using enumerate() ===") +subjects = ["Math", "Science", "English"] +for index, subject in enumerate(subjects): + print(f"{index + 1}. {subject}") + +# Starting enumerate from 1 +print("\n=== enumerate() Starting from 1 ===") +for index, subject in enumerate(subjects, start=1): + print(f"{index}. {subject}") + +# Looping through a tuple +print("\n=== Looping Through a Tuple ===") +coordinates = (10, 20, 30, 40) +for coord in coordinates: + print(f"Coordinate: {coord}") + +# Calculating sum using loop +print("\n=== Sum of Numbers ===") +numbers = [10, 20, 30, 40, 50] +total = 0 +for num in numbers: + total += num +print(f"Numbers: {numbers}") +print(f"Sum: {total}") + +# Multiplication table +print("\n=== Multiplication Table of 5 ===") +for i in range(1, 11): + print(f"5 Γ— {i} = {5 * i}") + +# Countdown +print("\n=== Countdown ===") +for i in range(5, 0, -1): + print(i) +print("Blast off! πŸš€") + +# Pattern printing +print("\n=== Star Pattern ===") +for i in range(1, 6): + print("* " * i) + +# Shopping list with formatting +print("\n=== Shopping List ===") +shopping_items = ["milk", "bread", "eggs", "butter", "cheese"] +print("My Shopping List:") +print("-" * 30) +for item_num, item in enumerate(shopping_items, start=1): + print(f"{item_num}. {item.capitalize()}") + +# Looping through dictionary keys +print("\n=== Dictionary Keys ===") +student = {"name": "Alice", "age": 20, "grade": "A"} +for key in student: + print(f"{key}: {student[key]}") + +# Better way - using items() +print("\n=== Dictionary Items ===") +for key, value in student.items(): + print(f"{key}: {value}") + +# Squaring numbers +print("\n=== Square Numbers ===") +for num in range(1, 6): + square = num ** 2 + print(f"{num}Β² = {square}") + +# Finding maximum in a list +print("\n=== Finding Maximum ===") +numbers = [45, 23, 78, 12, 67, 34] +max_num = numbers[0] +for num in numbers: + if num > max_num: + max_num = num +print(f"Numbers: {numbers}") +print(f"Maximum: {max_num}") + +# Greeting multiple people +print("\n=== Greeting Multiple People ===") +names = ["Alice", "Bob", "Charlie", "Diana"] +for name in names: + print(f"Hello, {name}! Welcome to Python.") diff --git a/04_Loops/02_range_function.py b/04_Loops/02_range_function.py new file mode 100644 index 0000000..761c626 --- /dev/null +++ b/04_Loops/02_range_function.py @@ -0,0 +1,156 @@ +""" +Range Function in Python +========================= +This program demonstrates different ways to use the range() function in loops. +""" + +# Basic range - starts from 0 +print("=== range(5) - Numbers 0 to 4 ===") +for i in range(5): + print(i, end=" ") +print() + +# Range with start and stop +print("\n=== range(1, 6) - Numbers 1 to 5 ===") +for i in range(1, 6): + print(i, end=" ") +print() + +# Range with step +print("\n=== range(0, 10, 2) - Even numbers ===") +for i in range(0, 10, 2): + print(i, end=" ") +print() + +# Odd numbers using range +print("\n=== Odd Numbers (1-20) ===") +for i in range(1, 21, 2): + print(i, end=" ") +print() + +# Counting backwards +print("\n=== Countdown from 10 ===") +for i in range(10, 0, -1): + print(i, end=" ") +print("\nLiftoff! πŸš€") + +# Range with negative step +print("\n=== range(20, 0, -2) - Reverse even ===") +for i in range(20, 0, -2): + print(i, end=" ") +print() + +# Converting range to list +print("\n=== Range as List ===") +numbers = list(range(1, 11)) +print(f"List: {numbers}") + +# Sum of first n natural numbers +print("\n=== Sum of First 10 Natural Numbers ===") +n = 10 +total = 0 +for i in range(1, n + 1): + total += i +print(f"Sum of 1 to {n} = {total}") + +# Multiplication tables using range +print("\n=== Multiplication Table of 7 ===") +table_num = 7 +for i in range(1, 11): + result = table_num * i + print(f"{table_num} Γ— {i} = {result}") + +# Printing multiples +print("\n=== Multiples of 3 (up to 30) ===") +for num in range(3, 31, 3): + print(num, end=" ") +print() + +# Squares using range +print("\n=== Squares of Numbers 1-10 ===") +for num in range(1, 11): + print(f"{num}Β² = {num**2}") + +# Powers of 2 +print("\n=== Powers of 2 (2⁰ to 2¹⁰) ===") +for power in range(11): + result = 2 ** power + print(f"2^{power} = {result}") + +# Accessing list elements using range +print("\n=== Accessing List with range ===") +fruits = ["apple", "banana", "orange", "grape", "mango"] +print("Fruits:") +for i in range(len(fruits)): + print(f" [{i}] {fruits[i]}") + +# Reverse iteration through a list +print("\n=== Reverse List Iteration ===") +for i in range(len(fruits) - 1, -1, -1): + print(fruits[i]) + +# Skipping elements +print("\n=== Every Third Element ===") +numbers = list(range(1, 21)) +print(f"Original: {numbers}") +print("Every 3rd element:", end=" ") +for i in range(0, len(numbers), 3): + print(numbers[i], end=" ") +print() + +# Creating a number grid +print("\n=== Number Grid (5Γ—5) ===") +for row in range(1, 6): + for col in range(1, 6): + print(f"{row * col:3}", end=" ") + print() + +# Alphabet using range +print("\n=== First 10 Letters of Alphabet ===") +for i in range(ord('A'), ord('A') + 10): + print(chr(i), end=" ") +print() + +# Factorial using range +print("\n=== Factorial of 5 ===") +num = 5 +factorial = 1 +for i in range(1, num + 1): + factorial *= i +print(f"{num}! = {factorial}") + +# Average of numbers +print("\n=== Average of 1 to 100 ===") +total = 0 +count = 0 +for num in range(1, 101): + total += num + count += 1 +average = total / count +print(f"Sum: {total}") +print(f"Count: {count}") +print(f"Average: {average}") + +# Nested range example +print("\n=== Nested Range - Right Triangle ===") +for i in range(1, 6): + for j in range(i): + print("*", end="") + print() + +# Temperature conversion table +print("\n=== Celsius to Fahrenheit Table ===") +print(f"{'Celsius':>8} {'Fahrenheit':>10}") +print("-" * 20) +for celsius in range(0, 101, 10): + fahrenheit = (celsius * 9/5) + 32 + print(f"{celsius:>8}Β°C {fahrenheit:>10.1f}Β°F") + +# Finding divisible numbers +print("\n=== Numbers Divisible by 5 (1-50) ===") +count = 0 +for num in range(1, 51): + if num % 5 == 0: + print(num, end=" ") + count += 1 +print(f"\nTotal count: {count}") diff --git a/04_Loops/03_while_loop.py b/04_Loops/03_while_loop.py new file mode 100644 index 0000000..fffd539 --- /dev/null +++ b/04_Loops/03_while_loop.py @@ -0,0 +1,209 @@ +""" +While Loop in Python +==================== +This program demonstrates how to use while loops. +While loops continue until a condition becomes False. +""" + +# Basic while loop +print("=== Basic While Loop ===") +count = 0 +while count < 5: + print(f"Count: {count}") + count += 1 + +# Counting from 1 to 10 +print("\n=== Counting 1 to 10 ===") +num = 1 +while num <= 10: + print(num, end=" ") + num += 1 +print() + +# Countdown +print("\n=== Countdown from 5 ===") +countdown = 5 +while countdown > 0: + print(countdown) + countdown -= 1 +print("Blast off! πŸš€") + +# Sum of numbers until condition +print("\n=== Sum Until 100 ===") +total = 0 +num = 1 +while total < 100: + total += num + num += 1 +print(f"Sum reached: {total}") +print(f"Last number added: {num - 1}") + +# User input validation (simulated) +print("\n=== Password Attempt (Simulated) ===") +correct_password = "python123" +attempts = 0 +max_attempts = 3 + +# Simulated user inputs +test_inputs = ["wrong1", "wrong2", "python123"] + +while attempts < max_attempts: + user_input = test_inputs[attempts] if attempts < len(test_inputs) else "wrong" + print(f"Attempt {attempts + 1}: Trying password '{user_input}'") + + if user_input == correct_password: + print("Access granted! βœ“") + break + else: + attempts += 1 + if attempts < max_attempts: + print(f"Wrong password. {max_attempts - attempts} attempts remaining.") + else: + print("Access denied! Too many attempts.") + +# While loop with condition +print("\n=== Doubling Until Limit ===") +number = 1 +while number < 1000: + print(number, end=" ") + number *= 2 +print() + +# Menu-driven program (simulated) +print("\n=== Simple Menu (Simulated) ===") +running = True +iteration = 0 +simulated_choices = [1, 2, 3] # Simulated user choices + +while running and iteration < len(simulated_choices): + choice = simulated_choices[iteration] + print(f"\n--- Menu ---") + print("1. Say Hello") + print("2. Show Date") + print("3. Exit") + print(f"Choice: {choice}") + + if choice == 1: + print("Hello, User!") + elif choice == 2: + print("Today is a great day!") + elif choice == 3: + print("Goodbye!") + running = False + + iteration += 1 + +# Finding first number divisible by 7 +print("\n=== First Number Divisible by 7 ===") +num = 50 +while num % 7 != 0: + num += 1 +print(f"First number >= 50 divisible by 7: {num}") + +# Summing digits +print("\n=== Sum of Digits ===") +number = 12345 +original = number +digit_sum = 0 + +while number > 0: + digit = number % 10 + digit_sum += digit + number //= 10 + +print(f"Number: {original}") +print(f"Sum of digits: {digit_sum}") + +# Reverse a number +print("\n=== Reverse a Number ===") +number = 1234 +original = number +reversed_num = 0 + +while number > 0: + digit = number % 10 + reversed_num = reversed_num * 10 + digit + number //= 10 + +print(f"Original: {original}") +print(f"Reversed: {reversed_num}") + +# Guessing game (simulated) +print("\n=== Number Guessing Game (Simulated) ===") +secret_number = 7 +guesses = [3, 5, 7] # Simulated guesses +guess_count = 0 +found = False + +while guess_count < len(guesses) and not found: + guess = guesses[guess_count] + guess_count += 1 + print(f"Guess {guess_count}: {guess}") + + if guess == secret_number: + print(f"Correct! You guessed it in {guess_count} attempts!") + found = True + elif guess < secret_number: + print("Too low!") + else: + print("Too high!") + +# Factorial using while loop +print("\n=== Factorial Using While ===") +num = 6 +factorial = 1 +temp = num + +while temp > 0: + factorial *= temp + temp -= 1 + +print(f"{num}! = {factorial}") + +# Fibonacci sequence +print("\n=== Fibonacci Sequence (up to 100) ===") +a, b = 0, 1 +print(a, end=" ") +while b <= 100: + print(b, end=" ") + a, b = b, a + b +print() + +# Collatz sequence +print("\n=== Collatz Sequence (starting from 10) ===") +num = 10 +steps = 0 +print(num, end=" ") + +while num != 1: + if num % 2 == 0: + num = num // 2 + else: + num = 3 * num + 1 + print(num, end=" ") + steps += 1 + +print(f"\nReached 1 in {steps} steps") + +# Bank balance simulation +print("\n=== Bank Balance Simulation ===") +balance = 1000 +monthly_expense = 150 +months = 0 + +print(f"Starting balance: ${balance}") +while balance >= monthly_expense: + balance -= monthly_expense + months += 1 + print(f"Month {months}: ${balance}") + +print(f"Money lasted {months} months") + +# Power of 2 until limit +print("\n=== Powers of 2 (until > 1000) ===") +power = 0 +result = 1 +while result <= 1000: + print(f"2^{power} = {result}") + power += 1 + result = 2 ** power diff --git a/04_Loops/04_nested_loops.py b/04_Loops/04_nested_loops.py new file mode 100644 index 0000000..6a18bb0 --- /dev/null +++ b/04_Loops/04_nested_loops.py @@ -0,0 +1,208 @@ +""" +Nested Loops in Python +======================= +This program demonstrates loops inside loops (nested loops). +""" + +# Basic nested loop +print("=== Basic Nested Loop ===") +for i in range(1, 4): + for j in range(1, 4): + print(f"i={i}, j={j}") + print() + +# Multiplication table +print("=== Multiplication Table (1-5) ===") +for i in range(1, 6): + for j in range(1, 6): + print(f"{i*j:3}", end=" ") + print() + +# Complete multiplication table +print("\n=== Complete Multiplication Table (1-10) ===") +print(" ", end="") +for i in range(1, 11): + print(f"{i:4}", end="") +print() +print(" " + "-" * 40) + +for i in range(1, 11): + print(f"{i:2} |", end="") + for j in range(1, 11): + print(f"{i*j:4}", end="") + print() + +# Star patterns +print("\n=== Right Triangle Pattern ===") +for i in range(1, 6): + for j in range(i): + print("*", end=" ") + print() + +print("\n=== Inverted Right Triangle ===") +for i in range(5, 0, -1): + for j in range(i): + print("*", end=" ") + print() + +print("\n=== Pyramid Pattern ===") +n = 5 +for i in range(1, n + 1): + # Print spaces + for j in range(n - i): + print(" ", end="") + # Print stars + for j in range(2 * i - 1): + print("*", end="") + print() + +print("\n=== Number Triangle ===") +for i in range(1, 6): + for j in range(1, i + 1): + print(j, end=" ") + print() + +print("\n=== Number Pattern ===") +num = 1 +for i in range(1, 5): + for j in range(i): + print(num, end=" ") + num += 1 + print() + +# Rectangle pattern +print("\n=== Rectangle Pattern (5Γ—8) ===") +rows = 5 +cols = 8 +for i in range(rows): + for j in range(cols): + print("*", end=" ") + print() + +# Hollow rectangle +print("\n=== Hollow Rectangle (5Γ—8) ===") +for i in range(rows): + for j in range(cols): + if i == 0 or i == rows - 1 or j == 0 or j == cols - 1: + print("*", end=" ") + else: + print(" ", end=" ") + print() + +# Diamond pattern +print("\n=== Diamond Pattern ===") +n = 5 +# Upper half +for i in range(1, n + 1): + for j in range(n - i): + print(" ", end="") + for j in range(2 * i - 1): + print("*", end="") + print() +# Lower half +for i in range(n - 1, 0, -1): + for j in range(n - i): + print(" ", end="") + for j in range(2 * i - 1): + print("*", end="") + print() + +# Nested loop with lists +print("\n=== Nested Lists Iteration ===") +matrix = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] +] + +print("Matrix:") +for row in matrix: + for element in row: + print(f"{element:3}", end=" ") + print() + +# Sum of all elements in matrix +total = 0 +for row in matrix: + for element in row: + total += element +print(f"Sum of all elements: {total}") + +# Chess board pattern +print("\n=== Chess Board Pattern (8Γ—8) ===") +for i in range(8): + for j in range(8): + if (i + j) % 2 == 0: + print("β– ", end=" ") + else: + print("β–‘", end=" ") + print() + +# Times table chart +print("\n=== Times Table Chart ===") +for num in range(1, 4): + print(f"\nTable of {num}:") + for i in range(1, 6): + print(f"{num} Γ— {i} = {num * i}") + +# Finding all pairs +print("\n=== All Pairs from Two Lists ===") +list1 = [1, 2, 3] +list2 = ['A', 'B', 'C'] + +for num in list1: + for char in list2: + print(f"({num}, {char})", end=" ") +print() + +# Matrix addition +print("\n=== Matrix Addition ===") +matrix1 = [[1, 2, 3], [4, 5, 6]] +matrix2 = [[7, 8, 9], [10, 11, 12]] +result = [] + +print("Matrix 1:") +for row in matrix1: + print(row) + +print("\nMatrix 2:") +for row in matrix2: + print(row) + +print("\nSum:") +for i in range(len(matrix1)): + row_result = [] + for j in range(len(matrix1[0])): + row_result.append(matrix1[i][j] + matrix2[i][j]) + result.append(row_result) + print(row_result) + +# Coordinate system +print("\n=== Coordinate Grid (5Γ—5) ===") +for y in range(5, 0, -1): + for x in range(1, 6): + print(f"({x},{y})", end=" ") + print() + +# Nested while loops +print("\n=== Nested While Loops ===") +i = 1 +while i <= 3: + j = 1 + while j <= 3: + print(f"{i}Γ—{j}={i*j}", end=" ") + j += 1 + print() + i += 1 + +# Prime numbers up to n +print("\n=== Prime Numbers (2-30) ===") +for num in range(2, 31): + is_prime = True + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + is_prime = False + break + if is_prime: + print(num, end=" ") +print() diff --git a/04_Loops/05_loop_control.py b/04_Loops/05_loop_control.py new file mode 100644 index 0000000..6f52273 --- /dev/null +++ b/04_Loops/05_loop_control.py @@ -0,0 +1,208 @@ +""" +Loop Control Statements in Python +================================== +This program demonstrates break, continue, and pass statements. +""" + +# break statement - exits the loop immediately +print("=== BREAK Statement ===") +print("Finding first number divisible by 7:") +for num in range(1, 20): + if num % 7 == 0: + print(f"Found: {num}") + break # Exit loop when found + print(f"Checking: {num}") + +# break in while loop +print("\n=== BREAK in While Loop ===") +count = 0 +while True: # Infinite loop + count += 1 + print(f"Count: {count}") + if count >= 5: + print("Limit reached!") + break # Exit the infinite loop + +# Search in a list +print("\n=== Searching in a List ===") +names = ["Alice", "Bob", "Charlie", "Diana", "Eve"] +search_name = "Charlie" + +for name in names: + if name == search_name: + print(f"Found '{search_name}'!") + break +else: + # This runs only if break was NOT called + print(f"'{search_name}' not found") + +# continue statement - skips current iteration +print("\n=== CONTINUE Statement ===") +print("Printing odd numbers (1-10):") +for num in range(1, 11): + if num % 2 == 0: + continue # Skip even numbers + print(num, end=" ") +print() + +# Skip specific values +print("\n=== Skipping Specific Values ===") +for i in range(1, 11): + if i == 5: + continue # Skip 5 + print(i, end=" ") +print() + +# Filtering with continue +print("\n=== Filtering Positive Numbers ===") +numbers = [12, -5, 8, -3, 15, -7, 20] +print(f"Original list: {numbers}") +print("Positive numbers:", end=" ") +for num in numbers: + if num < 0: + continue # Skip negative numbers + print(num, end=" ") +print() + +# pass statement - does nothing (placeholder) +print("\n=== PASS Statement ===") +for i in range(5): + if i == 2: + pass # Placeholder - do nothing special + print(f"Number: {i}") + +# Using pass in functions (placeholder for future code) +print("\n=== Pass in Function Definition ===") +def future_feature(): + pass # Will implement later + +future_feature() +print("Function with pass executed (did nothing)") + +# Pass in exception handling +print("\n=== Pass in Exception Handling ===") +numbers = [1, 2, 0, 4, 5] +for num in numbers: + try: + result = 10 / num + print(f"10 / {num} = {result}") + except ZeroDivisionError: + pass # Ignore division by zero + +# break with nested loops +print("\n=== Break in Nested Loops ===") +print("Finding first pair that multiplies to 20:") +found = False +for i in range(1, 10): + for j in range(1, 10): + if i * j == 20: + print(f"Found: {i} Γ— {j} = 20") + found = True + break + if found: + break # Break outer loop too + +# continue in nested loops +print("\n=== Continue in Nested Loops ===") +print("Multiplication table skipping multiples of 5:") +for i in range(1, 6): + for j in range(1, 6): + product = i * j + if product % 5 == 0: + continue # Skip multiples of 5 + print(f"{i}Γ—{j}={product}", end=" ") + print() + +# for-else and while-else +print("\n=== for-else Statement ===") +numbers = [2, 4, 6, 8, 10] +for num in numbers: + if num % 2 != 0: + print(f"Found odd number: {num}") + break +else: + # Executes only if loop completed without break + print("All numbers are even!") + +# while-else example +print("\n=== while-else Statement ===") +count = 0 +while count < 5: + print(count, end=" ") + count += 1 +else: + # Executes when while condition becomes False + print("\nLoop completed normally!") + +# Practical: Password validator +print("\n=== Password Validator ===") +passwords = ["pass", "python123", "short", "validpass"] +min_length = 8 + +for password in passwords: + if len(password) < min_length: + print(f"'{password}' - Too short, skipped") + continue + if "admin" in password: + print(f"'{password}' - Contains 'admin', rejected") + break + print(f"'{password}' - Valid!") + +# Filtering and processing +print("\n=== Processing Scores ===") +scores = [45, 78, 92, 34, 88, 55, 67] +print(f"Original scores: {scores}") +print("\nProcessing:") +for score in scores: + if score < 50: + print(f" {score} - Failed (skipping)") + continue + if score >= 90: + print(f" {score} - Excellent!") + elif score >= 70: + print(f" {score} - Good") + else: + print(f" {score} - Pass") + +# Menu with break +print("\n=== Menu System (Simulated) ===") +menu_choices = [1, 2, 4, 3] # Simulated inputs + +for choice in menu_choices: + print(f"\n--- Menu ---") + print("1. View Profile") + print("2. Edit Profile") + print("3. Exit") + print(f"Choice: {choice}") + + if choice == 1: + print("Viewing profile...") + elif choice == 2: + print("Editing profile...") + elif choice == 3: + print("Exiting...") + break + else: + print("Invalid choice, try again") + continue + +# Skip printing specific characters +print("\n=== Skipping Vowels ===") +text = "Hello World" +print(f"Original: {text}") +print("Without vowels: ", end="") +for char in text: + if char.lower() in 'aeiou': + continue + print(char, end="") +print() + +# Finding and stopping +print("\n=== Finding Negative Number ===") +numbers = [10, 20, -5, 30, 40] +for i, num in enumerate(numbers): + if num < 0: + print(f"First negative number at index {i}: {num}") + break +else: + print("No negative numbers found") diff --git a/04_Loops/06_practical_examples.py b/04_Loops/06_practical_examples.py new file mode 100644 index 0000000..35851e8 --- /dev/null +++ b/04_Loops/06_practical_examples.py @@ -0,0 +1,257 @@ +""" +Practical Loop Examples +======================== +This program contains real-world applications of loops. +""" + +# Example 1: Grade Calculator for Multiple Students +print("=== GRADE CALCULATOR ===") +students = [ + {"name": "Alice", "marks": 85}, + {"name": "Bob", "marks": 92}, + {"name": "Charlie", "marks": 78}, + {"name": "Diana", "marks": 65}, + {"name": "Eve", "marks": 45} +] + +print(f"{'Name':<12} {'Marks':<8} {'Grade':<8} {'Status'}") +print("-" * 40) + +for student in students: + marks = student["marks"] + + if marks >= 90: + grade = "A" + elif marks >= 80: + grade = "B" + elif marks >= 70: + grade = "C" + elif marks >= 60: + grade = "D" + elif marks >= 50: + grade = "E" + else: + grade = "F" + + status = "Pass" if marks >= 50 else "Fail" + print(f"{student['name']:<12} {marks:<8} {grade:<8} {status}") + +# Example 2: Shopping Cart Total +print("\n=== SHOPPING CART ===") +cart = [ + {"item": "Laptop", "price": 899.99, "quantity": 1}, + {"item": "Mouse", "price": 25.50, "quantity": 2}, + {"item": "Keyboard", "price": 75.00, "quantity": 1}, + {"item": "USB Cable", "price": 10.99, "quantity": 3} +] + +print(f"{'Item':<15} {'Price':<10} {'Qty':<5} {'Total'}") +print("-" * 40) + +subtotal = 0 +for item in cart: + item_total = item["price"] * item["quantity"] + subtotal += item_total + print(f"{item['item']:<15} ${item['price']:<9.2f} {item['quantity']:<5} ${item_total:.2f}") + +tax = subtotal * 0.08 # 8% tax +total = subtotal + tax + +print("-" * 40) +print(f"{'Subtotal:':<30} ${subtotal:.2f}") +print(f"{'Tax (8%):':<30} ${tax:.2f}") +print(f"{'Total:':<30} ${total:.2f}") + +# Example 3: Attendance Tracker +print("\n=== ATTENDANCE TRACKER ===") +attendance = { + "Monday": True, + "Tuesday": True, + "Wednesday": False, + "Thursday": True, + "Friday": False +} + +present_days = 0 +total_days = 0 + +for day, status in attendance.items(): + total_days += 1 + if status: + present_days += 1 + print(f"{day:<10} - Present βœ“") + else: + print(f"{day:<10} - Absent βœ—") + +percentage = (present_days / total_days) * 100 +print(f"\nAttendance: {present_days}/{total_days} days ({percentage:.1f}%)") + +if percentage >= 75: + print("Status: Good attendance! βœ“") +else: + print("Status: Low attendance! βœ—") + +# Example 4: Password Generator +print("\n=== SIMPLE PASSWORD GENERATOR ===") +import random +random.seed(42) # For consistent output + +lowercase = "abcdefghijklmnopqrstuvwxyz" +uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +digits = "0123456789" +symbols = "!@#$%^&*" + +all_chars = lowercase + uppercase + digits + symbols +password_length = 12 + +password = "" +for i in range(password_length): + password += random.choice(all_chars) + +print(f"Generated password: {password}") + +# Example 5: Prime Number Finder +print("\n=== PRIME NUMBERS (2-50) ===") +primes = [] + +for num in range(2, 51): + is_prime = True + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + is_prime = False + break + if is_prime: + primes.append(num) + +print("Prime numbers:", primes) +print(f"Count: {len(primes)}") + +# Example 6: Word Frequency Counter +print("\n=== WORD FREQUENCY COUNTER ===") +text = "python is great and python is powerful python is easy" +words = text.split() +word_count = {} + +for word in words: + if word in word_count: + word_count[word] += 1 + else: + word_count[word] = 1 + +print("Word frequencies:") +for word, count in word_count.items(): + print(f" '{word}': {count}") + +# Example 7: Fibonacci Sequence Generator +print("\n=== FIBONACCI SEQUENCE (first 15 terms) ===") +n = 15 +fib = [0, 1] + +for i in range(2, n): + next_num = fib[i-1] + fib[i-2] + fib.append(next_num) + +print("Fibonacci sequence:") +for i, num in enumerate(fib): + print(f"F({i}) = {num}") + +# Example 8: Temperature Converter +print("\n=== TEMPERATURE CONVERSION TABLE ===") +print(f"{'Celsius':>8} {'Fahrenheit':>12} {'Kelvin':>10}") +print("-" * 32) + +for celsius in range(0, 101, 10): + fahrenheit = (celsius * 9/5) + 32 + kelvin = celsius + 273.15 + print(f"{celsius:>8}Β°C {fahrenheit:>11.1f}Β°F {kelvin:>9.2f}K") + +# Example 9: Pattern Matcher +print("\n=== EMAIL VALIDATOR ===") +emails = [ + "user@example.com", + "invalid.email", + "test@domain.org", + "no-at-sign.com", + "valid@test.co" +] + +valid_count = 0 +for email in emails: + if "@" in email and "." in email.split("@")[1]: + print(f"βœ“ {email} - Valid") + valid_count += 1 + else: + print(f"βœ— {email} - Invalid") + +print(f"\nValid emails: {valid_count}/{len(emails)}") + +# Example 10: Sum and Average Calculator +print("\n=== STATISTICS CALCULATOR ===") +numbers = [45, 67, 23, 89, 12, 56, 78, 34, 91, 25] + +total_sum = 0 +count = 0 +maximum = numbers[0] +minimum = numbers[0] + +for num in numbers: + total_sum += num + count += 1 + if num > maximum: + maximum = num + if num < minimum: + minimum = num + +average = total_sum / count + +print(f"Numbers: {numbers}") +print(f"Count: {count}") +print(f"Sum: {total_sum}") +print(f"Average: {average:.2f}") +print(f"Maximum: {maximum}") +print(f"Minimum: {minimum}") +print(f"Range: {maximum - minimum}") + +# Example 11: Character Counter +print("\n=== CHARACTER STATISTICS ===") +text = "Hello, Python World!" +vowels = "aeiouAEIOU" +consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" + +vowel_count = 0 +consonant_count = 0 +digit_count = 0 +space_count = 0 +special_count = 0 + +for char in text: + if char in vowels: + vowel_count += 1 + elif char in consonants: + consonant_count += 1 + elif char.isdigit(): + digit_count += 1 + elif char.isspace(): + space_count += 1 + else: + special_count += 1 + +print(f"Text: '{text}'") +print(f"Vowels: {vowel_count}") +print(f"Consonants: {consonant_count}") +print(f"Digits: {digit_count}") +print(f"Spaces: {space_count}") +print(f"Special characters: {special_count}") +print(f"Total characters: {len(text)}") + +# Example 12: Simple Progress Bar +print("\n=== PROGRESS BAR SIMULATION ===") +total_tasks = 20 +for i in range(total_tasks + 1): + percentage = (i / total_tasks) * 100 + filled = int(percentage / 5) + bar = "β–ˆ" * filled + "-" * (20 - filled) + # Showing progress at key milestones for better performance + if i % 5 == 0 or i == total_tasks: + print(f"Progress: [{bar}] {percentage:.0f}%") +print("Complete!") diff --git a/04_Loops/README.md b/04_Loops/README.md new file mode 100644 index 0000000..19c3fd1 --- /dev/null +++ b/04_Loops/README.md @@ -0,0 +1,70 @@ +# Loops in Python πŸ” + +## What are Loops? + +Loops allow you to repeat a block of code multiple times. Instead of writing the same code again and again, you can use loops to automate repetitive tasks. + +## Types of Loops in Python + +### 1. **for Loop** +Used when you know how many times you want to repeat something +```python +for i in range(5): + print(i) +``` + +### 2. **while Loop** +Used when you want to repeat until a condition becomes False +```python +count = 0 +while count < 5: + print(count) + count += 1 +``` + +## Loop Control Statements + +- **break**: Exit the loop immediately +- **continue**: Skip the current iteration and move to the next +- **pass**: Do nothing (placeholder) + +## Common Loop Patterns + +### Range Function +```python +range(5) # 0, 1, 2, 3, 4 +range(1, 6) # 1, 2, 3, 4, 5 +range(0, 10, 2) # 0, 2, 4, 6, 8 +``` + +### Looping Through Collections +```python +# List +for item in [1, 2, 3]: + print(item) + +# String +for char in "hello": + print(char) +``` + +## Examples in This Folder + +1. **01_basic_for_loop.py** - Introduction to for loops +2. **02_range_function.py** - Using range() function +3. **03_while_loop.py** - Understanding while loops +4. **04_nested_loops.py** - Loops inside loops +5. **05_loop_control.py** - break, continue, pass statements +6. **06_practical_examples.py** - Real-world loop applications + +## Tips for Beginners + +- Use **for loops** when you know the number of iterations +- Use **while loops** when the number of iterations depends on a condition +- Always make sure while loops have a way to end (avoid infinite loops) +- Use meaningful variable names in loops (instead of just `i`) +- Remember proper indentation! + +## Practice + +Try modifying the loop ranges and conditions to see different outputs! diff --git a/05_Functions/01_basic_functions.py b/05_Functions/01_basic_functions.py new file mode 100644 index 0000000..53ebc83 --- /dev/null +++ b/05_Functions/01_basic_functions.py @@ -0,0 +1,203 @@ +""" +Basic Functions in Python +========================== +This program demonstrates how to create and use functions. +""" + +# Simple function without parameters +def greet(): + """Prints a greeting message""" + print("Hello, World!") + +print("=== Simple Function ===") +greet() # Call the function + +# Function called multiple times +print("\n=== Calling Function Multiple Times ===") +def say_hello(): + print("Hello!") + +say_hello() +say_hello() +say_hello() + +# Function with a parameter +print("\n=== Function with Parameter ===") +def greet_person(name): + """Greets a person by name""" + print(f"Hello, {name}!") + +greet_person("Alice") +greet_person("Bob") +greet_person("Charlie") + +# Function with multiple parameters +print("\n=== Multiple Parameters ===") +def introduce(name, age): + """Introduces a person with name and age""" + print(f"My name is {name} and I am {age} years old.") + +introduce("Alice", 20) +introduce("Bob", 22) + +# Function with calculation +print("\n=== Function with Calculation ===") +def calculate_square(number): + """Calculates the square of a number""" + square = number ** 2 + print(f"The square of {number} is {square}") + +calculate_square(5) +calculate_square(10) +calculate_square(7) + +# Function that prints a pattern +print("\n=== Function for Pattern ===") +def print_stars(count): + """Prints a line of stars""" + print("*" * count) + +print_stars(5) +print_stars(10) +print_stars(3) + +# Function with return value +print("\n=== Function with Return ===") +def add_numbers(a, b): + """Returns the sum of two numbers""" + return a + b + +result1 = add_numbers(5, 3) +result2 = add_numbers(10, 20) + +print(f"5 + 3 = {result1}") +print(f"10 + 20 = {result2}") + +# Using return value in expressions +total = add_numbers(15, 25) + add_numbers(10, 5) +print(f"(15 + 25) + (10 + 5) = {total}") + +# Function with multiple operations +print("\n=== Calculator Functions ===") +def add(a, b): + return a + b + +def subtract(a, b): + return a - b + +def multiply(a, b): + return a * b + +def divide(a, b): + if b != 0: + return a / b + else: + return "Cannot divide by zero" + +x, y = 10, 5 +print(f"{x} + {y} = {add(x, y)}") +print(f"{x} - {y} = {subtract(x, y)}") +print(f"{x} * {y} = {multiply(x, y)}") +print(f"{x} / {y} = {divide(x, y)}") + +# Function with conditional logic +print("\n=== Function with Conditions ===") +def check_even_odd(number): + """Checks if a number is even or odd""" + if number % 2 == 0: + return "Even" + else: + return "Odd" + +print(f"7 is {check_even_odd(7)}") +print(f"10 is {check_even_odd(10)}") +print(f"15 is {check_even_odd(15)}") + +# Function with loop +print("\n=== Function with Loop ===") +def print_numbers(n): + """Prints numbers from 1 to n""" + for i in range(1, n + 1): + print(i, end=" ") + print() + +print("Numbers 1 to 5:") +print_numbers(5) +print("Numbers 1 to 10:") +print_numbers(10) + +# Function returning maximum +print("\n=== Finding Maximum ===") +def find_max(a, b): + """Returns the larger of two numbers""" + if a > b: + return a + else: + return b + +print(f"Max of 15 and 20: {find_max(15, 20)}") +print(f"Max of 50 and 30: {find_max(50, 30)}") + +# Function with list parameter +print("\n=== Function with List ===") +def print_list(items): + """Prints all items in a list""" + for item in items: + print(f" - {item}") + +fruits = ["apple", "banana", "orange"] +print("Fruits:") +print_list(fruits) + +numbers = [1, 2, 3, 4, 5] +print("\nNumbers:") +print_list(numbers) + +# Function returning sum of list +print("\n=== Sum of List ===") +def calculate_sum(numbers): + """Returns the sum of numbers in a list""" + total = 0 + for num in numbers: + total += num + return total + +my_numbers = [10, 20, 30, 40, 50] +print(f"Numbers: {my_numbers}") +print(f"Sum: {calculate_sum(my_numbers)}") + +# Docstrings +print("\n=== Function Docstrings ===") +def example_function(param): + """ + This is a docstring. + It explains what the function does. + + Parameters: + param: Description of parameter + + Returns: + Description of return value + """ + return param * 2 + +print("Function name:", example_function.__name__) +print("Function docstring:", example_function.__doc__) + +# Multiple functions working together +print("\n=== Functions Working Together ===") +def celsius_to_fahrenheit(celsius): + """Converts Celsius to Fahrenheit""" + return (celsius * 9/5) + 32 + +def fahrenheit_to_celsius(fahrenheit): + """Converts Fahrenheit to Celsius""" + return (fahrenheit - 32) * 5/9 + +temp_c = 25 +temp_f = celsius_to_fahrenheit(temp_c) +print(f"{temp_c}Β°C = {temp_f}Β°F") + +temp_f = 77 +temp_c = fahrenheit_to_celsius(temp_f) +print(f"{temp_f}Β°F = {temp_c}Β°C") diff --git a/05_Functions/02_parameters_arguments.py b/05_Functions/02_parameters_arguments.py new file mode 100644 index 0000000..e249bc1 --- /dev/null +++ b/05_Functions/02_parameters_arguments.py @@ -0,0 +1,186 @@ +""" +Parameters and Arguments in Python +=================================== +This program demonstrates different ways to pass arguments to functions. +""" + +# Positional arguments - order matters +print("=== Positional Arguments ===") +def introduce(name, age, city): + print(f"I am {name}, {age} years old, from {city}") + +introduce("Alice", 20, "New York") +introduce("Bob", 22, "London") + +# Keyword arguments - order doesn't matter +print("\n=== Keyword Arguments ===") +introduce(age=25, name="Charlie", city="Paris") +introduce(city="Tokyo", age=30, name="Diana") + +# Mixing positional and keyword arguments +print("\n=== Mixed Arguments ===") +introduce("Eve", age=28, city="Berlin") +# introduce(name="Frank", 35, "Rome") # Error: positional after keyword + +# Default parameters +print("\n=== Default Parameters ===") +def greet(name, message="Hello"): + print(f"{message}, {name}!") + +greet("Alice") # Uses default message +greet("Bob", "Hi") # Custom message +greet("Charlie", message="Hey") # Keyword argument + +# Multiple default parameters +print("\n=== Multiple Defaults ===") +def create_profile(name, age=18, country="USA"): + print(f"Name: {name}, Age: {age}, Country: {country}") + +create_profile("Alice") +create_profile("Bob", 25) +create_profile("Charlie", 30, "Canada") +create_profile("Diana", country="UK") + +# Function with calculations +print("\n=== Area Calculations ===") +def calculate_rectangle_area(length, width): + """Calculate area of rectangle""" + area = length * width + return area + +def calculate_circle_area(radius, pi=3.14159): + """Calculate area of circle""" + area = pi * radius ** 2 + return area + +rect_area = calculate_rectangle_area(5, 3) +print(f"Rectangle (5Γ—3) area: {rect_area}") + +circle_area = calculate_circle_area(7) +print(f"Circle (radius 7) area: {circle_area:.2f}") + +circle_area_precise = calculate_circle_area(7, pi=3.14159265359) +print(f"Circle (precise) area: {circle_area_precise:.2f}") + +# Variable number of arguments (*args) +print("\n=== Variable Arguments (*args) ===") +def sum_all(*numbers): + """Sum any number of arguments""" + total = 0 + for num in numbers: + total += num + return total + +print(f"Sum of 1, 2, 3: {sum_all(1, 2, 3)}") +print(f"Sum of 10, 20, 30, 40: {sum_all(10, 20, 30, 40)}") +print(f"Sum of 5: {sum_all(5)}") + +# *args with other parameters +print("\n=== *args with Regular Parameters ===") +def make_sentence(prefix, *words): + """Creates a sentence with a prefix""" + sentence = prefix + " " + " ".join(words) + return sentence + +print(make_sentence("Hello:", "Python", "is", "awesome")) +print(make_sentence("I", "love", "programming")) + +# Keyword arguments (**kwargs) +print("\n=== Keyword Arguments (**kwargs) ===") +def print_info(**info): + """Print key-value pairs""" + for key, value in info.items(): + print(f"{key}: {value}") + +print("Student Info:") +print_info(name="Alice", age=20, grade="A", city="New York") + +print("\nBook Info:") +print_info(title="Python Guide", author="John Doe", year=2024) + +# Combining *args and **kwargs +print("\n=== Combining *args and **kwargs ===") +def flexible_function(*args, **kwargs): + """Accepts any number of positional and keyword arguments""" + print("Positional arguments:") + for i, arg in enumerate(args, 1): + print(f" {i}. {arg}") + + print("Keyword arguments:") + for key, value in kwargs.items(): + print(f" {key} = {value}") + +flexible_function(1, 2, 3, name="Alice", age=20) + +# Practical: Student grade calculator +print("\n=== Student Grade Calculator ===") +def calculate_grade(name, *scores, bonus=0): + """Calculate average grade with optional bonus""" + if len(scores) == 0: + return f"{name}: No scores provided" + + average = sum(scores) / len(scores) + bonus + return f"{name}: Average = {average:.2f}" + +print(calculate_grade("Alice", 85, 90, 88)) +print(calculate_grade("Bob", 75, 80, 70, bonus=5)) +print(calculate_grade("Charlie", 95, 92, 98, 90)) + +# Function with list as parameter +print("\n=== List as Parameter ===") +def find_max_min(numbers): + """Find maximum and minimum in a list""" + if not numbers: + return None, None + return max(numbers), min(numbers) + +nums = [45, 23, 67, 89, 12, 34] +maximum, minimum = find_max_min(nums) +print(f"Numbers: {nums}") +print(f"Max: {maximum}, Min: {minimum}") + +# Mutable default argument (be careful!) +print("\n=== Mutable Default Arguments ===") +def add_item(item, items=None): + """Correct way to handle mutable defaults""" + if items is None: + items = [] + items.append(item) + return items + +list1 = add_item("apple") +list2 = add_item("banana") +print(f"List 1: {list1}") +print(f"List 2: {list2}") + +# Type hints (Python 3.5+) +print("\n=== Type Hints (Optional) ===") +def greet_with_types(name: str, age: int) -> str: + """Function with type hints""" + return f"Hello {name}, you are {age} years old" + +result = greet_with_types("Alice", 20) +print(result) + +# Practical: Format name +print("\n=== Name Formatter ===") +def format_name(first, last, middle=""): + """Format a person's name""" + if middle: + return f"{first} {middle} {last}" + return f"{first} {last}" + +print(format_name("John", "Doe")) +print(format_name("John", "Doe", "Paul")) +print(format_name("John", "Doe", middle="Smith")) + +# Unpacking arguments +print("\n=== Unpacking Arguments ===") +def display_coordinates(x, y, z): + print(f"Coordinates: ({x}, {y}, {z})") + +coords = [10, 20, 30] +display_coordinates(*coords) # Unpacking list + +point = {"x": 5, "y": 15, "z": 25} +display_coordinates(**point) # Unpacking dictionary diff --git a/05_Functions/03_return_values.py b/05_Functions/03_return_values.py new file mode 100644 index 0000000..5d67316 --- /dev/null +++ b/05_Functions/03_return_values.py @@ -0,0 +1,244 @@ +""" +Return Values in Python Functions +================================== +This program demonstrates different ways functions can return values. +""" + +# Simple return +print("=== Simple Return ===") +def square(number): + """Returns the square of a number""" + return number ** 2 + +result = square(5) +print(f"Square of 5: {result}") +print(f"Square of 8: {square(8)}") + +# Return with conditional +print("\n=== Return with Conditional ===") +def absolute_value(number): + """Returns absolute value of a number""" + if number < 0: + return -number + return number + +print(f"Absolute of -5: {absolute_value(-5)}") +print(f"Absolute of 10: {absolute_value(10)}") + +# Multiple return statements +print("\n=== Multiple Returns ===") +def grade_to_points(grade): + """Convert letter grade to points""" + if grade == "A": + return 4.0 + elif grade == "B": + return 3.0 + elif grade == "C": + return 2.0 + elif grade == "D": + return 1.0 + else: + return 0.0 + +print(f"Grade A: {grade_to_points('A')} points") +print(f"Grade B: {grade_to_points('B')} points") +print(f"Grade F: {grade_to_points('F')} points") + +# Returning multiple values (tuple) +print("\n=== Returning Multiple Values ===") +def get_circle_properties(radius): + """Returns area and circumference of a circle""" + pi = 3.14159 + area = pi * radius ** 2 + circumference = 2 * pi * radius + return area, circumference # Returns a tuple + +area, circumference = get_circle_properties(5) +print(f"Circle with radius 5:") +print(f" Area: {area:.2f}") +print(f" Circumference: {circumference:.2f}") + +# Returning a list +print("\n=== Returning a List ===") +def get_multiples(number, count): + """Returns first 'count' multiples of number""" + multiples = [] + for i in range(1, count + 1): + multiples.append(number * i) + return multiples + +result = get_multiples(5, 10) +print(f"First 10 multiples of 5: {result}") + +# Returning a dictionary +print("\n=== Returning a Dictionary ===") +def get_student_info(name, age, grade): + """Returns student information as a dictionary""" + return { + "name": name, + "age": age, + "grade": grade, + "status": "Pass" if grade != "F" else "Fail" + } + +student = get_student_info("Alice", 20, "A") +print(f"Student: {student}") + +# Return None (implicitly) +print("\n=== Return None ===") +def print_message(text): + """Prints message but doesn't return anything""" + print(f"Message: {text}") + # No return statement means returns None + +result = print_message("Hello") +print(f"Return value: {result}") + +# Explicit return None +def check_positive(number): + """Returns number if positive, None otherwise""" + if number > 0: + return number + return None + +print(f"Check 5: {check_positive(5)}") +print(f"Check -3: {check_positive(-3)}") + +# Early return +print("\n=== Early Return ===") +def divide(a, b): + """Divides a by b with error checking""" + if b == 0: + return "Error: Division by zero" + return a / b + +print(f"10 / 2 = {divide(10, 2)}") +print(f"10 / 0 = {divide(10, 0)}") + +# Returning boolean +print("\n=== Returning Boolean ===") +def is_even(number): + """Returns True if number is even""" + return number % 2 == 0 + +def is_prime(n): + """Returns True if number is prime""" + if n < 2: + return False + for i in range(2, int(n ** 0.5) + 1): + if n % i == 0: + return False + return True + +print(f"Is 10 even? {is_even(10)}") +print(f"Is 7 even? {is_even(7)}") +print(f"Is 17 prime? {is_prime(17)}") +print(f"Is 20 prime? {is_prime(20)}") + +# Using return value in conditions +print("\n=== Using Return in Conditions ===") +def check_password(password): + """Validates password strength""" + if len(password) < 8: + return False, "Too short" + if not any(c.isdigit() for c in password): + return False, "Needs a number" + if not any(c.isupper() for c in password): + return False, "Needs uppercase" + return True, "Strong password" + +passwords = ["short", "longpassword", "LongPassword1"] +for pwd in passwords: + valid, message = check_password(pwd) + status = "βœ“" if valid else "βœ—" + print(f"{status} '{pwd}': {message}") + +# Chaining function calls +print("\n=== Chaining Functions ===") +def double(x): + return x * 2 + +def add_ten(x): + return x + 10 + +number = 5 +result = add_ten(double(number)) # double(5) = 10, then add_ten(10) = 20 +print(f"double({number}) + 10 = {result}") + +# Returning calculation results +print("\n=== Statistics Calculator ===") +def calculate_stats(numbers): + """Returns multiple statistics""" + total = sum(numbers) + count = len(numbers) + average = total / count if count > 0 else 0 + maximum = max(numbers) if numbers else None + minimum = min(numbers) if numbers else None + + return { + "sum": total, + "count": count, + "average": average, + "max": maximum, + "min": minimum + } + +nums = [45, 67, 23, 89, 12, 56] +stats = calculate_stats(nums) +print(f"Numbers: {nums}") +print(f"Statistics: {stats}") + +# Practical: Grade calculator +print("\n=== Grade Calculator ===") +def calculate_final_grade(*scores): + """Calculate average and assign letter grade""" + if not scores: + return None, "No scores" + + average = sum(scores) / len(scores) + + if average >= 90: + letter = "A" + elif average >= 80: + letter = "B" + elif average >= 70: + letter = "C" + elif average >= 60: + letter = "D" + else: + letter = "F" + + return average, letter + +avg, grade = calculate_final_grade(85, 90, 88, 92) +print(f"Average: {avg:.2f}, Grade: {grade}") + +# Returning nested structures +print("\n=== Returning Nested Structures ===") +def analyze_text(text): + """Analyzes text and returns detailed statistics""" + words = text.split() + return { + "char_count": len(text), + "word_count": len(words), + "words": { + "first": words[0] if words else None, + "last": words[-1] if words else None, + "longest": max(words, key=len) if words else None + } + } + +text = "Python programming is fun and powerful" +analysis = analyze_text(text) +print(f"Text: '{text}'") +print(f"Analysis: {analysis}") + +# Lambda with return +print("\n=== Lambda Functions (Inline Returns) ===") +square_lambda = lambda x: x ** 2 +add_lambda = lambda a, b: a + b +max_lambda = lambda a, b: a if a > b else b + +print(f"Square of 6: {square_lambda(6)}") +print(f"Add 3 + 7: {add_lambda(3, 7)}") +print(f"Max of 15, 10: {max_lambda(15, 10)}") diff --git a/05_Functions/04_scope.py b/05_Functions/04_scope.py new file mode 100644 index 0000000..6d596c1 --- /dev/null +++ b/05_Functions/04_scope.py @@ -0,0 +1,247 @@ +""" +Variable Scope in Python +========================= +This program demonstrates local and global variable scope. +""" + +# Global variable +global_var = "I am global" + +print("=== Global Variable ===") +def show_global(): + """Access global variable""" + print(f"Inside function: {global_var}") + +print(f"Outside function: {global_var}") +show_global() + +# Local variable +print("\n=== Local Variable ===") +def show_local(): + """Create and use local variable""" + local_var = "I am local" + print(f"Inside function: {local_var}") + +show_local() +# print(local_var) # Error: local_var not defined outside function + +# Local vs Global with same name +print("\n=== Local vs Global with Same Name ===") +x = "global x" + +def test_scope(): + x = "local x" # This is a different variable + print(f"Inside function: {x}") + +print(f"Before function: {x}") +test_scope() +print(f"After function: {x}") # Global x unchanged + +# Using global keyword +print("\n=== Modifying Global Variable ===") +counter = 0 + +def increment(): + global counter # Declare we want to use global variable + counter += 1 + print(f"Counter inside: {counter}") + +print(f"Initial counter: {counter}") +increment() +increment() +increment() +print(f"Final counter: {counter}") + +# Multiple global variables +print("\n=== Multiple Global Variables ===") +name = "Alice" +age = 20 + +def update_info(): + global name, age + name = "Bob" + age = 25 + print(f"Updated: {name}, {age}") + +print(f"Before: {name}, {age}") +update_info() +print(f"After: {name}, {age}") + +# Function parameters are local +print("\n=== Parameters are Local ===") +def greet(name): + """Parameter 'name' is local to this function""" + name = name.upper() # Modifies local copy + print(f"Inside: {name}") + +person = "alice" +print(f"Before: {person}") +greet(person) +print(f"After: {person}") # Unchanged + +# Nested function scope +print("\n=== Nested Function Scope ===") +def outer(): + outer_var = "I'm in outer" + + def inner(): + # Can access outer function's variables + print(f"Inner accessing: {outer_var}") + + print(f"Outer: {outer_var}") + inner() + +outer() + +# nonlocal keyword +print("\n=== Nonlocal Keyword ===") +def outer_function(): + count = 0 + + def inner_function(): + nonlocal count # Access outer function's variable + count += 1 + print(f"Count: {count}") + + inner_function() + inner_function() + inner_function() + print(f"Final count: {count}") + +outer_function() + +# Constants (convention: UPPERCASE) +print("\n=== Constants ===") +PI = 3.14159 +MAX_SIZE = 100 +APP_NAME = "MyApp" + +def calculate_circle_area(radius): + """Uses global constant PI""" + return PI * radius ** 2 + +print(f"Circle area (r=5): {calculate_circle_area(5):.2f}") +print(f"Max size: {MAX_SIZE}") + +# Scope resolution order +print("\n=== Scope Resolution (LEGB Rule) ===") +# LEGB: Local -> Enclosing -> Global -> Built-in + +x = "global" + +def outer(): + x = "enclosing" + + def inner(): + x = "local" + print(f"Inner x: {x}") # Local + + inner() + print(f"Outer x: {x}") # Enclosing + +print(f"Global x: {x}") # Global +outer() + +# Built-in scope example +print("\n=== Built-in Scope ===") +# 'len' is a built-in function +my_list = [1, 2, 3, 4, 5] +print(f"Length: {len(my_list)}") + +# Don't shadow built-ins! +def bad_example(): + len = 10 # Bad: shadows built-in function + print(f"Local len: {len}") + # print(len([1, 2, 3])) # Error: len is now an integer + +bad_example() +print(f"Global len still works: {len([1, 2, 3])}") + +# Practical: Counter with closure +print("\n=== Practical: Counter ===") +def create_counter(): + """Creates a counter function using closure""" + count = 0 + + def increment(): + nonlocal count + count += 1 + return count + + return increment + +counter1 = create_counter() +counter2 = create_counter() + +print(f"Counter 1: {counter1()}") # 1 +print(f"Counter 1: {counter1()}") # 2 +print(f"Counter 2: {counter2()}") # 1 (separate counter) +print(f"Counter 1: {counter1()}") # 3 + +# Practical: Configuration +print("\n=== Configuration Variables ===") +# Global configuration +DEBUG = True +MAX_RETRIES = 3 + +def process_data(data): + """Uses global configuration""" + if DEBUG: + print(f"[DEBUG] Processing: {data}") + + retries = 0 + while retries < MAX_RETRIES: + # Simulated processing + if data: # Success condition + return f"Processed: {data}" + retries += 1 + + return "Failed after retries" + +result = process_data("sample data") +print(result) + +# Variable lifetime +print("\n=== Variable Lifetime ===") +def demonstrate_lifetime(): + """Local variables exist only during function execution""" + temp = "I exist only during function call" + print(temp) + # 'temp' is destroyed when function ends + +demonstrate_lifetime() +demonstrate_lifetime() # New 'temp' created each time + +# Global mutable objects +print("\n=== Global Mutable Objects ===") +scores = [85, 90, 78] + +def add_score(score): + """Can modify mutable global objects without 'global' keyword""" + scores.append(score) # Modifying list contents + print(f"Scores: {scores}") + +print(f"Initial: {scores}") +add_score(92) +add_score(88) +print(f"Final: {scores}") + +# Best practices +print("\n=== Best Practices ===") +# Good: Pass values as parameters, return results +def calculate_total(items): + """Pure function - doesn't depend on global state""" + return sum(items) + +# Good: Return value instead of modifying global +def add_item_good(items, new_item): + """Returns new list instead of modifying global""" + return items + [new_item] + +numbers = [1, 2, 3] +total = calculate_total(numbers) +new_numbers = add_item_good(numbers, 4) + +print(f"Total: {total}") +print(f"Original: {numbers}") +print(f"New list: {new_numbers}") diff --git a/05_Functions/05_practical_examples.py b/05_Functions/05_practical_examples.py new file mode 100644 index 0000000..2457b37 --- /dev/null +++ b/05_Functions/05_practical_examples.py @@ -0,0 +1,275 @@ +""" +Practical Function Examples +============================ +This program contains real-world applications of functions. +""" + +# Example 1: Temperature Converter +print("=== TEMPERATURE CONVERTER ===") +def celsius_to_fahrenheit(celsius): + """Convert Celsius to Fahrenheit""" + return (celsius * 9/5) + 32 + +def fahrenheit_to_celsius(fahrenheit): + """Convert Fahrenheit to Celsius""" + return (fahrenheit - 32) * 5/9 + +def celsius_to_kelvin(celsius): + """Convert Celsius to Kelvin""" + return celsius + 273.15 + +temp_c = 25 +print(f"{temp_c}Β°C = {celsius_to_fahrenheit(temp_c):.1f}Β°F") +print(f"{temp_c}Β°C = {celsius_to_kelvin(temp_c):.2f}K") + +# Example 2: Password Validator +print("\n=== PASSWORD VALIDATOR ===") +def validate_password(password): + """Validate password strength""" + if len(password) < 8: + return False, "Password must be at least 8 characters" + if not any(c.isupper() for c in password): + return False, "Password must contain uppercase letter" + if not any(c.islower() for c in password): + return False, "Password must contain lowercase letter" + if not any(c.isdigit() for c in password): + return False, "Password must contain a number" + return True, "Password is strong" + +test_passwords = ["weak", "NoNumbers", "nonumbers1", "GoodPass123"] +for pwd in test_passwords: + valid, message = validate_password(pwd) + status = "βœ“" if valid else "βœ—" + print(f"{status} '{pwd}': {message}") + +# Example 3: Grade Calculator +print("\n=== GRADE CALCULATOR ===") +def calculate_grade(scores): + """Calculate average and letter grade""" + if not scores: + return None, "N/A" + + average = sum(scores) / len(scores) + + if average >= 90: + letter = "A" + elif average >= 80: + letter = "B" + elif average >= 70: + letter = "C" + elif average >= 60: + letter = "D" + else: + letter = "F" + + return average, letter + +students = [ + ("Alice", [85, 90, 88, 92]), + ("Bob", [78, 82, 75, 80]), + ("Charlie", [92, 95, 98, 94]) +] + +print(f"{'Name':<10} {'Average':<10} {'Grade'}") +print("-" * 30) +for name, scores in students: + avg, grade = calculate_grade(scores) + print(f"{name:<10} {avg:<10.2f} {grade}") + +# Example 4: Factorial Calculator +print("\n=== FACTORIAL CALCULATOR ===") +def factorial(n): + """Calculate factorial of n""" + if n < 0: + return None + if n == 0 or n == 1: + return 1 + + result = 1 + for i in range(2, n + 1): + result *= i + return result + +for num in [0, 1, 5, 10]: + print(f"{num}! = {factorial(num)}") + +# Example 5: Palindrome Checker +print("\n=== PALINDROME CHECKER ===") +def is_palindrome(text): + """Check if text is a palindrome""" + # Remove spaces and convert to lowercase + cleaned = text.replace(" ", "").lower() + return cleaned == cleaned[::-1] + +words = ["racecar", "hello", "level", "python", "A man a plan a canal Panama"] +for word in words: + result = "is" if is_palindrome(word) else "is not" + print(f"'{word}' {result} a palindrome") + +# Example 6: Prime Number Checker +print("\n=== PRIME NUMBER CHECKER ===") +def is_prime(n): + """Check if number is prime""" + if n < 2: + return False + for i in range(2, int(n ** 0.5) + 1): + if n % i == 0: + return False + return True + +def get_primes(start, end): + """Get all prime numbers in range""" + primes = [] + for num in range(start, end + 1): + if is_prime(num): + primes.append(num) + return primes + +primes = get_primes(1, 30) +print(f"Prime numbers (1-30): {primes}") + +# Example 7: Shopping Cart +print("\n=== SHOPPING CART ===") +def calculate_total(items, tax_rate=0.08): + """Calculate total with tax""" + subtotal = sum(item['price'] * item['quantity'] for item in items) + tax = subtotal * tax_rate + total = subtotal + tax + return subtotal, tax, total + +cart = [ + {"name": "Book", "price": 15.99, "quantity": 2}, + {"name": "Pen", "price": 2.50, "quantity": 5}, + {"name": "Notebook", "price": 5.99, "quantity": 3} +] + +subtotal, tax, total = calculate_total(cart) +print(f"Subtotal: ${subtotal:.2f}") +print(f"Tax (8%): ${tax:.2f}") +print(f"Total: ${total:.2f}") + +# Example 8: List Statistics +print("\n=== LIST STATISTICS ===") +def get_statistics(numbers): + """Calculate various statistics""" + if not numbers: + return None + + return { + "count": len(numbers), + "sum": sum(numbers), + "average": sum(numbers) / len(numbers), + "min": min(numbers), + "max": max(numbers), + "range": max(numbers) - min(numbers) + } + +data = [45, 67, 23, 89, 12, 56, 78] +stats = get_statistics(data) +print(f"Data: {data}") +for key, value in stats.items(): + if isinstance(value, float): + print(f"{key.capitalize()}: {value:.2f}") + else: + print(f"{key.capitalize()}: {value}") + +# Example 9: String Formatter +print("\n=== STRING FORMATTER ===") +def format_name(first, last, middle=None, title=None): + """Format a person's name""" + parts = [] + if title: + parts.append(title) + parts.append(first) + if middle: + parts.append(middle) + parts.append(last) + return " ".join(parts) + +print(format_name("John", "Doe")) +print(format_name("John", "Doe", middle="Paul")) +print(format_name("John", "Doe", title="Dr.")) +print(format_name("John", "Doe", middle="Paul", title="Prof.")) + +# Example 10: Fibonacci Generator +print("\n=== FIBONACCI SEQUENCE ===") +def generate_fibonacci(n): + """Generate first n Fibonacci numbers""" + if n <= 0: + return [] + elif n == 1: + return [0] + + fib = [0, 1] + for i in range(2, n): + fib.append(fib[i-1] + fib[i-2]) + return fib + +fib_sequence = generate_fibonacci(10) +print(f"First 10 Fibonacci numbers: {fib_sequence}") + +# Example 11: Email Validator +print("\n=== EMAIL VALIDATOR ===") +def is_valid_email(email): + """Basic email validation""" + if "@" not in email: + return False, "Missing @ symbol" + + parts = email.split("@") + if len(parts) != 2: + return False, "Invalid format" + + username, domain = parts + if not username or not domain: + return False, "Empty username or domain" + + if "." not in domain: + return False, "Domain needs a period" + + return True, "Valid email" + +emails = [ + "user@example.com", + "invalid.email", + "test@domain.co", + "@nodomain.com", + "noatsign.com" +] + +for email in emails: + valid, message = is_valid_email(email) + status = "βœ“" if valid else "βœ—" + print(f"{status} {email}: {message}") + +# Example 12: Word Counter +print("\n=== WORD COUNTER ===") +def count_words(text): + """Count word frequency""" + words = text.lower().split() + word_count = {} + + for word in words: + # Remove punctuation + word = word.strip(".,!?;:") + if word: + word_count[word] = word_count.get(word, 0) + 1 + + return word_count + +text = "Python is great. Python is powerful. I love Python!" +word_freq = count_words(text) +print(f"Text: '{text}'") +print("Word frequencies:") +for word, count in sorted(word_freq.items()): + print(f" {word}: {count}") + +# Example 13: Distance Calculator +print("\n=== DISTANCE CALCULATOR ===") +def calculate_distance(x1, y1, x2, y2): + """Calculate Euclidean distance between two points""" + return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + +point1 = (0, 0) +point2 = (3, 4) +distance = calculate_distance(*point1, *point2) +print(f"Distance between {point1} and {point2}: {distance:.2f}") diff --git a/05_Functions/README.md b/05_Functions/README.md new file mode 100644 index 0000000..bfd5a63 --- /dev/null +++ b/05_Functions/README.md @@ -0,0 +1,74 @@ +# Functions in Python πŸ”§ + +## What are Functions? + +Functions are reusable blocks of code that perform a specific task. They help organize code, avoid repetition, and make programs easier to understand and maintain. + +## Why Use Functions? + +1. **Code Reusability** - Write once, use many times +2. **Organization** - Break complex problems into smaller parts +3. **Readability** - Make code easier to understand +4. **Maintainability** - Update code in one place + +## Function Basics + +### Defining a Function +```python +def function_name(): + # code to execute + print("Hello!") +``` + +### Calling a Function +```python +function_name() # Call the function +``` + +### Parameters and Arguments +```python +def greet(name): # 'name' is a parameter + print(f"Hello, {name}!") + +greet("Alice") # "Alice" is an argument +``` + +### Return Values +```python +def add(a, b): + return a + b + +result = add(5, 3) # result = 8 +``` + +## Types of Arguments + +1. **Positional Arguments** - Order matters +2. **Keyword Arguments** - Named arguments +3. **Default Arguments** - Pre-set values +4. **Variable-length Arguments** - `*args` and `**kwargs` + +## Scope + +- **Local Variables** - Defined inside function +- **Global Variables** - Defined outside function + +## Examples in This Folder + +1. **01_basic_functions.py** - Creating and calling functions +2. **02_parameters_arguments.py** - Working with function parameters +3. **03_return_values.py** - Returning values from functions +4. **04_scope.py** - Understanding variable scope +5. **05_practical_examples.py** - Real-world function applications + +## Tips for Beginners + +- Use descriptive function names (e.g., `calculate_area` not `func1`) +- Functions should do one thing well +- Use docstrings to document your functions +- Return values instead of printing when possible +- Test your functions with different inputs + +## Practice + +Try creating your own functions and combining them to solve problems! diff --git a/06_Practice_Problems/01_number_problems.py b/06_Practice_Problems/01_number_problems.py new file mode 100644 index 0000000..407c7be --- /dev/null +++ b/06_Practice_Problems/01_number_problems.py @@ -0,0 +1,293 @@ +""" +Number Problems - Practice Exercises +===================================== +Try to solve these problems yourself before looking at the solutions! +""" + +print("=" * 60) +print("PROBLEM 1: Even or Odd") +print("=" * 60) +print("Write a program that checks if a number is even or odd") +print() + +# Your code here +# ... + +# Solution: +def check_even_odd(number): + """Check if number is even or odd""" + if number % 2 == 0: + return "Even" + else: + return "Odd" + +# Test +print("Solution:") +test_numbers = [5, 10, 13, 20, 7] +for num in test_numbers: + print(f"{num} is {check_even_odd(num)}") + +print("\n" + "=" * 60) +print("PROBLEM 2: Sum of First N Natural Numbers") +print("=" * 60) +print("Calculate the sum of first n natural numbers (1 + 2 + 3 + ... + n)") +print() + +# Your code here +# ... + +# Solution: +def sum_natural_numbers(n): + """Calculate sum of first n natural numbers""" + total = 0 + for i in range(1, n + 1): + total += i + return total + +# Alternative solution using formula +def sum_natural_formula(n): + """Using mathematical formula: n * (n + 1) / 2""" + return n * (n + 1) // 2 + +# Test +print("Solution:") +for n in [5, 10, 100]: + print(f"Sum of 1 to {n} = {sum_natural_numbers(n)}") + +print("\n" + "=" * 60) +print("PROBLEM 3: Factorial") +print("=" * 60) +print("Calculate factorial of a number (n! = n Γ— (n-1) Γ— ... Γ— 2 Γ— 1)") +print() + +# Your code here +# ... + +# Solution: +def factorial(n): + """Calculate factorial of n""" + if n < 0: + return None + if n == 0 or n == 1: + return 1 + + result = 1 + for i in range(2, n + 1): + result *= i + return result + +# Test +print("Solution:") +for num in [0, 1, 5, 10]: + print(f"{num}! = {factorial(num)}") + +print("\n" + "=" * 60) +print("PROBLEM 4: Prime Number Checker") +print("=" * 60) +print("Check if a given number is prime") +print() + +# Your code here +# ... + +# Solution: +def is_prime(n): + """Check if number is prime""" + if n < 2: + return False + for i in range(2, int(n ** 0.5) + 1): + if n % i == 0: + return False + return True + +# Test +print("Solution:") +test_numbers = [2, 4, 17, 20, 29, 30] +for num in test_numbers: + result = "is" if is_prime(num) else "is not" + print(f"{num} {result} prime") + +print("\n" + "=" * 60) +print("PROBLEM 5: Reverse a Number") +print("=" * 60) +print("Reverse the digits of a number (e.g., 1234 β†’ 4321)") +print() + +# Your code here +# ... + +# Solution: +def reverse_number(num): + """Reverse digits of a number""" + reversed_num = 0 + temp = abs(num) # Handle negative numbers + + while temp > 0: + digit = temp % 10 + reversed_num = reversed_num * 10 + digit + temp //= 10 + + return reversed_num if num >= 0 else -reversed_num + +# Test +print("Solution:") +test_numbers = [1234, 9876, 100, 505] +for num in test_numbers: + print(f"Reverse of {num} is {reverse_number(num)}") + +print("\n" + "=" * 60) +print("PROBLEM 6: Sum of Digits") +print("=" * 60) +print("Find the sum of all digits in a number") +print() + +# Your code here +# ... + +# Solution: +def sum_of_digits(num): + """Calculate sum of all digits""" + total = 0 + temp = abs(num) + + while temp > 0: + digit = temp % 10 + total += digit + temp //= 10 + + return total + +# Test +print("Solution:") +test_numbers = [123, 9876, 505, 1111] +for num in test_numbers: + print(f"Sum of digits in {num} = {sum_of_digits(num)}") + +print("\n" + "=" * 60) +print("PROBLEM 7: Armstrong Number") +print("=" * 60) +print("Check if a number is an Armstrong number") +print("(e.g., 153 = 1Β³ + 5Β³ + 3Β³ = 1 + 125 + 27 = 153)") +print() + +# Your code here +# ... + +# Solution: +def is_armstrong(num): + """Check if number is Armstrong number""" + # Convert to string to count digits + digits = [int(d) for d in str(num)] + power = len(digits) + + total = sum(d ** power for d in digits) + return total == num + +# Test +print("Solution:") +test_numbers = [153, 370, 371, 407, 123, 9474] +for num in test_numbers: + result = "is" if is_armstrong(num) else "is not" + print(f"{num} {result} an Armstrong number") + +print("\n" + "=" * 60) +print("PROBLEM 8: Fibonacci Sequence") +print("=" * 60) +print("Generate first n Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, ...)") +print() + +# Your code here +# ... + +# Solution: +def fibonacci(n): + """Generate first n Fibonacci numbers""" + if n <= 0: + return [] + elif n == 1: + return [0] + + fib = [0, 1] + for i in range(2, n): + fib.append(fib[i-1] + fib[i-2]) + return fib + +# Test +print("Solution:") +for n in [5, 10]: + print(f"First {n} Fibonacci numbers: {fibonacci(n)}") + +print("\n" + "=" * 60) +print("PROBLEM 9: GCD (Greatest Common Divisor)") +print("=" * 60) +print("Find the GCD of two numbers") +print() + +# Your code here +# ... + +# Solution: +def gcd(a, b): + """Calculate GCD using Euclidean algorithm""" + while b: + a, b = b, a % b + return a + +# Test +print("Solution:") +pairs = [(48, 18), (100, 50), (17, 19)] +for a, b in pairs: + print(f"GCD of {a} and {b} = {gcd(a, b)}") + +print("\n" + "=" * 60) +print("PROBLEM 10: Leap Year") +print("=" * 60) +print("Check if a year is a leap year") +print("Rules: Divisible by 4, but not by 100 (unless also by 400)") +print() + +# Your code here +# ... + +# Solution: +def is_leap_year(year): + """Check if year is a leap year""" + if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): + return True + return False + +# Test +print("Solution:") +test_years = [2000, 2004, 2100, 2024, 1900] +for year in test_years: + result = "is" if is_leap_year(year) else "is not" + print(f"{year} {result} a leap year") + +print("\n" + "=" * 60) +print("BONUS: Perfect Number") +print("=" * 60) +print("A perfect number equals the sum of its divisors (excluding itself)") +print("Example: 6 = 1 + 2 + 3") +print() + +# Solution: +def is_perfect(n): + """Check if number is perfect""" + if n < 2: + return False + + divisors_sum = 1 # 1 is always a divisor + for i in range(2, int(n ** 0.5) + 1): + if n % i == 0: + divisors_sum += i + if i != n // i: # Add the other divisor + divisors_sum += n // i + + return divisors_sum == n + +# Test +print("Solution:") +test_numbers = [6, 28, 12, 496] +for num in test_numbers: + result = "is" if is_perfect(num) else "is not" + print(f"{num} {result} a perfect number") diff --git a/06_Practice_Problems/02_string_problems.py b/06_Practice_Problems/02_string_problems.py new file mode 100644 index 0000000..ca2d5d9 --- /dev/null +++ b/06_Practice_Problems/02_string_problems.py @@ -0,0 +1,304 @@ +""" +String Problems - Practice Exercises +===================================== +Try to solve these problems yourself before looking at the solutions! +""" + +print("=" * 60) +print("PROBLEM 1: Reverse a String") +print("=" * 60) +print("Reverse the characters in a string") +print() + +# Your code here +# ... + +# Solution: +def reverse_string(text): + """Reverse a string""" + return text[::-1] + +# Alternative solution using loop +def reverse_string_loop(text): + """Reverse using loop""" + reversed_text = "" + for char in text: + reversed_text = char + reversed_text + return reversed_text + +# Test +print("Solution:") +test_strings = ["hello", "Python", "12345"] +for s in test_strings: + print(f"'{s}' reversed is '{reverse_string(s)}'") + +print("\n" + "=" * 60) +print("PROBLEM 2: Count Vowels") +print("=" * 60) +print("Count the number of vowels in a string") +print() + +# Your code here +# ... + +# Solution: +def count_vowels(text): + """Count vowels in text""" + vowels = "aeiouAEIOU" + count = 0 + for char in text: + if char in vowels: + count += 1 + return count + +# Test +print("Solution:") +test_strings = ["hello", "Python Programming", "aeiou"] +for s in test_strings: + print(f"'{s}' has {count_vowels(s)} vowels") + +print("\n" + "=" * 60) +print("PROBLEM 3: Palindrome Checker") +print("=" * 60) +print("Check if a string is a palindrome (reads same forwards and backwards)") +print() + +# Your code here +# ... + +# Solution: +def is_palindrome(text): + """Check if string is palindrome""" + cleaned = text.replace(" ", "").lower() + return cleaned == cleaned[::-1] + +# Test +print("Solution:") +test_strings = ["racecar", "hello", "level", "A man a plan a canal Panama"] +for s in test_strings: + result = "is" if is_palindrome(s) else "is not" + print(f"'{s}' {result} a palindrome") + +print("\n" + "=" * 60) +print("PROBLEM 4: Count Words") +print("=" * 60) +print("Count the number of words in a sentence") +print() + +# Your code here +# ... + +# Solution: +def count_words(text): + """Count words in text""" + words = text.split() + return len(words) + +# Test +print("Solution:") +test_strings = [ + "Hello World", + "Python is awesome", + "One two three four five" +] +for s in test_strings: + print(f"'{s}' has {count_words(s)} words") + +print("\n" + "=" * 60) +print("PROBLEM 5: Remove Spaces") +print("=" * 60) +print("Remove all spaces from a string") +print() + +# Your code here +# ... + +# Solution: +def remove_spaces(text): + """Remove all spaces""" + return text.replace(" ", "") + +# Alternative solution +def remove_spaces_loop(text): + """Remove spaces using loop""" + result = "" + for char in text: + if char != " ": + result += char + return result + +# Test +print("Solution:") +test_strings = ["hello world", "Python Programming", "a b c d"] +for s in test_strings: + print(f"'{s}' β†’ '{remove_spaces(s)}'") + +print("\n" + "=" * 60) +print("PROBLEM 6: Title Case") +print("=" * 60) +print("Convert string to title case (capitalize first letter of each word)") +print() + +# Your code here +# ... + +# Solution: +def to_title_case(text): + """Convert to title case""" + words = text.split() + title_words = [word.capitalize() for word in words] + return " ".join(title_words) + +# Test +print("Solution:") +test_strings = ["hello world", "python programming", "the quick brown fox"] +for s in test_strings: + print(f"'{s}' β†’ '{to_title_case(s)}'") + +print("\n" + "=" * 60) +print("PROBLEM 7: Count Character Frequency") +print("=" * 60) +print("Count how many times each character appears in a string") +print() + +# Your code here +# ... + +# Solution: +def count_characters(text): + """Count character frequency""" + freq = {} + for char in text: + if char != " ": # Skip spaces + freq[char] = freq.get(char, 0) + 1 + return freq + +# Test +print("Solution:") +test_string = "hello" +freq = count_characters(test_string) +print(f"Character frequency in '{test_string}':") +for char, count in sorted(freq.items()): + print(f" '{char}': {count}") + +print("\n" + "=" * 60) +print("PROBLEM 8: First Non-Repeating Character") +print("=" * 60) +print("Find the first character that appears only once") +print() + +# Your code here +# ... + +# Solution: +def first_non_repeating(text): + """Find first non-repeating character""" + freq = {} + for char in text: + freq[char] = freq.get(char, 0) + 1 + + for char in text: + if freq[char] == 1: + return char + return None + +# Test +print("Solution:") +test_strings = ["hello", "aabbcc", "python", "aabbc"] +for s in test_strings: + result = first_non_repeating(s) + if result: + print(f"'{s}' β†’ First non-repeating: '{result}'") + else: + print(f"'{s}' β†’ No non-repeating character") + +print("\n" + "=" * 60) +print("PROBLEM 9: Anagram Checker") +print("=" * 60) +print("Check if two strings are anagrams") +print("(contain same characters in different order)") +print() + +# Your code here +# ... + +# Solution: +def are_anagrams(str1, str2): + """Check if two strings are anagrams""" + # Remove spaces and convert to lowercase + s1 = str1.replace(" ", "").lower() + s2 = str2.replace(" ", "").lower() + + # Sort characters and compare + return sorted(s1) == sorted(s2) + +# Test +print("Solution:") +pairs = [ + ("listen", "silent"), + ("hello", "world"), + ("The eyes", "They see"), + ("python", "java") +] +for str1, str2 in pairs: + result = "are" if are_anagrams(str1, str2) else "are not" + print(f"'{str1}' and '{str2}' {result} anagrams") + +print("\n" + "=" * 60) +print("PROBLEM 10: Remove Duplicates") +print("=" * 60) +print("Remove duplicate characters from string (keep first occurrence)") +print() + +# Your code here +# ... + +# Solution: +def remove_duplicates(text): + """Remove duplicate characters""" + seen = set() + result = [] + + for char in text: + if char not in seen: + seen.add(char) + result.append(char) + + return "".join(result) + +# Test +print("Solution:") +test_strings = ["hello", "programming", "aabbcc"] +for s in test_strings: + print(f"'{s}' β†’ '{remove_duplicates(s)}'") + +print("\n" + "=" * 60) +print("BONUS: Longest Word") +print("=" * 60) +print("Find the longest word in a sentence") +print() + +# Solution: +def find_longest_word(text): + """Find longest word""" + words = text.split() + if not words: + return None + + longest = words[0] + for word in words: + if len(word) > len(longest): + longest = word + return longest + +# Test +print("Solution:") +test_strings = [ + "Python is an awesome programming language", + "Hello world", + "The quick brown fox jumps" +] +for s in test_strings: + longest = find_longest_word(s) + print(f"Longest word in '{s}':") + print(f" β†’ '{longest}' ({len(longest)} characters)") diff --git a/06_Practice_Problems/03_list_problems.py b/06_Practice_Problems/03_list_problems.py new file mode 100644 index 0000000..a7cf8d6 --- /dev/null +++ b/06_Practice_Problems/03_list_problems.py @@ -0,0 +1,313 @@ +""" +List Problems - Practice Exercises +=================================== +Try to solve these problems yourself before looking at the solutions! +""" + +print("=" * 60) +print("PROBLEM 1: Find Maximum and Minimum") +print("=" * 60) +print("Find the maximum and minimum elements in a list") +print() + +# Your code here +# ... + +# Solution: +def find_max_min(numbers): + """Find max and min in list""" + if not numbers: + return None, None + + maximum = numbers[0] + minimum = numbers[0] + + for num in numbers: + if num > maximum: + maximum = num + if num < minimum: + minimum = num + + return maximum, minimum + +# Test +print("Solution:") +test_list = [45, 23, 67, 12, 89, 34] +max_val, min_val = find_max_min(test_list) +print(f"List: {test_list}") +print(f"Maximum: {max_val}, Minimum: {min_val}") + +print("\n" + "=" * 60) +print("PROBLEM 2: Sum and Average") +print("=" * 60) +print("Calculate sum and average of numbers in a list") +print() + +# Your code here +# ... + +# Solution: +def calculate_sum_average(numbers): + """Calculate sum and average""" + if not numbers: + return 0, 0 + + total = sum(numbers) + average = total / len(numbers) + return total, average + +# Test +print("Solution:") +test_list = [10, 20, 30, 40, 50] +total, avg = calculate_sum_average(test_list) +print(f"List: {test_list}") +print(f"Sum: {total}, Average: {avg}") + +print("\n" + "=" * 60) +print("PROBLEM 3: Remove Duplicates") +print("=" * 60) +print("Remove duplicate elements from a list") +print() + +# Your code here +# ... + +# Solution: +def remove_duplicates(lst): + """Remove duplicates preserving order""" + unique = [] + seen = set() + + for item in lst: + if item not in seen: + unique.append(item) + seen.add(item) + + return unique + +# Test +print("Solution:") +test_list = [1, 2, 2, 3, 4, 4, 5, 1] +print(f"Original: {test_list}") +print(f"Without duplicates: {remove_duplicates(test_list)}") + +print("\n" + "=" * 60) +print("PROBLEM 4: Find Second Largest") +print("=" * 60) +print("Find the second largest element in a list") +print() + +# Your code here +# ... + +# Solution: +def find_second_largest(numbers): + """Find second largest element""" + if len(numbers) < 2: + return None + + # Remove duplicates and sort + unique_numbers = list(set(numbers)) + unique_numbers.sort(reverse=True) + + if len(unique_numbers) < 2: + return None + + return unique_numbers[1] + +# Test +print("Solution:") +test_list = [45, 23, 67, 89, 34, 67] +print(f"List: {test_list}") +print(f"Second largest: {find_second_largest(test_list)}") + +print("\n" + "=" * 60) +print("PROBLEM 5: Count Occurrences") +print("=" * 60) +print("Count how many times each element appears in a list") +print() + +# Your code here +# ... + +# Solution: +def count_occurrences(lst): + """Count occurrences of each element""" + freq = {} + for item in lst: + freq[item] = freq.get(item, 0) + 1 + return freq + +# Test +print("Solution:") +test_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] +freq = count_occurrences(test_list) +print(f"List: {test_list}") +print("Frequency:") +for item, count in sorted(freq.items()): + print(f" {item}: {count} times") + +print("\n" + "=" * 60) +print("PROBLEM 6: Merge Two Sorted Lists") +print("=" * 60) +print("Merge two sorted lists into one sorted list") +print() + +# Your code here +# ... + +# Solution: +def merge_sorted_lists(list1, list2): + """Merge two sorted lists""" + merged = [] + i, j = 0, 0 + + while i < len(list1) and j < len(list2): + if list1[i] < list2[j]: + merged.append(list1[i]) + i += 1 + else: + merged.append(list2[j]) + j += 1 + + # Add remaining elements + merged.extend(list1[i:]) + merged.extend(list2[j:]) + + return merged + +# Test +print("Solution:") +list1 = [1, 3, 5, 7] +list2 = [2, 4, 6, 8] +print(f"List 1: {list1}") +print(f"List 2: {list2}") +print(f"Merged: {merge_sorted_lists(list1, list2)}") + +print("\n" + "=" * 60) +print("PROBLEM 7: Rotate List") +print("=" * 60) +print("Rotate list to the right by k positions") +print() + +# Your code here +# ... + +# Solution: +def rotate_list(lst, k): + """Rotate list by k positions""" + if not lst: + return lst + + k = k % len(lst) # Handle k larger than list length + return lst[-k:] + lst[:-k] + +# Test +print("Solution:") +test_list = [1, 2, 3, 4, 5] +for k in [1, 2, 3]: + rotated = rotate_list(test_list, k) + print(f"Rotate {test_list} by {k}: {rotated}") + +print("\n" + "=" * 60) +print("PROBLEM 8: Find Common Elements") +print("=" * 60) +print("Find elements that appear in both lists") +print() + +# Your code here +# ... + +# Solution: +def find_common(list1, list2): + """Find common elements""" + return list(set(list1) & set(list2)) + +# Test +print("Solution:") +list1 = [1, 2, 3, 4, 5] +list2 = [4, 5, 6, 7, 8] +print(f"List 1: {list1}") +print(f"List 2: {list2}") +print(f"Common elements: {find_common(list1, list2)}") + +print("\n" + "=" * 60) +print("PROBLEM 9: Partition Even and Odd") +print("=" * 60) +print("Separate even and odd numbers into two lists") +print() + +# Your code here +# ... + +# Solution: +def partition_even_odd(numbers): + """Partition into even and odd lists""" + even = [] + odd = [] + + for num in numbers: + if num % 2 == 0: + even.append(num) + else: + odd.append(num) + + return even, odd + +# Test +print("Solution:") +test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +even, odd = partition_even_odd(test_list) +print(f"Original: {test_list}") +print(f"Even numbers: {even}") +print(f"Odd numbers: {odd}") + +print("\n" + "=" * 60) +print("PROBLEM 10: Flatten Nested List") +print("=" * 60) +print("Convert a nested list into a flat list") +print() + +# Your code here +# ... + +# Solution: +def flatten_list(nested): + """Flatten nested list""" + flat = [] + for item in nested: + if isinstance(item, list): + flat.extend(flatten_list(item)) # Recursive call + else: + flat.append(item) + return flat + +# Test +print("Solution:") +nested_list = [1, [2, 3], [4, [5, 6]], 7] +print(f"Nested: {nested_list}") +print(f"Flattened: {flatten_list(nested_list)}") + +print("\n" + "=" * 60) +print("BONUS: List Comprehension Examples") +print("=" * 60) + +# Squares of numbers +numbers = [1, 2, 3, 4, 5] +squares = [x**2 for x in numbers] +print(f"Numbers: {numbers}") +print(f"Squares: {squares}") + +# Filter even numbers +even_numbers = [x for x in numbers if x % 2 == 0] +print(f"Even numbers: {even_numbers}") + +# Create pairs +pairs = [(x, y) for x in [1, 2] for y in [3, 4]] +print(f"Pairs: {pairs}") + +# Convert to uppercase +words = ["hello", "world", "python"] +uppercase = [word.upper() for word in words] +print(f"Original: {words}") +print(f"Uppercase: {uppercase}") diff --git a/06_Practice_Problems/04_mixed_problems.py b/06_Practice_Problems/04_mixed_problems.py new file mode 100644 index 0000000..b73439a --- /dev/null +++ b/06_Practice_Problems/04_mixed_problems.py @@ -0,0 +1,341 @@ +""" +Mixed Problems - Combining Multiple Concepts +============================================= +These problems combine concepts from variables, conditions, loops, and functions. +""" + +print("=" * 60) +print("PROBLEM 1: Temperature Statistics") +print("=" * 60) +print("Given a list of temperatures, find:") +print("- Average temperature") +print("- Number of days above average") +print("- Hottest and coldest days") +print() + +# Solution: +def analyze_temperatures(temps): + """Analyze temperature data""" + if not temps: + return None + + avg_temp = sum(temps) / len(temps) + above_avg = sum(1 for temp in temps if temp > avg_temp) + hottest = max(temps) + coldest = min(temps) + + return { + "average": avg_temp, + "above_average_count": above_avg, + "hottest": hottest, + "coldest": coldest + } + +# Test +print("Solution:") +temperatures = [72, 68, 75, 70, 78, 65, 73] +results = analyze_temperatures(temperatures) +print(f"Temperatures: {temperatures}") +print(f"Average: {results['average']:.1f}Β°F") +print(f"Days above average: {results['above_average_count']}") +print(f"Hottest: {results['hottest']}Β°F") +print(f"Coldest: {results['coldest']}Β°F") + +print("\n" + "=" * 60) +print("PROBLEM 2: Student Grade System") +print("=" * 60) +print("Calculate grades for multiple students and class statistics") +print() + +# Solution: +def process_student_grades(students): + """Process student grades""" + results = [] + + for name, scores in students: + avg = sum(scores) / len(scores) + + if avg >= 90: + grade = "A" + elif avg >= 80: + grade = "B" + elif avg >= 70: + grade = "C" + elif avg >= 60: + grade = "D" + else: + grade = "F" + + results.append({ + "name": name, + "average": avg, + "grade": grade, + "status": "Pass" if avg >= 60 else "Fail" + }) + + return results + +# Test +print("Solution:") +students = [ + ("Alice", [85, 90, 88]), + ("Bob", [78, 82, 75]), + ("Charlie", [92, 95, 98]), + ("Diana", [55, 60, 58]) +] + +results = process_student_grades(students) +print(f"{'Name':<10} {'Average':<10} {'Grade':<8} {'Status'}") +print("-" * 40) +for student in results: + print(f"{student['name']:<10} {student['average']:<10.2f} {student['grade']:<8} {student['status']}") + +print("\n" + "=" * 60) +print("PROBLEM 3: Shopping Cart Calculator") +print("=" * 60) +print("Calculate total cost with discounts and tax") +print() + +# Solution: +def calculate_shopping_cart(items, tax_rate=0.08, discount_threshold=100): + """Calculate shopping cart total""" + subtotal = sum(item["price"] * item["quantity"] for item in items) + + # Apply discount if subtotal exceeds threshold + if subtotal >= discount_threshold: + discount = subtotal * 0.1 # 10% discount + else: + discount = 0 + + after_discount = subtotal - discount + tax = after_discount * tax_rate + total = after_discount + tax + + return { + "subtotal": subtotal, + "discount": discount, + "after_discount": after_discount, + "tax": tax, + "total": total + } + +# Test +print("Solution:") +cart = [ + {"name": "Book", "price": 15.99, "quantity": 2}, + {"name": "Pen", "price": 2.50, "quantity": 5}, + {"name": "Notebook", "price": 8.99, "quantity": 3} +] + +result = calculate_shopping_cart(cart) +print(f"Subtotal: ${result['subtotal']:.2f}") +print(f"Discount: -${result['discount']:.2f}") +print(f"After discount: ${result['after_discount']:.2f}") +print(f"Tax (8%): ${result['tax']:.2f}") +print(f"Total: ${result['total']:.2f}") + +print("\n" + "=" * 60) +print("PROBLEM 4: Password Generator") +print("=" * 60) +print("Generate a random password with specific requirements") +print() + +# Solution: +import random +random.seed(42) # For consistent results + +def generate_password(length=12, include_special=True): + """Generate a random password""" + lowercase = "abcdefghijklmnopqrstuvwxyz" + uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + digits = "0123456789" + special = "!@#$%^&*" + + # Ensure at least one of each type + password = [ + random.choice(lowercase), + random.choice(uppercase), + random.choice(digits) + ] + + if include_special: + password.append(random.choice(special)) + + # Fill remaining length + all_chars = lowercase + uppercase + digits + if include_special: + all_chars += special + + while len(password) < length: + password.append(random.choice(all_chars)) + + # Shuffle the password + random.shuffle(password) + return "".join(password) + +# Test +print("Solution:") +for i in range(3): + pwd = generate_password(12) + print(f"Password {i+1}: {pwd}") + +print("\n" + "=" * 60) +print("PROBLEM 5: Word Frequency Analyzer") +print("=" * 60) +print("Analyze word frequency in a text") +print() + +# Solution: +def analyze_word_frequency(text): + """Analyze word frequency""" + # Clean and split text + words = text.lower().split() + words = [word.strip(".,!?;:") for word in words] + + # Count frequencies + freq = {} + for word in words: + if word: + freq[word] = freq.get(word, 0) + 1 + + # Find most common + most_common = max(freq.items(), key=lambda x: x[1]) if freq else (None, 0) + + return { + "total_words": len(words), + "unique_words": len(freq), + "frequency": freq, + "most_common": most_common + } + +# Test +print("Solution:") +text = "Python is great. Python is powerful. I love Python programming!" +results = analyze_word_frequency(text) +print(f"Text: '{text}'") +print(f"Total words: {results['total_words']}") +print(f"Unique words: {results['unique_words']}") +print(f"Most common: '{results['most_common'][0]}' ({results['most_common'][1]} times)") +print("\nTop 5 words:") +sorted_freq = sorted(results['frequency'].items(), key=lambda x: x[1], reverse=True) +for word, count in sorted_freq[:5]: + print(f" '{word}': {count}") + +print("\n" + "=" * 60) +print("PROBLEM 6: Number Pattern Generator") +print("=" * 60) +print("Generate various number patterns") +print() + +# Solution: +def generate_pyramid(n): + """Generate number pyramid""" + print(f"Number Pyramid (n={n}):") + for i in range(1, n + 1): + # Print spaces + print(" " * (n - i), end="") + # Print numbers ascending + for j in range(1, i + 1): + print(j, end="") + # Print numbers descending + for j in range(i - 1, 0, -1): + print(j, end="") + print() + +def generate_floyd_triangle(n): + """Generate Floyd's triangle""" + print(f"\nFloyd's Triangle (n={n}):") + num = 1 + for i in range(1, n + 1): + for j in range(i): + print(num, end=" ") + num += 1 + print() + +# Test +print("Solution:") +generate_pyramid(5) +generate_floyd_triangle(5) + +print("\n" + "=" * 60) +print("PROBLEM 7: Bank Account Simulator") +print("=" * 60) +print("Simulate basic banking operations") +print() + +# Solution: +class BankAccount: + """Simple bank account simulator""" + def __init__(self, name, initial_balance=0): + self.name = name + self.balance = initial_balance + self.transactions = [] + + def deposit(self, amount): + """Deposit money""" + if amount > 0: + self.balance += amount + self.transactions.append(f"Deposit: +${amount:.2f}") + return True + return False + + def withdraw(self, amount): + """Withdraw money""" + if 0 < amount <= self.balance: + self.balance -= amount + self.transactions.append(f"Withdrawal: -${amount:.2f}") + return True + return False + + def get_balance(self): + """Get current balance""" + return self.balance + + def get_statement(self): + """Get account statement""" + return self.transactions + +# Test +print("Solution:") +account = BankAccount("Alice", 1000) +print(f"Initial balance: ${account.get_balance():.2f}") + +account.deposit(500) +print(f"After deposit: ${account.get_balance():.2f}") + +account.withdraw(200) +print(f"After withdrawal: ${account.get_balance():.2f}") + +print("\nTransaction History:") +for transaction in account.get_statement(): + print(f" {transaction}") + +print("\n" + "=" * 60) +print("PROBLEM 8: Calendar Helper") +print("=" * 60) +print("Determine day of the week for a given date") +print() + +# Solution: +def is_leap_year(year): + """Check if year is leap year""" + return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) + +def days_in_month(month, year): + """Get number of days in month""" + days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + if month == 2 and is_leap_year(year): + return 29 + return days[month - 1] + +def calculate_age(birth_year, current_year): + """Calculate age""" + return current_year - birth_year + +# Test +print("Solution:") +print(f"2024 is leap year: {is_leap_year(2024)}") +print(f"2023 is leap year: {is_leap_year(2023)}") +print(f"Days in February 2024: {days_in_month(2, 2024)}") +print(f"Days in February 2023: {days_in_month(2, 2023)}") +print(f"Age if born in 2000 (current 2024): {calculate_age(2000, 2024)} years") diff --git a/06_Practice_Problems/README.md b/06_Practice_Problems/README.md new file mode 100644 index 0000000..295a4ff --- /dev/null +++ b/06_Practice_Problems/README.md @@ -0,0 +1,59 @@ +# Practice Problems πŸ’ͺ + +## About This Section + +This folder contains practice problems to help you apply what you've learned. Each problem has a solution file, but try solving them on your own first! + +## How to Use + +1. **Read the problem** in the problem file +2. **Try to solve it yourself** - This is important! +3. **Test your solution** with different inputs +4. **Check the solution file** only after attempting +5. **Compare approaches** - There might be multiple ways to solve! + +## Problem Categories + +### Basic Problems +- Simple calculations +- String manipulations +- List operations + +### Intermediate Problems +- Using loops and conditions together +- Working with functions +- Processing multiple inputs + +### Challenge Problems +- Combining multiple concepts +- Algorithm implementation +- Real-world scenarios + +## Problems List + +1. **01_number_problems.py** - Number manipulation and calculations +2. **02_string_problems.py** - String operations and formatting +3. **03_list_problems.py** - List operations and algorithms +4. **04_function_problems.py** - Creating and using functions +5. **05_mixed_problems.py** - Problems combining multiple concepts + +## Tips for Problem Solving + +1. **Understand the problem** - Read carefully +2. **Plan your approach** - Think before coding +3. **Start simple** - Get basic solution working first +4. **Test with examples** - Try different inputs +5. **Optimize later** - Make it work, then make it better + +## Solutions + +Solutions are provided in the same files after the problem statement. Try to solve problems before looking at solutions! + +## Keep Practicing! + +- Try modifying the problems +- Create your own variations +- Challenge yourself with edge cases +- Time yourself and try to improve + +Remember: **Practice makes perfect!** πŸš€ diff --git a/README.md b/README.md index 7677c98..deb0285 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,86 @@ -# 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 collection of Python programs designed for students and anyone starting their journey in programming. + +## πŸ“– Purpose + +This repository is created to help beginners learn Python programming through: +- **Clear Examples**: Easy-to-understand code with detailed comments +- **Structured Learning**: Organized folders covering fundamental concepts +- **Hands-on Practice**: Practice problems to reinforce learning +- **Step-by-Step Approach**: Progress from basics to more complex topics + +## 🎯 Who is this for? + +- College students learning Python +- Complete beginners to programming +- Self-learners who want structured Python practice +- Anyone looking to refresh Python basics + +## πŸ“š Repository Structure + +``` +Python/ +β”‚ +β”œβ”€β”€ 01_Variables_and_Data_Types/ # Learn about variables, strings, numbers, lists, etc. +β”œβ”€β”€ 02_Input_Output/ # Taking input and displaying output +β”œβ”€β”€ 03_Conditional_Statements/ # if, elif, else conditions +β”œβ”€β”€ 04_Loops/ # for loops and while loops +β”œβ”€β”€ 05_Functions/ # Creating and using functions +└── 06_Practice_Problems/ # Practice problems with solutions +``` + +## πŸš€ Getting Started + +1. **Clone the repository**: + ```bash + git clone https://github.com/karan7307/Python.git + cd Python + ``` + +2. **Make sure Python 3 is installed**: + ```bash + python3 --version + ``` + +3. **Navigate to any folder and run the examples**: + ```bash + cd 01_Variables_and_Data_Types + python3 example_file.py + ``` + +## πŸ’‘ How to Use This Repository + +1. Start with **01_Variables_and_Data_Types** and progress sequentially +2. Read the README.md in each folder for concept explanations +3. Study the example programs and their comments +4. Modify the code and experiment with different inputs +5. Try the practice problems on your own before checking solutions + +## πŸ“ Topics Covered + +- **Variables and Data Types**: Integers, floats, strings, booleans, lists, tuples, dictionaries +- **Input/Output**: Reading user input, printing output, formatting +- **Conditional Statements**: if, elif, else, nested conditions +- **Loops**: for loops, while loops, nested loops, loop control (break, continue) +- **Functions**: Defining functions, parameters, return values, scope +- **Practice Problems**: Real-world problems combining multiple concepts + +## 🀝 Contributing + +Feel free to contribute by: +- Adding more examples +- Improving documentation +- Fixing bugs or typos +- Suggesting new topics + +## πŸ“„ License + +This repository is open for educational purposes. Feel free to use and share! + +## 🌟 Happy Learning! + +Remember: **Practice is the key to mastering programming!** Don't just read the codeβ€”type it out, run it, modify it, and experiment with it. + +--- +Made with ❀️ for Python learners