Introduction to Python PDF

Document Details

John Randolph M. Peñaredondo

Tags

python programming programming language introduction to python computer programming

Summary

This document provides an introduction to the Python programming language, covering its basics, features, and syntax. It details why Python is a popular choice, what it can do, and how its syntax compares to other languages.

Full Transcript

INTRODUCTION TO PYTHON Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. THINGS TO DO: To discuss python basics To have a quiz for last week’s lesson- Introduction to Data Structures and Algorithms. PYTHON DISCUSSION CONTENTS INTRO SYNTAX...

INTRODUCTION TO PYTHON Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. THINGS TO DO: To discuss python basics To have a quiz for last week’s lesson- Introduction to Data Structures and Algorithms. PYTHON DISCUSSION CONTENTS INTRO SYNTAX COMMENTS VARIABLES DATA TYPES NUMBERS CASTING STRINGS BOOLEANS OPERATORS LIST MR. PEÑAREDONDO, JOHN RANDOLF M. A PYTHON INTRODUCTION ITEC 204- DATA STRUCTURES AND ALGORITHMS WHAT IS PYTHON? Python is a programming language. It was made to be open source and easy to read. A Dutch programmer named Guido van Rossum made Python in 1991. He named it after the television program Monty Python's Flying Circus. Many Python examples and tutorials include jokes from the show. USES OF PYTHON: web development (server-side), software development, mathematics, system scripting. WHAT CAN PYTHON DO? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. WHY PYTHON? Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-oriented way or a functional way. PYTHON SYNTAX COMPARED TO OTHER PROGRAMMING LANGUAGES Python was designed for readability, and has some similarities to the English language with influence from mathematics. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. MR. PEÑAREDONDO, JOHN RANDOLF M. B PYTHON SYNTAX ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON INDENTATION Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. PYTHON INDENTATION The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: MR. PEÑAREDONDO, JOHN RANDOLF M. C PYTHON COMMENTS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON COMMENTS Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. SINGLE LINE COMMENT: MULTIPLE LINE COMMENT: MR. PEÑAREDONDO, JOHN RANDOLF M. D PYTHON VARIABLES ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON VARIABLES Variables are containers for storing data values. Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set. CASTING If you want to specify the data type of a variable, this can be done with casting. which means if you want to change a data type to another data type we do, Casting. GET THE TYPE You can get the data type of a variable with the type() function. SINGLE OR DOUBLE QUOTES? String variables can be declared either by using single or double quotes CASE-SENSITIVE Variable names are case-sensitive. MR. PEÑAREDONDO, JOHN RANDOLF M. D2 PYTHON - VARIABLE NAMES ITEC 204- DATA STRUCTURES AND ALGORITHMS VARIABLE NAMES A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables) A variable name cannot be any of the Python keywords. MULTI WORDS VARIABLE NAMES Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable: Camel Case- Each word, except the first, starts with a capital letter Pascal Case- Each word starts with a capital letter Snake Case- Each word is separated by an underscore character MR. PEÑAREDONDO, JOHN RANDOLF M. PYTHON VARIABLES D3 - ASSIGN MULTIPLE VALUES ITEC 204- DATA STRUCTURES AND ALGORITHMS MANY VALUES TO MULTIPLE VARIABLES Python allows you to assign values to multiple variables in one line: Note: Make sure the number of variables matches the number of values, or else you will get an error. ONE VALUE TO MULTIPLE VARIABLES You can assign the same value to multiple variables in one line: UNPACK A COLLECTION If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. MR. PEÑAREDONDO, JOHN RANDOLF M. D4 PYTHON - OUTPUT VARIABLES ITEC 204- DATA STRUCTURES AND ALGORITHMS OUTPUT VARIABLES The Python print() function is often used to output variables. OUTPUT VARIABLES In the print() function, you output multiple variables, separated by a comma: OUTPUT VARIABLES You can also use the + operator to output multiple variables: Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome". NOTES: For numbers, the + character works as a mathematical operator: In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error: NOTES: The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types: MR. PEÑAREDONDO, JOHN RANDOLF M. D5 PYTHON - GLOBAL VARIABLES ITEC 204- DATA STRUCTURES AND ALGORITHMS GLOBAL VARIABLES Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables. Global variables can be used by everyone, both inside of functions and outside. GLOBAL VARIABLES If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value. NOTE: Which means that we can create the same multiple variable names that will not overwrite the original value of the variable as long as the variables were declared differently by means of a global and a local variable (using a function). THE GLOBAL KEYWORD Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword. Also, use the global keyword if you want to change a global variable inside a function. WHY THE OUTPUT IS 2? EVEN THOUGH WE USED DECLARE X AS A GLOBAL VARIABLE INSIDE THE FUNCTIONS? ANSWER TO EXECUTE THE CODES INSIDE THE FUNCTIONS, DON’T FORGET TO CALL IT. MR. PEÑAREDONDO, JOHN RANDOLF M. E PYTHON DATA TYPES ITEC 204- DATA STRUCTURES AND ALGORITHMS BUILT-IN DATA TYPES In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: GETTING THE DATA TYPE You can get the data type of any object by using the type() function: SETTING THE DATA TYPE In Python, the data type is set when you assign a value to a variable: HOW TO APPLY IT IN PROGRAMMING? SETTING THE SPECIFIC DATA TYPE If you want to specify the data type, you can use the following constructor functions: HOW TO APPLY IT IN PROGRAMMING? HOW TO APPLY IT IN PROGRAMMING? In Python, the bool() function converts non-zero numbers to True. Since -3.1 is a non-zero float, bool(-3.1) evaluates to True. So, is_active is True. Non-zero Values: Any value that is not zero, whether it's an integer or a floating-point number, is considered True. This includes positive and negative numbers. So, bool(3) and bool(-3.1) both evaluate to True. MR. PEÑAREDONDO, JOHN RANDOLF M. F PYTHON NUMBERS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON NUMBERS There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them: INT OR INTEGER Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. FLOAT Float, or "floating point number" is a number, positive or negative, containing one or more decimals. FLOAT Float can also be scientific numbers with an "e" to indicate the power of 10. COMPLEX Complex numbers are written with a "j" as the imaginary part: TYPE CONVERSION You can convert from one type to another with the int(), float(), and complex() methods: Convert from one type to another TYPE CONVERSION You can convert from one type to another with the int(), float(), and complex() methods: Convert from one type to another Note: You cannot convert complex numbers into another number type. Why? because of these following: Mathematical Nature, Conversion Limits, and Conceptual Differences. RANDOM NUMBERS Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: MR. PEÑAREDONDO, JOHN RANDOLF M. G PYTHON CASTING ITEC 204- DATA STRUCTURES AND ALGORITHMS SPECIFY A VARIABLE TYPE There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals INTEGERS Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) FLOAT Casting in python is therefore done using constructor functions: float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) STRING Casting in python is therefore done using constructor functions: str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals MR. PEÑAREDONDO, JOHN RANDOLF M. H PYTHON STRINGS ITEC 204- DATA STRUCTURES AND ALGORITHMS STRINGS ARE ARRAYS Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. LOOPING THROUGH A STRING Since strings are arrays, we can loop through the characters in a string, with a for loop. STRING LENGTH To get the length of a string, use the len() function. CHECK STRING To check if a certain phrase or character is present in a string, we can use the keyword in. CHECK STRING CAN BE USE IN IF STATEMENT To check if a certain phrase or character is present in a string, we can use the keyword in. CHECK IF NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. CHECK IF NOT CAN BE USE IN IF STATEMENT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. MR. PEÑAREDONDO, JOHN RANDOLF M. H2 PYTHON - SLICING STRINGS ITEC 204- DATA STRUCTURES AND ALGORITHMS SLICING You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. SLICE FROM THE START By leaving out the start index, the range will start at the first character: SLICE TO THE END By leaving out the end index, the range will go to the end: NEGATIVE INDEXING Use negative indexes to start the slice from the end of the string: MR. PEÑAREDONDO, JOHN RANDOLF M. H2 PYTHON - MODIFY STRINGS ITEC 204- DATA STRUCTURES AND ALGORITHMS UPPER CASE Python has a set of built-in methods that you can use on strings. The upper() method returns the string in upper case: LOWER CASE The lower() method returns the string in lower case: REMOVE WHITESPACE Whitespace is the space before and/or after the actual text, and very often you want to remove this space. The strip() method removes any whitespace from the beginning or the end: REPLACE STRING The replace() method replaces a string with another string: SPLIT STRING The split() method returns a list where the text between the specified separator becomes the list items. The split() method splits the string into substrings if it finds instances of the separator: MR. PEÑAREDONDO, JOHN RANDOLF M. H3 PYTHON - STRING CONCATENATION ITEC 204- DATA STRUCTURES AND ALGORITHMS STRING CONCATENATION To concatenate, or combine, two strings you can use the + operator. STRING CONCATENATION To add a space between them, add a " ": MR. PEÑAREDONDO, JOHN RANDOLF M. H4 PYTHON - FORMAT - STRINGS ITEC 204- DATA STRUCTURES AND ALGORITHMS STRING FORMAT As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: F-STRINGS F-String was introduced in Python 3.6, and is now the preferred way of formatting strings. To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations. PLACEHOLDERS AND MODIFIERS A placeholder can contain variables, operations, functions, and modifiers to format the value. Add a placeholder for the price variable: PLACEHOLDERS AND MODIFIERS A placeholder can include a modifier to format the value. A modifier is included by adding a colon : followed by a legal formatting type, like.2f which means fixed point number with 2 decimals: PLACEHOLDERS AND MODIFIERS A placeholder can contain Python code, like math operations: Perform a math operation in the placeholder, and return the result: MR. PEÑAREDONDO, JOHN RANDOLF M. H5 PYTHON - ESCAPE CHARACTERS ITEC 204- DATA STRUCTURES AND ALGORITHMS ESCAPE CHARACTER To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes: ESCAPE CHARACTER To fix this problem, use the escape character \": The escape character allows you to use double quotes when you normally would not be allowed: ESCAPE CHARACTERS Other escape characters used in Python: MR. PEÑAREDONDO, JOHN RANDOLF M. H5 PYTHON - STRING METHODS ITEC 204- DATA STRUCTURES AND ALGORITHMS STRING METHODS Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. STRING METHODS Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. STRING METHODS Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. MR. PEÑAREDONDO, JOHN RANDOLF M. I PYTHON BOOLEANS ITEC 204- DATA STRUCTURES AND ALGORITHMS BOOLEAN VALUES Booleans represent one of two values: True or False. In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer: BOOLEAN VALUES When you run a condition in an if statement, Python returns True or False: EVALUATE VALUES AND VARIABLES The bool() function allows you to evaluate any value, and give you True or False in return, Example: EVALUATE VALUES AND VARIABLES The bool() function allows you to evaluate any value, and give you True or False in return, Example: MOST VALUES ARE TRUE Almost any value is evaluated to True if it has some sort of content. Any string is True, except empty strings. Any number is True, except 0. Any list, tuple, set, and dictionary are True, except empty ones. SOME VALUES ARE FALSE In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False. SOME VALUES ARE FALSE One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False: FUNCTIONS CAN RETURN A BOOLEAN You can create functions that returns a Boolean Value: FUNCTIONS CAN RETURN A BOOLEAN You can execute code based on the Boolean answer of a function: FUNCTIONS CAN RETURN A BOOLEAN Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type: MR. PEÑAREDONDO, JOHN RANDOLF M. J PYTHON OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON OPERATORS Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators MR. PEÑAREDONDO, JOHN RANDOLF M. PYTHON J1 ARITHMETIC OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON ARITHMETIC OPERATORS Arithmetic operators are used with numeric values to perform common mathematical operations: NOTE: the floor division // rounds the result down to the nearest whole number MR. PEÑAREDONDO, JOHN RANDOLF M. PYTHON J2 ASSIGNMENT OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON ASSIGNMENT OPERATORS Assignment operators are used to assign values to variables: HOW DOES BITWISE WORK? Bitwise AND Operation: The bitwise AND operation compares each bit of the numbers involved. If both bits at the same position are 1, the resulting bit is 1. Otherwise, the resulting bit is 0. WHY DOES THE PROGRAM PRINT OUT 1? ALWAYS REMEMBER THIS LOGICAL OPERATORS TRUTH TABLE HOW DOES BITWISE WORK? Just refer to the logical operator truth table and use the binary number system. HOW DOES BITWISE WORK? Just refer to the logical operator truth table and use the binary number system. HOW DOES WALRUS OPERATOR WORKS? It allows you to assign a value to a variable as part of an expression. This was introduced in Python 3.8 and is useful when you want to both assign and use a value within the same expression. MR. PEÑAREDONDO, JOHN RANDOLF M. PYTHON J3 COMPARISON OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON COMPARISON OPERATORS Comparison operators are used to compare two values: MR. PEÑAREDONDO, JOHN RANDOLF M. J4 PYTHON LOGICAL OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON LOGICAL OPERATORS Logical operators are used to combine conditional statements: MR. PEÑAREDONDO, JOHN RANDOLF M. J5 PYTHON IDENTITY OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON IDENTITY OPERATORS Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: PYTHON IDENTITY OPERATORS Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: MR. PEÑAREDONDO, JOHN RANDOLF M. J6 PYTHON MEMBERSHIP OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON MEMBERSHIP OPERATORS Membership operators are used to test if a sequence is presented in an object: PYTHON MEMBERSHIP OPERATORS Membership operators are used to test if a sequence is presented in an object: MR. PEÑAREDONDO, JOHN RANDOLF M. J7 PYTHON BITWISE OPERATORS ITEC 204- DATA STRUCTURES AND ALGORITHMS PYTHON BITWISE OPERATORS Bitwise operators are used to compare (binary) numbers: MR. PEÑAREDONDO, JOHN RANDOLF M. J8 OPERATOR PRECEDENCE ITEC 204- DATA STRUCTURES AND ALGORITHMS OPERATOR PRECEDENCE Operator precedence describes the order in which operations are performed. The precedence order is described in the table below, starting with the highest precedence at the top. If two operators have the same precedence, the expression is evaluated from left to right. MR. PEÑAREDONDO, JOHN RANDOLF M. K PYTHON LISTS ITEC 204- DATA STRUCTURES AND ALGORITHMS LIST Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Lists are created using square brackets: LIST ITEMS List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index , the second item has index etc. ORDERED When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list. Note: There are some list methods that will change the order, but in general: the order of the items will not change. CHANGEABLE The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. ALLOW DUPLICATES Since lists are indexed, lists can have items with the same value: LIST LENGTH To determine how many items a list has, use the len() function: LIST ITEMS - DATA TYPES List items can be of any data type: THE LIST() CONSTRUCTOR It is also possible to use the list() constructor when creating a new list. HOW TO DETERMINE EACH DATA TYPE OF THE ELEMENTS OF LIST Since list can contain different data types in its collection, we can also identify its elements data type individually. MR. PEÑAREDONDO, JOHN RANDOLF M. K1 PYTHON - ACCESS LIST ITEMS ITEC 204- DATA STRUCTURES AND ALGORITHMS ACCESS ITEMS List items are indexed and you can access them by referring to the index number: ACCESS ITEMS By leaving out the end value, the range will go on to the end of the list: RANGE OF NEGATIVE INDEXES Specify negative indexes if you want to start the search from the end of the list: CHECK IF ITEM EXISTS To determine if a specified item is present in a list use the in keyword: MR. PEÑAREDONDO, JOHN RANDOLF M. K2 PYTHON - CHANGE LIST ITEMS ITEC 204- DATA STRUCTURES AND ALGORITHMS CHANGE ITEM VALUE To change the value of a specific item, refer to the index number: CHANGE A RANGE OF ITEM VALUES To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: Note: The length of the list will change when the number of items inserted does not match the number of items replaced. CHANGE A RANGE OF ITEM VALUES If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly: INSERT ITEMS To insert a new list item, without replacing any of the existing values, we can use the insert() method. The insert() method inserts an item at the specified index: Note: As a result of the example above, the list will now contain 4 items. MR. PEÑAREDONDO, JOHN RANDOLF M. K3 PYTHON - ADD LIST ITEMS ITEC 204- DATA STRUCTURES AND ALGORITHMS APPEND ITEMS To add an item to the end of the list, use the append() method: Using the append() method to append an item: INSERT ITEMS To insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index: Insert an item as the second position: Note: As a result of the examples above, the lists will now contain 4 items. EXTEND LIST To append elements from another list to the current list, use the extend() method. The elements will be added to the end of the list. ADD ANY ITERABLE The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.). Add elements of a tuple to a list: HOW DO WE INSERT NEW LIST TO OUR DESIRED INDEX NUMBER? When you use thislist[1:1] = tropical, you are essentially telling Python, "Replace the elements from index 1 to index 1 (which is an empty slice) with the elements of tropical." Since 1:1 represents a slice with no elements, it does not remove any existing elements; it just inserts the new elements at that position. SO WHY DO WE USE 1:1 AND NOT ONLY 1? If you were to try thislist = tropical, you would not be inserting the elements of tropical into the list. Instead, you would replace the element at index 1 ("banana") with the entire tropical list, which would result in a list within a list. The thislist would then contain ["apple", ["mango", "pineapple", "papaya"], "cherry"], which is not what you want if you're looking to insert the elements of tropical individually into thislist. MR. PEÑAREDONDO, JOHN RANDOLF M. K4 PYTHON - REMOVE LIST ITEMS ITEC 204- DATA STRUCTURES AND ALGORITHMS REMOVE SPECIFIED ITEM The remove() method removes the specified item. REMOVE SPECIFIED ITEM If there are more than one item with the specified value, the remove() method removes the first occurrence: REMOVE SPECIFIED ITEM If you want to use the remove() method in deleting elements in list with particular number of arguments, you can also do it with this way: REMOVE SPECIFIED INDEX The pop() method removes the specified index. REMOVE SPECIFIED INDEX If you do not specify the index, the pop() method removes the last item. REMOVE SPECIFIED INDEX The del keyword also removes the specified index: REMOVE SPECIFIED INDEX The del keyword can also delete the list completely. REMOVE SPECIFIED INDEX Since we don’t want our clients to use a program with an error, we must find ways to let our program still works even list is not present by using the ‘try and except’ statements in Python. CLEAR THE LIST The clear() method empties the list. The list still remains, but it has no content. MR. PEÑAREDONDO, JOHN RANDOLF M. K5 LOOP THROUGH A LIST ITEC 204- DATA STRUCTURES AND ALGORITHMS LOOP THROUGH A LIST You can loop through the list items by using a for loop: LOOP THROUGH THE INDEX NUMBERS You can also loop through the list items by referring to their index number. Use the range() and len() functions to create a suitable iterable. The iterable created in the example above is [0, 1, 2]. USING A WHILE LOOP You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration. USING A WHILE LOOP You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration. MR. PEÑAREDONDO, JOHN RANDOLF M. K6 PYTHON - LIST COMPREHENSION ITEC 204- DATA STRUCTURES AND ALGORITHMS LIST COMPREHENSION List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside: LIST COMPREHENSION With list comprehension you can do all that with only one line of code: THE SYNTAX newlist = [expression for item in iterable if condition == True] The return value is a new list, leaving the old list unchanged. MR. PEÑAREDONDO, JOHN RANDOLF M. K7 PYTHON - SORT LISTS ITEC 204- DATA STRUCTURES AND ALGORITHMS SORT LIST ALPHANUMERICALLY List objects have a sort() method that will sort the list alphanumerically, ascending, by default: SORT LIST ALPHANUMERICALLY Sort the list numerically: SORT DESCENDING To sort descending, use the keyword argument reverse = True: SORT DESCENDING Sort the list descending: CUSTOMIZE SORT FUNCTION You can also customize your own function by using the keyword argument key = function. The function will return a number that will be used to sort the list (the lowest number first): CASE INSENSITIVE SORT By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters Case sensitive sorting can give an unexpected result: CASE INSENSITIVE SORT Luckily we can use built-in functions as key functions when sorting a list. So if you want a case-insensitive sort function, use str.lower as a key function: REVERSE ORDER What if you want to reverse the order of a list, regardless of the alphabet? The reverse() method reverses the current sorting order of the elements. MR. PEÑAREDONDO, JOHN RANDOLF M. K8 PYTHON - COPY LISTS ITEC 204- DATA STRUCTURES AND ALGORITHMS COPY A LIST You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. USE THE COPY() METHOD You can use the built-in List method copy() to copy a list. USE THE LIST() METHOD Another way to make a copy is to use the built-in method list(). USE THE SLICE OPERATOR You can also make a copy of a list by using the : (slice) operator. MR. PEÑAREDONDO, JOHN RANDOLF M. K9 PYTHON - JOIN LISTS ITEC 204- DATA STRUCTURES AND ALGORITHMS JOIN TWO LISTS There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. JOIN TWO LISTS Another way to join two lists is by appending all the items from list2 into list1, one by one: JOIN TWO LISTS Another way to join two lists is by appending all the items from list2 into list1, one by one: JOIN TWO LISTS Or you can use the extend() method, where the purpose is to add elements from one list to another list: MR. PEÑAREDONDO, JOHN RANDOLF M. K10 PYTHON - LIST METHODS ITEC 204- DATA STRUCTURES AND ALGORITHMS LIST METHODS MR. PEÑAREDONDO, JOHN RANDOLF M. L PYTHON TUPLES ITEC 204- DATA STRUCTURES AND ALGORITHMS TUPLE Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets. TUPLE ITEMS Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index , the second item has index etc. ORDERED When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. UNCHANGEABLE Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. ALLOW DUPLICATES Since tuples are indexed, they can have items with the same value: TUPLE LENGTH To determine how many items a tuple has, use the len() function: TUPLE ITEMS - DATA TYPES Tuple items can be of any data type: A TUPLE CAN CONTAIN DIFFERENT DATA TYPES: Tuple items can be of any data type: TO DETERMINE THE DATA TYPE OF EACH ELEMENT WE CAN USE FOR LOOP THE TUPLE() CONSTRUCTOR It is also possible to use the tuple() constructor to make a tuple. PYTHON COLLECTIONS (ARRAYS) There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members. Dictionary is a collection which is ordered** and changeable. No duplicate members. MR. PEÑAREDONDO, JOHN RANDOLF M. L1 ACCESS TUPLE ITEMS ITEC 204- DATA STRUCTURES AND ALGORITHMS ACCESS TUPLE ITEMS You can access tuple items by referring to the index number, inside square brackets: Note: The first item has index 0. RANGE OF INDEXES You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items. Note: The search will start at index 2 (included) and end at index 5 (not included). RANGE OF INDEXES By leaving out the start value, the range will start at the first item: CHECK IF ITEM EXISTS To determine if a specified item is present in a tuple use the in keyword: MR. PEÑAREDONDO, JOHN RANDOLF M. L2 PYTHON - UPDATE TUPLES ITEC 204- DATA STRUCTURES AND ALGORITHMS CHANGE TUPLE VALUES Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple. ADD ITEMS Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple. 1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple. ADD ITEMS 2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple: Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple. REMOVE ITEMS Note: You cannot remove items in a tuple. Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items: REMOVE ITEMS Or you can delete the tuple completely The del keyword can delete the tuple completely:

Use Quizgecko on...
Browser
Browser