Python Basics: Operators and Data Types
Python Basics: Operators and Data Types
Logical operators in Python are used to perform boolean operations on values, determining the logic of expressions. The primary logical operators are `and`, `or`, and `not`. - The `and` operator returns True if both operands are true. For example, `True and False` returns `False`. - The `or` operator returns True if at least one of the operands is true. For example, `True or False` returns `True`. - The `not` operator inverts the boolean value of operand. For example, `not True` returns `False`. These operators help in making decisions in conditional statements .
In Python, both lists and dictionaries can store heterogeneous data types, yet they differ fundamentally in their structure and use cases. Lists are ordered collections indexed by integers, allowing storage of items like `['computer', 2018, 8.25, 'python']`, mixed without type constraints and accessed via index positions. They facilitate sequential data manipulation and iteration. Dictionaries, on the other hand, store data as key-value pairs in an unordered structure, allowing retrieval based on unique keys, not positions. For example, `d = {1: 'apple', 2: 'ball'}`. Each key must be unique, and keys are usually immutable types (like strings or numbers). The dichotomy of ordered lists and pair-wise unordered dictionaries supports flexible storage and retrieval use cases across varying programming scenarios .
The immutability of Python strings means once a string is created, its characters cannot be altered. This behavior is significant for programming as it ensures string constants remain unchanged and aids in optimizing memory usage and performance. For instance, if you have a string `s = 'hello'`, attempting to modify it with `s[0] = 'y'` will result in an error. Instead, any modification would create a new string, e.g., `s = 'y' + s[1:]` resulting in `'yello'`. Immutability leads to reliable references in code, which facilitates clearer data flow and reduces bugs related to unintended changes .
In Python, to swap the values of two variables without a third variable, the tuple unpacking feature is used. This involves grouping the two variables in a tuple on the right-hand side of the assignment (`x, y = y, x`), which internally creates a temporary tuple object to hold the original values. The values are then swapped as they are simultaneously assigned back to the respective variables on the left-hand side, resulting in swapped values. For example, if `x=10` and `y=20`, after executing `x, y = y, x`, `x` will be `20` and `y` will be `10` .
Lists and tuples in Python are both used to store ordered collections of items, but they have distinct differences. Lists are mutable, meaning their contents can be changed after creation (e.g., adding, removing, or modifying elements). They are created using square brackets, e.g., `list1 = ['computer', 2018, 8.25, 'python']`. Due to their mutability, lists are often used when data collection needs alteration or frequent updates. In contrast, tuples are immutable, meaning once created, their contents cannot be changed. This immutability ensures the integrity of data that should not be modified, making tuples useful for fixed collections like constants or configuration settings. Tuples are created with parentheses, e.g., `a=(1,'python')`. Both lists and tuples can store items of mixed data types .
Operator precedence in Python defines the order in which parts of an expression are evaluated in the presence of multiple operators. This precedence determines which operations are performed first when there is more than one operator, thus affecting the result of expressions. Python follows a hierarchy derived from PEMDAS rules: - Parentheses are evaluated first, - Exponentiation (`**`) follows, - Multiplication (`*`), Division (`/`), and Floor Division (`//`) are next, - Addition (`+`) and Subtraction (`-`) have the lowest precedence. Expressions are evaluated in this order unless overridden by parentheses, ensuring predictable and accurate computation of complex expressions .
Operator associativity in Python determines the order of evaluation for operators with the same precedence within an expression. Most Python operators have left-to-right associativity, meaning operations are grouped and evaluated from the left side first. For instance, in the expression `10 * 2 // 3`, multiplication and floor division operators are of equal precedence, so evaluation proceeds first with `10 * 2`, and then the result is divided using `//`. The exponentiation operator `**` is an exception, as it has right-to-left associativity. For example, in the expression `2 ** 3 ** 2`, the computation occurs starting from the rightmost `**`, resulting in `2 ** (3 ** 2)`, hence `2 ** 9`, not `(2 ** 3) ** 2` .
Keywords in Python are reserved words that hold specific meanings and constitute part of the language's syntax and structure. These words are case-sensitive, meaning their capitalization matters (e.g., `True`, `False`, `if`, `elif`, etc.), and they cannot be used as identifiers such as variable names. This sensitivity ensures clarity and prevents conflicts within the code, as keywords serve as essential building blocks that define operations, control structures, and data management within the language. Misuse of keywords (e.g., using `if` in place of a variable name) would lead to syntax errors, highlighting their crucial role in maintaining programming language integrity and functionality .
The four scalar object types in Python are `bool`, `int`, `float`, and `string`. - `bool`: Represents truth values, True and False, and is a subtype of integer. E.g., `x=True`. - `int`: Represents whole numbers without fractions. E.g., `x=5`. - `float`: Represents real numbers with fractional parts. E.g., `x=5.5`. - `string`: A sequence of characters enclosed in quotes. E.g., `name='python'` .
In Python, parentheses have the highest precedence among all operators in expressions, meaning they are evaluated first regardless of the operations they enclose. This allows for the explicit dictation of order in which expressions are evaluated. For instance, in the expression `2 * (3 - 1)`, the subtraction within the parentheses is computed first, resulting in multiplication with 2 being applied to the result. Thus, parentheses can override the default operator precedence to evaluate expressions in a desired order, ensuring clarity and correct results based on precedence requirements .