Python Programming Basics and Concepts
Python Programming Basics and Concepts
The `print()` function in Python outputs data to the console, supporting various parameters like `sep` for separator and `end` for specifying what to print at the end, such as a newline. For example, `print("Hello")` outputs "Hello". The `input()` function reads a user's input from the console and returns it as a string, which needs type conversion if numerical data is required, exemplified by `name = input("Enter your name: ")` to capture and print with `print("Hello,", name)`. String replication allows repeating strings using the `*` operator, useful in pattern creation or formatting, e.g., `print("*" * 10)` outputs "**********" .
Local variables exist only within the function or block in which they are declared, and they are destroyed when the function exits. Global variables are declared outside of any function and can be accessed anywhere in the code. Local variables can shadow global variables of the same name within their scope. The `global` keyword can be used inside a function to modify a global variable . For example, `x = 10` (global) and within a function `def func(): x = 5` (local) will print `5` for the local scope and `10` when printing globally outside the function. An example with modification is `count = 0` defined globally, and a subsequent use of `global count` within a function to modify its value. On calling the function, the global count will be updated .
Polymorphism in Python allows functions or methods to operate on different types of objects, providing flexibility and code reusability. Python supports polymorphism both through dynamic typing and method overriding. For example, the `+` operator is overloaded to work with both integers and strings, demonstrated by `print(5 + 10)` resulting in `15` and `print("Hello " + "World")` resulting in "Hello World", showcasing operator overloading. Function polymorphism is supported using method overriding or default arguments like `def add(a, b, c=0): return a+b+c`, which can accept two or three arguments, enhancing function versatility .
Python's logging module provides a standardized way to log program execution progress and issues, differentiated by levels: DEBUG (detailed diagnose), INFO (general events), WARNING (potential problems), ERROR (serious issues), and CRITICAL (highest severity). Proper logging aids in debugging and monitoring applications effectively. Logging is initiated via `logging.basicConfig()`, and messages are recorded with functions like `logging.info()` or `logging.error()`. For example, `import logging; logging.basicConfig(level=logging.INFO); logging.info("Program started")` logs an informational message, while `logging.error("File not found!")` logs an error, aiding issue identification and resolution in production environments .
Assertions in Python provide a mechanism for debugging by allowing assertions of conditions thought to be true in the code flow. They are implemented using the `assert` keyword, typically following the format `assert condition, message`. If the condition evaluates to false, an `AssertionError` is raised, halting the program and displaying the message. Assertions are useful for catching developer-introduced logical errors more rapidly and are used primarily during development. For example, `x = 10; assert x > 0, "x must be positive"` ensures `x` remains positive. Assertions should not replace exceptions for handling regular program errors and may be disabled in running code with the `-O` flag .
Tuples and lists in Python differ primarily in mutability; lists are mutable, allowing modifications like insertions and deletions, while tuples are immutable, leading to faster performance for fixed data collections due to their immutable nature. Tuples are denoted using parentheses `()` and are hashable, making them suitable for use as dictionary keys. Lists, designated by brackets `[]`, allow for dynamic resizing. The performance benefit of tuples over lists arises because immutability allows Python to optimize storage and access. This inherently leads to tuples using less memory and typically being faster for iteration over their elements .
User-defined functions in Python are blocks of reusable code defined using the `def` keyword, allowing for modular programming and reducing repetition. Parameters can be passed to these functions in several ways: positional arguments, which are passed in order; default arguments, which provide default values if none are specified; keyword arguments, which allow you to pass arguments using the parameter names, thereby improving code clarity; and variable-length arguments using `*args` for tuples and `**kwargs` for dictionaries of arguments. For example, a function `def greet(name="Guest"): return f"Hello {name}"` can be called with `print(greet("Ananya"))` to output "Hello Ananya". Similarly, a function `def add(*nums): return sum(nums)` can sum a variable set of numbers, as in `print(add(2, 3, 4))` which outputs 9 .
In Python dictionaries, `keys()` returns a view object displaying a list of all the keys used in the dictionary. `values()` returns a view object of all the values in the dictionary, while `items()` returns a view object of the dictionary's key-value pairs as tuples. These methods are particularly useful for iterating over a dictionary. For example, `d = {'a': 1, 'b': 2}` allows calling `d.keys()` to obtain `dict_keys(['a', 'b'])`, `d.values()` to return `dict_values([1, 2])`, and using `d.items()` within a for loop allows the iteration over pairs to print keys and values .
In Python, the `append()` method adds an element to the end of the list. For example, `lst = [1, 2, 3]; lst.append(4)` results in `[1, 2, 3, 4]`. The `insert()` method adds an element to a specific position in the list, as in `lst.insert(1, 'z')` where `lst = ['a', 'b', 'c']` would become `['a', 'z', 'b', 'c']`. The `remove()` method deletes the first match of a value. For example, in a list `lst = ['a', 'z', 'b', 'c']`, using `lst.remove('c')` would result in `['a', 'z', 'b']`. These methods allow dynamic modification of list content .
In Python, the `__init__()` method acts as a class constructor, called automatically when creating a new instance, allowing attributes initialization. For example, `class Student: def __init__(self, name): self.name = name` assigns the name provided during instantiation. The `__str__()` method provides a human-readable string representation of an object, used when an instance is printed. It is overridden from the object class. For example, `class Car: def __str__(self): return "Car object"; print(Car())` will output "Car object". These methods facilitate attribute management and improve readability, essential for debugging and data presentation .