Document Details

ToughestTaylor

Uploaded by ToughestTaylor

Pimpri Chinchwad University

Tags

python programming data types collections programming

Full Transcript

Module I Introduction to Python: Python Introduction- Features, Identifiers, Reserved words, Indentation, Comments, Built-in Data types and their Methods: Strings, List, Tuples, Dictionary, and Set - Type Conversion- Operators. Execution of a Python, Program, Writing Our Fir...

Module I Introduction to Python: Python Introduction- Features, Identifiers, Reserved words, Indentation, Comments, Built-in Data types and their Methods: Strings, List, Tuples, Dictionary, and Set - Type Conversion- Operators. Execution of a Python, Program, Writing Our First Python Program, Statements Precedence of Operators. 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. 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. mytuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry") print(thistuple) TUPLE 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: thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) tuple Tuple Length  To determine how many items a tuple has, use the len() function:  thistuple = ("apple", "banana", "cherry") print(len(thistuple)) Create Tuple With One Item To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. Example One item tuple, remember the comma: thistuple = ("apple",) print(type(thistuple)) #NOT a tuple thistuple = ("apple") print(type(thistuple)) Tuple Tuple Items - Data Types Tuple items can be of any data type: Example String, int and boolean data types: tuple1 = ("apple", "banana", "cherry") tuple2 = (1, 5, 7, 9, 3) tuple3 = (True, False, False) A tuple can contain different data types: Example A tuple with strings, integers and boolean values: tuple1 = ("abc", 34, True, 40, "male") Tuple type() From Python's perspective, tuples are defined as objects with the data type 'tuple': Example What is the data type of a tuple? mytuple = ("apple", "banana", "cherry") print(type(mytuple)) The tuple() Constructor It is also possible to use the tuple() constructor to make a tuple. Example Using the tuple() method to make a tuple: thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(thistuple) 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. When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security. tuple Access Tuple Items You can access tuple items by referring to the index number, inside square brackets: ExampleGet your own Python Server Print the second item in the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple) Negative Indexing Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc. Print the last item of the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) Tuple 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. Example Return the third, fourth, and fifth item: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "me lon", "mango") print(thistuple[2:5]) Note: The search will start at index 2 (included) and end at index 5 (not included). Tuple Example This example returns the items from the beginning to, but NOT included, "kiwi": thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[:4]) Range of Negative Indexes Specify negative indexes if you want to start the search from the end of the tuple: Example This example returns the items from index -4 (included) to index -1 (excluded) thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[-4:-1]) Tuple Check if Item Exists To determine if a specified item is present in a tuple use the in keyword: Example Check if "apple" is present in the tuple: thistuple = ("apple", "banana", "cherry") if "apple" in thistuple: print("Yes, 'apple' is in the fruits tuple") Python - Update Tuples Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created. 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. Example Convert the tuple into a list to be able to change it: x = ("apple", "banana", "cherry") y = list(x) y = "kiwi" x = tuple(y) print(x) Python - Update Tuples 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. Example Convert the tuple into a list, add "orange", and convert it back into a tuple: thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) Python - Update Tuples 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: Example Create a new tuple with the value "orange", and add that tuple: thistuple = ("apple", "banana", "cherry") y = ("orange",) thistuple += y print(thistuple) Python - 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: Example Convert the tuple into a list, remove "apple", and convert it back into a tuple: thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.remove("apple") thistuple = tuple(y) you can delete the tuple completely: Example The del keyword can delete the tuple completely: thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) #this will raise an error because the tuple no longer exists Unpacking a Tuple When we create a tuple, we normally assign values to it. This is called "packing" a tuple: Example Packing a tuple: fruits = ("apple", "banana", "cherry") But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking": Example Unpacking a tuple: fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) Unpacking a Tuple Using Asterisk* If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list: Example Assign the rest of the values as a list called "red": fruits = ("apple", "banana", "cherry", "strawberry", "raspberry") (green, yellow, *red) = fruits print(green) print(yellow) print(red) fruits = ("apple", "mango", "papaya", "pineapple", "cherry") (green, *tropic, red) = fruits print(green) print(tropic) print(red) Python - Loop Tuples ExampleGet your own Python Serve Iterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) Loop Through the Index Numbers You can also loop through the tuple items by referring to their index number. Use the range() and len() functions to create a suitable iterable. Example Print all items by referring to their index number: thistuple = ("apple", "banana", "cherry") for i in range(len(thistuple)): print(thistuple[i]) Python - Loop Tuples Using a While Loop You can loop through the tuple items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes. Remember to increase the index by 1 after each iteration. Example Print all items, using a while loop to go through all the index numbers: thistuple = ("apple", "banana", "cherry") i = 0 while i < len(thistuple): print(thistuple[i]) i = i + 1 Join Two Tuples Join two tuples: tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) Multiply the fruits tuple by 2: fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 print(mytuple) Strings Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function: print("Hello") print('Hello’) Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string: a = "Hello" print(a) Strings Multiline Strings You can assign a multiline string to a variable by using three quotes: a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(a) 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. Strings 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. Example Get the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a) Strings Strings with loops Example Loop through the letters in the word "banana": for x in "banana": print(x) len() function return length a = "Hello, World!" print(len(a)) Check if "free" is present in the following text: txt = "The best things in life are free!" print("free" in txt) Strings Example txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") txt = "The best things in life are free!" print("expensive" not in txt) txt = "The best things in life are free!" if "expensive" not in txt: print("No, 'expensive' is NOT present.") 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. Get the characters from position 2 to position 5 (not included): b = "Hello, World!" print(b[2:5]) Strings Slicing Get the characters from the start to position 5 (not included): b = "Hello, World!" print(b[:5]) Get the characters from position 2, and all the way to the end: b = "Hello, World!" print(b[2:]) Get the characters: From: "o" in "World!" (position -5) To, but not included: "d" in "World!" (position -2): b = "Hello, World!" print(b[-5:-2]) Strings Update operations The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) The lower() method returns the string in lower case: a = "Hello, World!“ print(a.lower()) The strip() method removes any whitespace from the beginning or the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!“ The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J")) Split String The split() method returns a list where the text between the specified separator becomes the list items. Example The split() method splits the string into substrings if it finds instances of the separator: a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!'] String Concatenation To concatenate, or combine, two strings you can use the + operator. Example Merge variable a with variable b into variable c: a = "Hello" b = "World" c=a+b print(c) To add a space between them, add a " ": a = "Hello" b = "World" c=a+""+b print(c) String Format As we learned in the Python Variables chapter, we cannot combine strings and numbers like this Example age = 36 txt = "My name is John, I am " + age print(txt) But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: Example Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) String Format The format() method takes unlimited number of arguments, and are placed into the respective placeholders: Example quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: Example quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) strings 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. Example The escape character allows you to use double quotes when you normally would not be allowed: txt = "We are the so-called \"Vikings\" from the north.“ String Methods Python has a set of built-in methods that you can use on strings. Method Description isalnum() Returns True if all characters in the string are alphanumeric capitalize() Converts the first character to upper case isalpha() Returns True if all characters in the string are casefold() Converts string into lower case in the alphabet center() Returns a centered string isascii() Returns True if all characters in the string are ascii characters count() Returns the number of times a specified value occurs in a string isdecimal() Returns True if all characters in the string are decimals encode() Returns an encoded version of the string isdigit() Returns True if all characters in the string are digits endswith() Returns true if the string ends with the specified value isidentifier() Returns True if the string is an identifier expandtabs() Sets the tab size of the string islower() Returns True if all characters in the string are find() Searches the string for a specified value and lower case returns the position of where it was found isnumeric() Returns True if all characters in the string are numeric format() Formats specified values in a string isprintable() Returns True if all characters in the string are printable format_map() Formats specified values in a string isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of index() Searches the string for a specified value and a title returns the position of where it was found isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable split() Splits the string at the to the end of the string specified separator, and returns a list ljust() Returns a left justified version of the string splitlines() Splits the string at line breaks lower() Converts a string into lower case and returns a list lstrip() Returns a left trim version of the string startswith() Returns true if the string starts with the specified maketrans() Returns a translation table to be value used in translations partition() Returns a tuple where the string is parted into three parts strip() Returns a trimmed version of the string replace() Returns a string where a specified value is replaced with a specified swapcase() Swaps cases, lower case value becomes upper case and vice rfind() Searches the string for a specified versa value and returns the last position of where it was found title() Converts the first character of each word to upper case rindex() Searches the string for a specified value and returns the last position of where it was found translate() Returns a translated string rjust() Returns a right justified version of upper() Converts a string into upper the string case rpartition() Returns a tuple where the string is parted into three parts zfill() Fills the string with a specified number of 0 values rsplit() Splits the string at the specified at the beginning separator, and returns a list rstrip() Returns a right trim version of the string Python Sets myset = {"apple", "banana", "cherry"} Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is unordered, unchangeable*, and unindexed. * Note: Set items are unchangeable, but you can remove items and add new items. Sets are written with curly brackets. Create a Set: thisset = {"apple", "banana", "cherry"} print(thisset) Python Sets Note: Sets are unordered, so you cannot be sure in which order the items will appear. Set Items:- Set items are unordered, unchangeable, and do not allow duplicate values. Unordered:- Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key. Unchangeable:- Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items. Duplicates Not Allowed:- Sets cannot have two items with the same value. Python Sets Example Duplicate values will be ignored: thisset = {"apple", "banana", "cherry", "apple"} print(thisset) Output:- {'banana', 'cherry', 'apple'} 'apple’} Note: The values True and 1 are considered the same value in sets, and are treated as duplicates: Example True and 1 is considered the same value: thisset = {"apple", "banana", "cherry", True, 1, 2} print(thisset) Python Sets Get the Length of a Set To determine how many items a set has, use the len() function. Example Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset)) Set Items - Data Types Set items can be of any data type: Example String, int and boolean data types: set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} Python Sets A set can contain different data types: Example A set with strings, integers and boolean values: set1 = {"abc", 34, True, 40, "male"} type() From Python's perspective, sets are defined as objects with the data type 'set': > 2 = 15 (means 0000 1111) specified by the right operand. Python Logical Operators Operator Description Example and Logical AND If both the operands are true then condition becomes true. (a and b) is true. If any of the two operands are non-zero then condition or Logical OR (a or b) is true. becomes true. not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false. Python Membership Operators Python's membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators. Operator Description Example Evaluates to true if it finds a variable in x in y, here in results in a 1 if in the specified sequence and false x is a member of sequence y. otherwise. Evaluates to true if it does not finds a x not in y, here not in results not in variable in the specified sequence and in a 1 if x is not a member of false otherwise. sequence y. Python Identity Operators Identity operators compare the memory locations of two objects. There are two Identity operators Operator Description Example Evaluates to true if the variables on either x is y, here is results in 1 if is side of the operator point to the same id(x) equals id(y). object and false otherwise. Evaluates to false if the variables on either x is not y, here is not results is not side of the operator point to the same in 1 if id(x) is not equal to object and true otherwise. id(y). Python Operators Precedence Example Operator Description ** Exponentiation (raise to the power) Complement, unary plus and minus (method names for the last two are +@ ~+- and -@) * / % // Multiply, divide, modulo and floor division +- Addition and subtraction >> ^| Bitwise exclusive `OR' and regular `OR' >= Comparison operators == != Equality operators = %= /= //= -= += *= **= Assignment operators is is not Identity operators in not in Membership operators not or and Logical operators Python Operators Precedence Example Operator precedence affects how an expression is evaluated. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. a = 20 b = 10 When you execute the program, it produces the c = 15 following result − d=5 Value of (a + b) * c / d is 90 Value of ((a + b) * c) / d is 90 e=0 Value of (a + b) * (c / d) is 90 e = (a + b) * c / d #( 30 * 15 ) / 5 Value of a + (b * c) / d is 50 print ("Value of (a + b) * c / d is ", e) e = ((a + b) * c) / d # (30 * 15 ) / 5 print ("Value of ((a + b) * c) / d is ", e) e = (a + b) * (c / d); # (30) * (15/5) print ("Value of (a + b) * (c / d) is ", e) e = a + (b * c) / d; # 20 + (150/5) print ("Value of a + (b * c) / d is ", e)

Use Quizgecko on...
Browser
Browser