### Introduction to Python - **What is Python?** High-level, interpreted, general-purpose programming language. - **Features:** Easy to learn, vast libraries, cross-platform, object-oriented. - **Applications:** Web development, data science, AI/ML, automation. ### Python Basics - **Comments:** Use `#` for single-line, `"""` or `'''` for multi-line. ```python # This is a single-line comment """ This is a multi-line comment """ ``` - **Variables:** No explicit declaration needed. ```python name = "Alice" age = 17 height = 5.5 is_student = True ``` - **Data Types:** - **Numeric:** `int`, `float`, `complex` - **Boolean:** `bool` (`True`, `False`) - **Sequence:** `str`, `list`, `tuple` - **Set:** `set` - **Mapping:** `dict` ### Operators - **Arithmetic:** `+`, `-`, `*`, `/`, `%` (modulo), `//` (floor division), `**` (exponentiation) - **Comparison:** `==`, `!=`, ` `, ` =` - **Logical:** `and`, `or`, `not` - **Assignment:** `=`, `+=`, `-=`, `*=` etc. - **Identity:** `is`, `is not` (checks if two variables refer to the same object) - **Membership:** `in`, `not in` (checks if a value is present in a sequence) ### Input and Output - **Output:** `print()` function ```python print("Hello, World!") print("Name:", name, "Age:", age) ``` - **Input:** `input()` function (returns string) ```python user_name = input("Enter your name: ") user_age = int(input("Enter your age: ")) # Type casting to int ``` ### Control Flow #### Conditional Statements (`if-elif-else`) ```python score = 85 if score >= 90: print("Grade A") elif score >= 80: print("Grade B") else: print("Grade C") ``` #### Loops - **`for` loop:** Iterates over a sequence (list, tuple, string, range). ```python for i in range(5): # 0, 1, 2, 3, 4 print(i) fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) ``` - **`while` loop:** Executes as long as a condition is true. ```python count = 0 while count ### Strings - **Definition:** Immutable sequence of characters. - **Indexing:** `my_string[0]` (first char), `my_string[-1]` (last char) - **Slicing:** `my_string[start:end:step]` ```python s = "Python" print(s[0]) # P print(s[1:4]) # yth print(s[::2]) # Pto ``` - **Common Methods:** - `len(s)`: Length of string - `s.lower()`, `s.upper()`: Case conversion - `s.strip()`: Remove whitespace - `s.replace('old', 'new')`: Replace substrings - `s.split(',')`: Split into a list of strings - `s.join(list_of_strings)`: Join elements of a list - `s.find('sub')`: Returns index of first occurrence, -1 if not found - `s.count('char')`: Count occurrences ### Lists - **Definition:** Mutable, ordered sequence of items. `[item1, item2, ...]` - **Indexing & Slicing:** Same as strings. - **Common Methods:** - `len(my_list)`: Length of list - `my_list.append(item)`: Add item to end - `my_list.insert(index, item)`: Insert at specific index - `my_list.remove(item)`: Remove first occurrence of item - `my_list.pop(index)`: Remove and return item at index (default last) - `my_list.sort()`: Sorts list in-place - `sorted(my_list)`: Returns a new sorted list - `my_list.reverse()`: Reverse list in-place - `my_list.count(item)`: Count occurrences - `my_list.extend(another_list)`: Add elements from another list ### Tuples - **Definition:** Immutable, ordered sequence of items. `(item1, item2, ...)` - **When to use:** For fixed collections of items, dictionary keys. - **Indexing & Slicing:** Same as strings/lists. - **Methods:** `count()`, `index()`. Limited due to immutability. ```python my_tuple = (1, "hello", 3.14) print(my_tuple[1]) # hello # my_tuple[0] = 5 # Error: Tuples are immutable ``` ### Dictionaries - **Definition:** Unordered collection of key-value pairs. Keys must be unique and immutable. `{key1: value1, key2: value2, ...}` - **Accessing values:** `my_dict[key]` - **Adding/Modifying:** `my_dict[new_key] = new_value` - **Common Methods:** - `my_dict.keys()`: Returns a view of all keys - `my_dict.values()`: Returns a view of all values - `my_dict.items()`: Returns a view of all key-value pairs - `my_dict.get(key, default_value)`: Get value, returns `None` or `default_value` if key not found - `my_dict.pop(key)`: Remove item with key and return its value - `len(my_dict)`: Number of key-value pairs ### Functions - **Definition:** Reusable blocks of code. - **Syntax:** ```python def greet(name): """This function greets the person passed in as a parameter.""" print("Hello,", name) return f"Greeting for {name}" greet("Alice") # Call the function message = greet("Bob") print(message) ``` - **Parameters:** - **Positional arguments:** Must be in correct order. - **Keyword arguments:** Passed with `key=value`. - **Default arguments:** `def func(param=default_value):` - **Arbitrary arguments (`*args`, `**kwargs`):** For unknown number of arguments. ```python def sum_all(*numbers): # *args for tuple of positional args return sum(numbers) def print_info(**data): # **kwargs for dictionary of keyword args for key, value in data.items(): print(f"{key}: {value}") ``` - **`return` statement:** Sends a value back from the function. If omitted, returns `None`. ### Modules - **Definition:** Python files containing functions, classes, and variables. - **Importing:** ```python import math # Imports entire module print(math.pi) from math import sqrt # Imports specific function print(sqrt(16)) import random as rnd # Imports with an alias print(rnd.randint(1, 10)) ``` - **Common Built-in Modules:** `math`, `random`, `datetime`, `os`, `sys`. ### Error Handling (`try-except`) - **Syntax:** ```python try: # Code that might raise an error num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) result = num1 / num2 print("Result:", result) except ValueError: print("Invalid input! Please enter an integer.") except ZeroDivisionError: print("Error: Cannot divide by zero.") except Exception as e: # Catch any other error print(f"An unexpected error occurred: {e}") else: print("Operation successful!") # Executes if no error finally: print("This block always executes.") # Always executes ```