### Introduction to Python - **What is Python?** High-level, interpreted, interactive, object-oriented language. - **Features:** Easy to learn, free and open source, portable, extensible, large standard library. - **Applications:** Web development, AI/ML, data science, scientific computing, scripting. - **Python Interpreter:** Executes Python code line by line. - **Keywords:** Reserved words with special meaning (e.g., `if`, `else`, `while`, `for`, `def`, `class`). #### Python Character Set - Letters (A-Z, a-z) - Digits (0-9) - Special symbols (+, -, *, /, etc.) - Whitespace characters (blank space, tab, newline) ### Data Types - **Numbers:** - `int`: Integers (e.g., `10`, `-5`, `0`) - `float`: Floating-point numbers (e.g., `3.14`, `-0.5`, `2.0`) - `complex`: Complex numbers (e.g., `3 + 2j`) - **Boolean:** `True`, `False` - **Sequence Types:** - `str`: Strings (e.g., `"hello"`, `'Python'`) - `list`: Ordered, mutable sequence (e.g., `[1, 2, 'a']`) - `tuple`: Ordered, immutable sequence (e.g., `(10, 20, 'b')`) - **Mapping Type:** - `dict`: Unordered collection of key-value pairs (e.g., `{'name': 'Alice', 'age': 16}`) - **Set Type:** - `set`: Unordered collection of unique items (e.g., `{1, 2, 3}`) #### Variables - **Assignment:** `variable_name = value` (e.g., `x = 10`, `name = "Python"`) - **Rules for Naming Variables:** - Must start with a letter or underscore (`_`). - Cannot start with a digit. - Can contain letters, numbers, and underscores. - Case-sensitive (`myVar` is different from `myvar`). - Cannot be a keyword. ### Operators - **Arithmetic:** `+`, `-`, `*`, `/` (float division), `//` (integer division), `%` (modulo), `**` (exponentiation) - **Relational/Comparison:** `>`, ` =`, ` `, `>=`, `==`, `!=`) - `not` - `and` - `or` ### Expressions and Statements - **Expression:** A combination of values, variables, operators, and calls to functions that evaluates to a single value (e.g., `5 + 3`, `x * y`, `"Hello" + "World"`). - **Statement:** An instruction that the Python interpreter can execute (e.g., `x = 10`, `print("Hi")`, `if x > 0:`). - **Comments:** - Single-line: `# This is a comment` - Multi-line: `"""This is a multi-line comment"""` ### Input and Output - **Output:** `print()` function - `print("Hello World")` - `print("Value:", x)` - `print(f"The sum is {a+b}")` (f-string formatting) - `print("a", "b", "c", sep='-', end='!\n')` - **Input:** `input()` function - `name = input("Enter your name: ")` (returns string) - `age = int(input("Enter your age: "))` (type casting to integer) - `price = float(input("Enter price: "))` (type casting to float) ### Debugging - **Syntax Errors:** Mistakes in the syntax of the code (e.g., `prnt("Hello")`). Interpreter reports these. - **Logical Errors:** Program runs but produces incorrect output (e.g., `a - b` instead of `a + b`). Requires careful checking of logic. - **Runtime Errors (Exceptions):** Errors that occur during program execution (e.g., `ZeroDivisionError`, `IndexError`, `NameError`). ### Flow of Control #### Conditional Statements (Selection) - **`if` statement:** ```python if condition: # statements if condition is True ``` - **`if-else` statement:** ```python if condition: # statements if condition is True else: # statements if condition is False ``` - **`if-elif-else` statement:** ```python if condition1: # statements if condition1 is True elif condition2: # statements if condition2 is True else: # statements if both conditions are False ``` #### Looping Statements (Iteration) - **`for` loop:** Iterates over a sequence (list, tuple, string, range). ```python for variable in sequence: # statements to be repeated ``` - `range()` function: `range(stop)`, `range(start, stop)`, `range(start, stop, step)` - `for i in range(5): # 0, 1, 2, 3, 4` - `for i in range(1, 6): # 1, 2, 3, 4, 5` - `for i in range(10, 0, -2): # 10, 8, 6, 4, 2` - **`while` loop:** Repeats as long as a condition is true. ```python while condition: # statements to be repeated ``` - **Jump Statements:** - `break`: Terminates the loop immediately. - `continue`: Skips the rest of the current iteration and proceeds to the next iteration. ### String Manipulation - **Definition:** Sequence of characters enclosed in single, double, or triple quotes. - **Immutable:** Cannot be changed after creation. - **Accessing characters:** `my_string[index]` (e.g., `s = "Python"`, `s[0]` is 'P') - **Slicing:** `my_string[start:end:step]` - `s[0:2]` -> "Py" - `s[2:]` -> "thon" - `s[:3]` -> "Pyt" - `s[::-1]` -> "nohtyP" (reverse string) - **Concatenation:** `s1 + s2` - **Repetition:** `s * n` - **Membership:** `'P' in s` -> `True` - **String Functions/Methods:** - `len(s)`: Length of string - `s.lower()`, `s.upper()`: Convert case - `s.strip()`: Remove leading/trailing whitespace - `s.startswith(prefix)`, `s.endswith(suffix)` - `s.find(substring)`: Returns index of first occurrence, -1 if not found - `s.replace(old, new)` - `s.split(delimiter)`: Splits string into a list of substrings - `s.join(list_of_strings)`: Joins elements of a list into a string - `s.isdigit()`, `s.isalpha()`, `s.isalnum()` ### Lists - **Definition:** Ordered, mutable collection of items. - **Creating lists:** `my_list = [1, 2, 3, "apple"]`, `empty_list = []` - **Accessing elements:** `my_list[index]`, `my_list[-1]` (last element) - **Slicing:** `my_list[start:end:step]` (same as strings) - **Mutable:** Elements can be changed (`my_list[0] = 5`) - **List Operations:** - Concatenation: `list1 + list2` - Repetition: `list * n` - Membership: `5 in my_list` - **List Methods:** - `my_list.append(item)`: Adds item to the end. - `my_list.extend(another_list)`: Appends elements from another list. - `my_list.insert(index, item)`: Inserts item at a specific index. - `my_list.remove(item)`: Removes first occurrence of item. - `my_list.pop(index)`: Removes and returns item at index (default last). - `my_list.clear()`: Removes all items. - `my_list.index(item)`: Returns index of item. - `my_list.count(item)`: Returns number of occurrences of item. - `my_list.sort()`: Sorts list in-place. - `sorted(my_list)`: Returns a new sorted list (doesn't modify original). - `my_list.reverse()`: Reverses list in-place. - `len(my_list)`: Length of list. ### Tuples - **Definition:** Ordered, immutable collection of items. - **Creating tuples:** `my_tuple = (1, 2, "banana")`, `single_item_tuple = (5,)` - **Accessing elements & Slicing:** Same as lists/strings. - **Immutable:** Elements cannot be changed after creation. - **Tuple Operations:** Concatenation, Repetition, Membership (similar to lists). - **Functions:** `len()`, `min()`, `max()`, `sum()`, `tuple()` - **Tuple Unpacking:** `a, b, c = my_tuple` ### Dictionaries - **Definition:** Unordered collection of key-value pairs. Keys must be unique and immutable. - **Creating dictionaries:** `my_dict = {'name': 'Alice', 'age': 16}`, `empty_dict = {}` - **Accessing values:** `my_dict[key]` (raises KeyError if key not found), `my_dict.get(key, default_value)` - **Adding/Updating elements:** `my_dict[key] = value` - **Deleting elements:** `del my_dict[key]`, `my_dict.pop(key)`, `my_dict.clear()` - **Dictionary 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. - `len(my_dict)`: Number of key-value pairs. ### Introduction to Functions - **Function:** A block of organized, reusable code that performs a single, related action. - **Benefits:** Code reusability, modularity, easier debugging. - **Defining a function:** ```python def function_name(parameters): """Docstring: explains what the function does.""" # function body return [expression] # optional ``` - **Calling a function:** `function_name(arguments)` - **Parameters vs. Arguments:** - Parameters: Variables listed inside the parentheses in the function definition. - Arguments: Values passed to the function when it is called. - **`return` statement:** Used to send a value back to the caller. If no `return` or `return` without expression, `None` is returned. - **Types of Functions:** - **Built-in functions:** `print()`, `input()`, `len()`, `range()`, `int()`, `float()`, etc. - **Module functions:** Functions defined in modules (e.g., `math.sqrt()`). - **User-defined functions:** Functions created by the programmer.