02 Variables and Basic Data Structures.pptx
Document Details
Uploaded by PlentifulMonkey
Universidad Autónoma de Nuevo León
Tags
Related
- Data Structures and Algorithms Chapter 1 PDF
- Python Programming - Introduction to Computational Thinking PDF
- Fundamentals of Programming - ITM200 Data Variables and Calculations PDF
- Data Analytics with Python - MGM University - PDF
- Python For Computational Problem Solving - List - PDF
- Python Strings - Module 4 - Data Structures PDF
Full Transcript
Variables and Basic Data Structures Definition String of characters and numbers associated with of information Variables Introduction Assignmen Denoted by the “=” symbol t Operator Used to assign...
Variables and Basic Data Structures Definition String of characters and numbers associated with of information Variables Introduction Assignmen Denoted by the “=” symbol t Operator Used to assign values to variables to Variables Example of Line x=1 assigns value 1 to variable x Assignmen Variable x behaves like value 1 until changed or deleted t Equality Sign in Mathematics Statement x = 2 declares a universal truth 1 = x is valid in mathematics Equality Sign in Equality Sign in Programming Programmin Statement x=2 means assigning g value 2 to variable x Assignments always go left in Python 1=x generates an error in Python Assignment operator is last in the order of operations Alphanumeric characters (letters and Allowed numbers) Characters Underscores First Character Must be a letter or an underscore Rules Restrictions Prohibited on Variable Characters Spaces within a variable name Names Variable names are case sensitive (e.g., x Case Sensitivity and X are different) Importance of Variables should represent something tangible Meaningful Use descriptive names (e.g., dist for Names distance, n_rabbits for number of rabbits) Reassigning Variables have no memory of how they were assigned Variables Reassigning a variable does not change dependent variables Example Code: x = 1; y = x + 1; x = 2; y Output: y = 2 Variables can overwrite built-in functions Be careful not to use names of built-in functions Always assign results to variables Data Types Includes int, float, and boolean Overview Related to single value Strings, lists, tuples, sets, and New Data Types dictionaries Can store multiple values Introduction to Strings Sequence of characters Surrounded by single or Strings double quotation marks Use print function to output strings Examples Print "I love Python!" String Length Strings have a length indicating their size Use the built-in function len to check the size String Indexes String Indexes start at 0 Indexing and Access characters using brackets and index Slicing String Slicing Use slicing to select a sequence of characters Syntax: [start:end:step] Step argument is optional, default is 1 Ignore end position to slice to the end of the string String Concatenating Strings Concatenatio Example: str_a + str_b results in 'I love Python! n and You too!' Converting Data Types to Strings Conversion Use the built-in function str to convert other data types to strings Example: str(x) converts integer x to string Handling TypeError Direct concatenation of string and integer causes TypeError Convert integer to string before concatenation Example of Correct Conversion print('x = ' + str(x)) results in 'x=1' type(str(x)) returns str String Methods in Python Strings are objects with various methods for manipulation Access methods using string.method_name pattern String Methods Examples of String Methods Convert to upper case: w.upper() Count occurrences of a letter: w.count('l') Replace a substring: w.replace('World', 'Berkeley') Introduction of f-string in Python 3.6+ f-string allows easy string formatting String Example: print(f"{name} is a Formatting great school in {country}.") Printing Numerical Expressions with f-string No need to convert data type Example: print(f"{3*4}") Introduction Sequential data structure in Python to Lists Defined using brackets [ ] Elements separated by commas Can hold numerical data Can hold strings Can hold other types of data Examples of Lists list_1 = [1, 2, 3] list_2 = ["Hello", "World"] Retrieve 3rd Use list_3 element in list_3 Output: 3 Retrieve first 3 Use list_3[:3] elements in list_3 Output: [1, 2, 3] List Indexing and Slicing Retrieve last Use list_3[-1] Output: element in list_3 "orange" Retrieve first list Use list_4 from list_4 Output: [1, 2, 3] Getting the Length of a List Use the len function to obtain the length of a list Concatenating Lists Use the + sign to concatenate two lists Adding Items to a List Use the append method to add new items to List Methods an existing list Inserting and Removing Elements Use insert and remove methods to modify the list directly Use del function to delete an item by its index Defining an Empty List Define an empty list and add elements later using the append method List Operations Checking Element in List Use 'in' operator to check if an element is in a list Example: Check if number 5 is in list_5 Output: True Turning Sequence Items into List Use list function to convert sequence items to a list Example: Turn string 'Hello World' into a list of characters Output: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] Sequence data structure in Python Defined using parentheses ( ) Introduction to Tuples Elements separated by commas tuple_1 = (1, 2, 3, 2) Example of Tuple Output: (1, 2, 3, 2) Similar to strings and lists Access elements using index Tuple Indexing Extract elements from a range of and Slicing indices Length of Tuples Use len() function Immutability Tuples are immutable, meaning elements cannot be changed once defined Lists are mutable, allowing elements to be changed Element Type Difference Tuples usually contain a heterogeneous sequence of between elements Lists usually contain a homogeneous sequence of Lists and elements Usage Tuples Tuples are accessed via unpacking or indexing Lists are accessed by iterating over the list Example List: [1, 2, 3] Tuple: ( Unpacking Tuples or Lists Number of variables must match the number of elements Unpackin Example: a, b, c = list_1 g Tuple Unpacking Packing Tuples Opposite operation to unpacking Example: list_2 = 2, 4, 5 Packing Parentheses are not needed but recommended Unordered collection with no duplicate elements Supports mathematical operations like union, intersection, difference, and symmetric difference Introduction to Sets Defined using a pair of braces, { } Syntax Elements separated by commas Input: {3, 3, 2, 3, 1, 4, 5, 6, 4, 2} Example Output: {1, 2, 3, 4, 5, 6} Union of Sets Combines all elements from both sets Example: {1, 2, 3} union {2, 4, 5, 6} results in {1, 2, 3, 4, 5, 6} Intersection of Sets Finds common elements between sets Set Example: Operations {1, 2, 3} intersection {2, 4, 5, 6} results in {2} Subset Check Checks if one set is a subset of another Example: {1, 2, 3} is a subset of {1, 2, 3, 4, 5} Indexing by Keys Keys can be a string, number, or tuple Keys cannot be a list Introduction to Key-Value Pairs Dictionaries Each key maps to a corresponding value Defined using braces { } Elements are comma-separated key:value pairs Use the key to access elements: dictionary[key] Getting All Keys and Values Use keys() method to get all keys Dictionary Use values() method to get all values Determining Dictionary Size Methods Use len() function to get the size Defining and Modifying Dictionaries Define an empty dictionary and add elements later Turn a list of tuples into a dictionary Array/matrix construct usage Fundamental numerical computing module Coded in Python and C for speed Introduction Important Features of NumPy to NumPy Powerful N-dimensional array object Sophisticated broadcasting functions Useful linear algebra, Fourier transform, and random number capabilities Using np.array function Convert a list to an array Creating 1D array Creating Example: x = np.array([1, 4, 3]) Arrays Creating 2D array Example: y = np.array([[1, 4, 3], [9, 2, 7]]) Use nested lists to represent rows Array Accessing 1D NumPy Array Elements Indexing and Use index to indicate location Example: x returns 4 Slicing Example: x[1:] returns array([4, 3]) Example: x[-1] returns 3 Accessing 2D NumPy Array Elements Use M[r, c] for row and column Example: y[0, 1] returns 4 Example: y[0, :] returns array([1, 4, 3]) Example: y[:, -1] returns array([3, 7]) Example: y[:, [0, 2]] returns array([[1, 3], [9, 7]]) Predefined np.zeros Arrays Generates an array with all elements as 0 Example: np.zeros((3, 5)) creates a 3x5 array of zeros np.ones Generates an array with all elements as 1 Example: np.ones((5, 3)) creates a 5x3 array of ones Shape of array defined in a tuple 1D array: np.ones(5) np.empty Generates an array with random very small numbers Example: np.empty(3) creates a 1D array with 3 elements Reassigning Single and Multiple Elements Use array indexing and assignment operator Reassign multiple elements to a single number Ensure the number of elements being Array assigned and assigned are the same Creating Arrays Operations Use array indexing Operations Between Scalars and Arrays Add, subtract, multiply, and divide scalars with arrays Square every element of an array Verify reflexivity of scalar addition and multiplication Storing, retrieving, and Importance of manipulating information is crucial in scientific and Data Handling engineering fields Assigning Essential tool for managing data values Variables Summary Int, float, and boolean for Data Types in single values Strings, lists, tuples, sets, Python and dictionaries for sequential data Powerful data structure NumPy Array widely used in scientific computing