Python Fundamentals PDF
Document Details

Uploaded by SelfDeterminationPyrope
Tags
Related
- Python Programming Fundamentals PDF
- SDU University CSS 115: Python Programming Fundamentals Fall 2024 Lecture 4 PDF
- SDU CSS 115 Programming Fundamentals 1 (Python) Fall 2024 Practice 4 PDF
- BSc (Hons) Electronics Ist Sem - Programming Fundamentals using Python PDF
- Python Programming Fundamentals Lessons PDF
- Python Programming Fundamentals Lecture Notes PDF
Summary
This document provides an introduction to Python fundamentals including input/output, string formatting, comments, identifiers, and variables. It also covers data types such as integers, floats, and complex numbers. Additionally, it has information on type conversions, objects, and multiple assignments in Python.
Full Transcript
Python Python Fundamentals Input/Output: Input: The input() function takes a prompt as an argument and returns the user's input as a string. name = input("Enter your name: ") age = int(input("Enter your age: ")) Output: p...
Python Python Fundamentals Input/Output: Input: The input() function takes a prompt as an argument and returns the user's input as a string. name = input("Enter your name: ") age = int(input("Enter your age: ")) Output: print("Hello World") print("and your age,", age) Output Formatting in Python Python offers several methods to format strings, each with its own syntax and advantages: 1. Old-style String Formatting (Modulo Operator): This method uses the modulo operator (%) to format strings. It's similar to C's printf function. name = "Alice" age = 30 print("Hello, %s! You are %d years old." % (name, age)) Output: Hello, Alice! You are 30 years old. Explanation: o %s is a placeholder for a string. o %d is a placeholder for an integer. o The values in the tuple (name, age) are substituted into the string according to the placeholders. 2. String Formatting Method: name = "Bob" age = 25 print("Hello, {}! You are {} years old.".format(name, age)) Output: Hello, Bob! You are 25 years old. Explanation: o {} are placeholders for values. o The format() method takes the values to be substituted as arguments and inserts them into the string. 3. f-Strings (Formatted String Literals): name = "Charlie" age = 35 print(f"Hello, {name}! You are {age} years old.") Output: Hello, Charlie! You are 35 years old. Explanation: o f before the string literal indicates a formatted string. o Variables and expressions within curly braces {} are evaluated and inserted directly into the string. Format Specifiers: You can customize the formatting of numbers and strings using format specifiers within the curly braces: number = 3.14159 formatted_number = f"Pi is approximately {number:.2f}" print(formatted_number) # Output: Pi is approximately 3.14.2f: This specifies that the number should be formatted as a floating-point number with two decimal places. Other Format Specifiers: f: Floating-point number e: Scientific notation %: Percentage Comments Comments are lines in your code that are ignored by the Python interpreter. They are intended for human readers to understand the code's purpose and logic. Types: o Single-line comments: Start with a # symbol. Everything after # on that line is considered a comment. o Multi-line comments (docstrings) are enclosed in triple quotes ("""Docstring goes here"""). These are often used to document functions, classes, and modules. Benefits: o Readability: Comments make your code easier to understand. o Maintenance: Comments help you or others modify your code later. o Debugging: Comments can be used to temporarily disable parts of your code for debugging purposes. Example: # This is a single-line comment """ This is a multi-line comment (docstring) that can span multiple lines. """ print("Hello, world!") # This comment explains the following line Identifiers Identifiers are names assigned to variables, functions, classes, and other elements in Python. They must follow certain rules to ensure validity. Naming things: Names used to identify program elements (variables, functions, classes, etc.). Rules: o Start with a letter or underscore. o It can contain letters, digits, and underscores. o No limit on length. o Case-sensitive. ▪ Keywords: Reserved words with predefined meanings (e.g., for, while, if, etc.). Cannot be used as identifiers. help('keywords') ▪ Built-in names: Predefined names (e.g., print, len, max, etc.). Avoid using them as identifiers to prevent conflicts. dir(__builtins__) ▪ Nameing Conventions: ▪ Use meaningful and descriptive names. ▪ Use lowercase letters with underscores as word separators (e.g., marks_maths). ▪ Use CapWords convention for class names (e.g., MyClass). ▪ Avoid names with single or double leading underscores. variable_name = value function_name() class ClassName: pass Example: name = "Alice" # Valid identifier _age = 25 # Valid (underscore allowed) 2nd_value = 10 # Invalid (cannot start with a number) Variables and Data Types In Python, a variable is a named storage location that holds a value. You don't need to declare a variable's data type explicitly. Python automatically assigns the appropriate data type based on the value assigned to it. Data Types Python supports various data types: Numeric: o int: Integer numbers (e.g., 10, -5, 0) o float: Floating-point numbers (e.g., 3.14, -2.5) o complex: Complex numbers (e.g., 2+3j) int_var = 5 float_var = 5.5 complex_var = 3 + 4j Boolean: o bool: Boolean values (True or False) bool_var = True None Type: o None: Represents the absence of a value result = None Container types Data structures that hold collections of objects (e.g., lists, tuples, dictionaries, sets). Sequential Collections String: o str: Sequence of characters (e.g., "Hello, world!") List: o list: Ordered collection of items (e.g., [1, 2, 3, "apple"]) Tuple: o tuple: Ordered, immutable collection of items (e.g., (1, 2, 3)) Associative Collections Dictionary: o dict: Unordered collection of key-value pairs (e.g., {"name": "Alice", "age": 30}) Set: o set: Unordered collection of unique items (e.g., {1, 2, 3}) Type Conversions: Implicit: Python automatically converts data types when necessary. , for example, adding an int to a float results in a float. x = 10 # int y = 3.14 # float z = x + y # Implicitly converted to float Explicit (Type Casting): Explicit conversions (type casting) are done using functions like int(), float(), and str() x = 10 # int y = float(x) # y will be a float (10.0) Object Everything in Python is an object. Each object has a type, identity, and value. o Everything in Python is an object. o The objects are chunks of memory used to store data. o Each object has a type, a value, and an identity (a unique integer). Figure 2.1: Objects of type int and str x = 5 print(id(x)) # Get unique object ID Example: a = "Hello" b = "Hello" print(id(a), id(b)) # Outputs different IDs (sometimes same due to optimization) Variables and Assignment Statement Python stores values in objects, and variables are names that reference these objects. Assigning a value to a variable binds the name to an object. For example: variable_name = value x = 56 # x refers to an integer object with value 56 p = 'Hello' # p refers to a string object Figure 2.2: References to objects When a variable is referenced, its associated value is used. Variables act as object references, storing memory locations rather than values themselves. Object Sharing and Aliasing Assigning a variable to another variable does not copy the object; instead, both variables point to the same object: z = x # z now refers to the same object as x The name z will also refer to the same object to which x is referring: Figure 2.3: Variables x and z refer to the same object y = z # y also refers to the same object Figure 2.4: Variables x, y, and z refer to the same object Now, all three variables, x, y, and z are bound to the same object, and any of them can be used to access the underlying object. This is known as object sharing or aliasing. Using id(variable) confirms that all three refer to the same object. Rebinding Variables Variables can be reassigned to new objects: x = 25 # Now x refers to a new object z = z + 3 # z is rebound to a new object with value 59 y = 3.6 # y now refers to a float object Figure 2.5: Variable x refers to a new object Figure 2.7: Variable y refers to a new object; object 56 is orphaned If no variable references an object, Python’s garbage collector removes it. Multiple and Pairwise Assignments two ways to assign values to multiple variables in a single line in Python: multiple assignment and pairwise assignment. Multiple Assignment: Assigns the same value to multiple variables simultaneously. variable1 = variable2 = variable3 = value Figure 2.8: Multiple assignment makes variables refer to the same object Example: a = b = c = 10 #(all variables now refer to the same object with the value 10). Pairwise Assignment: Assigns different values to multiple variables in a specific order. variable1, variable2, variable3 = value1, value2, value3 Example: Figure 2.9: Pairwise assignment x, y, z = 1, 2.5, 3 #(x gets 1, y gets 2.5, z gets 3). The number of variables on the left must match the number of values on the right. Dynamic Typing in Python Python is dynamically typed, meaning variables do not have fixed types. A variable can hold different types of objects at different times, unlike statically typed languages (C, C++, Java), where a variable's type is fixed. Deleting a Name The del statement removes a variable reference, allowing Python's garbage collector to reclaim memory. del variable_name Example: x = 50 del x # print(x) # This will cause an error since x no longer exists Operators: Arithmetic: o +, -, *, /, // (floor division), % (modulo), ** (exponentiation) Key Differences Result Type: o / always returns a float. o // returns an integer (if both operands are integers) or a float. Decimal Handling: o / preserves decimal precision. o // discards the decimal part (or rounds down). Comparison: o ==, !=, , = Logical: o and, or, not Identity: Used to check if two variables refer to the same object. o is, is not (compare object identities) a = [1, 2] b = a print(a is b) # True Membership: Used to test if a value is in a sequence (like a list or a string). o in, not in (check if a value is in a sequence) fruits = ["apple", "banana"] print("apple" in fruits) # True Python Operator Precedence and Associativity Operator precedence dictates which operations are performed first. Operators with higher precedence are evaluated before those with lower precedence. Python Operator Precedence and Associativity Table Operator(s) Description Associativity Notes Highest to Lowest () Parentheses Left-to-Right Used to group expressions and override default precedence. ** Exponentiation Right-to-Left +x, -x, ~x Positive, Negative, Bitwise Right-to-Left Unary operators. NOT *, /, //, % Multiplication, Division, Left-to-Right Floor Division, Remainder (Modulo) +, - Addition, Subtraction Left-to-Right Left Shift, Right Shift Left-to-Right Bitwise shift operators. & Bitwise AND Left-to-Right ^ Bitwise XOR (Exclusive OR) Left-to-Right `\ ` Bitwise OR Left-to-Right in, not in, is, is not, Membership tests, Identity Left-to-Right =, !=, == tests, Comparisons not Boolean NOT Left-to-Right Unary operator. and Boolean AND Left-to-Right or Boolean OR Left-to-Right Associativity Associativity comes into play when two or more operators have the same precedence. It determines the direction of evaluation: o Left-to-right associativity: Most operators follow this rule. For example, 10 - 3 + 2 is evaluated as (10 - 3) + 2. o Right-to-left associativity: The exponentiation operator (**) is a notable exception. For example, 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2). Mutable/Immutable In Python, every object has three key attributes: Type: Defines the kind of object (e.g., int, list). ID (Memory Address): A unique identifier for the object. Value: The data stored inside the object. While an object's type and ID remain constant throughout its lifetime, whether its value can be modified depends on its mutability. Mutable vs. Immutable Types Python objects are categorized as either mutable or immutable: Immutable Types: The value inside these objects cannot be changed once they are created. (e.g., int, float, bool, str, tuple, frozenset) Mutable Types: The value can be modified in-place (e.g., lists, sets, dictionaries). Mutability applies to objects, not variable names. A variable name is just a reference (or label) to an object. A variable can be rebound to a new object, but an immutable object itself cannot be changed in-place. Rebinding vs. Mutating an Object Rebinding a variable Rebinding means making a variable reference a new object. This applies to both mutable and immutable types. Example: a = 56 # a refers to an int object with value 56 a = a + 3 # a now refers to a new int object with value 59 Since int is immutable, a + 3 does not modify the original object; instead, a new object is created, and a now refers to it. x = [1, 2, 3] # 'x' refers to a list object x = [4, 5, 6] # 'x' is now rebound to a new list object Initially, x refers to a list [1, 2, 3]. When x = [4, 5, 6] is executed, a new list object [4, 5, 6] is created. The variable x is rebound to the new list object, discarding the reference to the original list [1, 2, 3]. The original list remains unchanged (if there were no other references to it, it would be garbage collected). Mutating an object: Changing the content of an object in-place. This only applies to mutable objects. Example: x = [1, 2, 3] # x refers to a list object x.append(4) # The list object itself is modified Since list is mutable, the same object is updated without creating a new one. Multiple References: Mutability becomes significant when multiple variables reference the same object: Changes to a mutable object through one variable affect all references. Immutable objects don't have this issue since they can't be changed in-place. Mutability is important when multiple variables refer to the same object: x = [1, 2, 3] y = x # Both x and y refer to the same list object y.append(4) # Modifying the object through y print(x) # Output: [1, 2, 3, 4] (x also sees the change) Since lists are mutable, modifying y also affects x because both refer to the same object. However, with immutable types: a = 56 b = a # Both a and b refer to the same int object b = b + 3 # Creates a new int object with value 59, b is rebound print(a) # Output: 56 (a is unaffected) Here, b = b + 3 creates a new object instead of modifying the original. Understanding mutability is essential for: Predictability: Preventing unexpected side effects by knowing when objects might change. Efficiency: Optimizing performance by modifying mutable objects in-place, rather than creating new ones. Data Sharing: Enabling efficient sharing and modification of data across program sections. Functions/Methods Functions Reusable blocks of code with names that perform specific tasks. Built-in Functions: Pre-written functions always available in Python (e.g., print(), input(), type(), id()). Examples: abs(x), bin(x), oct(x), hex(x), max(a, b, c,...), min(a, b, c,...) Methods Similar to functions but associated with a specific data type. Calling Methods: Use the dot notation (.) after a variable or literal of that type (e.g., 'hello'.upper(), list1.append(10)). Type-Specific: Methods can only operate on objects of the type they are associated with. Exploring Methods dir(typename): Lists all methods available for a given type (e.g., dir(list)). help(typename.methodname): Provides detailed information about a specific method (e.g., help(list.append)). Modules and Importing Standard Library: A collection of pre-written modules containing various functions and tools. Modules: Python files that organize related functions and definitions. Importing: The process of making functions from a module available in your program. Ways to Import from... import...: o Imports specific functions from a module. o Example: from math import sqrt, trunc o You can then use the functions directly (e.g., sqrt(34)). import...: o Imports the entire module. o Example: import math o To use a function, you need to prefix it with the module name (e.g., math.sqrt(34)). Exploring Modules help(modulename): Provides documentation and information about a module (e.g., help(math)). dir(modulename): Lists all the names (functions, variables, etc.) defined in a module (e.g., dir(math)). Indentation Indentation refers to the spaces at the beginning of a code line. It defines code blocks (like loops, functions, and conditional statements). Consistency: Use the same amount of indentation throughout your code. Typically, four spaces are preferred. Code Blocks: Indentation defines code blocks associated with if, else, for, while, def, class, and other control flow statements. Readability: Proper indentation makes your code more readable and easier to understand. Error Prevention: Incorrect indentation will lead to IndentationError exceptions.