Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore 3. Data Types in Python

3. Data Types in Python

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-04-28 09:37:43

Description: 3. Data Types in Python

Search

Read the Text Version

Course On Python Basics UNIT - 3:DATA TYPES IN PYTHON Structure 1.0Learning Objectives 1.1Introduction to Data Types 1.2Variables and Data Types in Python 1.3Strings in Python 1.4Lists in Python 1.5Tuples in Python 1.6Sets in Python 1.7Dictionary in Python 1.8Arrays in Python 1.9Summary 1.10 Glossary 1.11 References Page 1 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.0 Learning Objectives After studying this unit, you will be able to:  Understand Data Types in programming  Understand variables and data types used in python  Explain Strings, Lists, Tuples, Sets, Dictionaries and Arrays in python  Learn to implement Strings, Lists, Tuples, Sets, Dictionaries and Array data types in python programming. 1.1 Introduction to Data Types A data type is a categorization in programming that determines the type of value a variable possesses and the types of mathematical, relational, and logical operations that may be performed on it without creating an error. A string, for instance, is a data type for classifying text, while an integer is a data type for classifying entire integers. The data type specifies which actions are safe to conduct when creating, transforming, or using the variable in some other calculation. A software language is considered to be highly typed when it allows a variable to be only utilised in order to respect its data type. Because it is rational to request the system to multiply a float by an integer (1.7 x 3), it is unreasonable to ask the system to multiply a float by a string, this eliminates mistakes (1.5 x Jacob). A programming language is considered to be weakly typed if it permits a variable of one type of data to be used as if it were a result of another data type. The idea of strongly typed or weakly typed coding is a misconception from a technical standpoint. Every variable's value has a static type in each and every programming language, however the type may be one whose values are Page 2 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics categorised into one or more classes. While some classes describe how the value of a data type would be compiled or interpreted, other classes' values are not annotated by their class until run-time. Type safety refers to how well a programming language prohibits or avoids type errors. Some of the common data types are as follows: Data Type Used for Example String Alphanumeric Hello Leaner, James465 characters Integer Whole numbers 10,19,45 Character Encoding text 65 (in ASCII, 65 is a numerically upper case 'A') Float Number with a decimal 3.14, 9.86, 22.32 point Boolean Representing logical True, False values 1.2 Variables and Data types in python Variables and data types are the values that change in Python, as the name implies. A variable is a memory region where you store a value in a computer Page 3 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics language. According to the requirements, the value you've saved could change in the future. In Python, a variable is formed when a value is set to it. Declaring a variable in Python does not need any further instructions. While writing a variable, we must adhere to certain laws and regulations. Let us now have a look at the variable definition and declarations to see how we declare a variable in Python. To define a variable in Python, there are no further instructions. The variable is defined as soon as a value is set to it. When declaring a variable, there are a few considerations to bear in mind:  A number cannot be used as the first character in the variable name.  Only a character or an underscore can be used as the first character.  Python variables are case sensitive.  Only alpha-numeric sequences and underscores are allowed.  There are no special characters permitted. Python has a number of data types. Let's take a glance at Python's data types. Page 4 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics A data type is assigned to each value declared in Python. Variables are instances of data types, which are represented by classes. In Python, there are primarily six data types based on the features they hold. Although, while dealing with loops in Python, there is one additional data type range that is frequently employed. Page 5 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.3 Strings in Python Strings are arrays of bytes in Python that represent Unicode characters. However, because Python lacks a character data type, a single character is merely a one-length string. Square brackets could be used to retrieve the string's components. Let us now look at various operation we can perform using strings.  Creating and Accessing Strings: In Python, single quotes, double quotes, and even triple quotes can be used to generate strings. Example: Page 6 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: Individual characters in a String can be retrieved using the Indexing function in Python. Negative address references, such as -1 for the final character, -2 for the second last character, and so on, allow negative address references to retrieve characters out from back of the String. An IndexError will occur if an index is accessed outside of the range. Only integers, floats, and other kinds that will trigger a TypeError are allowed as indexes. Page 7 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 8 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  Updating and deleting from string Updating or deleting characters from a String is really not permitted in Python. Since item assignment or deletion from a String also isn't supported, this will result in an error. Although there is an integrated del keyword that may be used to delete the entire String. Because Strings are permanent, their elements cannot be modified once they have been allocated. The same name can only be transferred to fresh strings. Example: Updating entire string. Page 9 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: Example: Deleting entire string Page 10 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Formatting string: The format() function, which is a very flexible and effective tool for formatting Strings, may be used to format strings in Python. Curly braces are placeholders in the String Format function that can hold parameters as per location or keyword to set the order. Although this can be a touch cumbersome at times, we could also give keyword arguments here. You may use the str.format function to set accuracy, rounding, and zero padding, among other things. For the sake of this article, we'll merely cover the fundamentals. Python string formatting is indeed a useful tool for Python programmers on a daily basis. Strings appear to be formatted in a similar fashion in each coding Page 11 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics language. It's also a big reason why we utilise scripting languages in the first place. Example: Output: 1.4Lists in Python Lists are similar to dynamically scaled arrays (vector in C++ & ArrayList in Java) that are specified in other languages. Lists don't have to be homogenous all of the time, which makes it Python's most powerful tool. DataTypes such as Integers, Strings, and Objects may all be found in a single list. Lists are Page 12 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics changeable, which means they may be changed after they've been created. In Python, lists are sorted and have a count. A list's elements are indexed in a certain order, with 0 serving as the first index. Every element inside the list does have its own separate spot in the list, allowing duplication of components in the list while maintaining the credibility of each member. Let us now look at various operation we can perform using lists.  Creating a list: In Python, you may make a list by simply putting the sequence inside square brackets [ ]. A list, unlike Sets, does not require a built-in function to be created. Example: Output: Page 13 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  Adding elements to a list: The built-in append() method may be used to add elements to the List. The append() function can only add one element to the list at a time; loops are needed to add many entries to the list with the append() method. Because tuples are immutable, they may also be added to the list using the append function. Lists, unlike Sets, may be appended to an existing list using the append() function. The append() function only works for adding entries to the end of the List; the insert() function is used for adding elements to the appropriate location. Unlike append(), which just requires one parameter, insert() requires two arguments (position, value) Apart from the append() and insert() functions, there is one additional technique for adding elements to a list: extend(). This function is used to add many entries to the end of the list at the same time. Example: Page 14 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Removing elements from the list: The built-in remove() method can be used to remove elements from the List, however if the element doesn't exist in the list, an Error will occur. The Remove() function only eliminates one item at a time; the iterator is used to delete a range of elements. Removes the provided object with the remove() function. The pop() method could be used to delete and return an element from a list, but it only removes the final element by default. To delete any element from a specified place in the list, supply the position of the element as a parameter to the pop() method. Page 15 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 16 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.5Tuples in Python Tuple is a list-like collection of Python objects. A tuple is a collection of items that can be of any type and are indexed by integers. 'Commas' are used to separate the values of a tuple. It is more customary to define a tuple by terminating the series of values in parentheses, even if it is not required. This makes understanding Python tuples a lot easier. Let us now look at various operation we can perform using tuples.  Creating Tuples: Tuples are produced in Python by putting a series of numbers separated by a 'comma', with or without the utilization parenthesis to group the data. Example: Page 17 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Accessing and Concatenation Tuples: Tuples are immutable and often include a succession of heterogeneous items that may be retrieved by indexing (or even by attribute in the case of named tuples). Lists are changeable, and its elements are generally homogenous, and they may be accessed by iterating through them. The technique of connecting two or even more Tuples is known as tuple concatenation. The '+' operator is used for concatenation. Tuples are always concatenated from the end of the previous tuple. On Tuples, other calculations do not apply. Page 18 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 19 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  Deleting Tuples: Tuples are immutable, which means they can't be deleted in parts. The del() function is used to remove the whole tuple. Example: Output: Page 20 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.6 Sets in Python Set is just an unordered data type collection that is iterable, changeable, and contains no duplicate items in Python. The order of items in a set is indefinite, even if it contains a variety of them. The main advantage of utilising a set over a list is that it provides a highly efficient way for determining if a certain member is in the set. Let us now look at various operation we can perform using tuples.  Creating a set: Sets can be generated with the built-in set() method and an iterable objects or a sequence by enclosing the sequence in curly braces and separating it with a comma. Example: Page 21 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Adding elements to a set: The built-in add() method can be used to add elements to the Set. The add() function can only add one element to the set at a time; loops are also used to add numerous pieces at once with the add() method. The Update() function is used to add two or more components. The update() function takes as inputs lists, strings, tuples, and other collections. Duplicate items are avoided in each of these scenarios. Page 22 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 23 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  Removing elements from sets: The built-in remove() method can be used to delete elements from the Set, however if the element doesn't exist in the set, a KeyError is thrown. Use discard() to delete entries out of a set without causing a KeyError; if indeed the element does not occur in the set, it will stay unaffected. The Pop() method could also be used to remove and return one element from a set; however, it only removes the set's final element. The clear() method is used to delete all of the elements from set. Example: Page 24 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output: 1.7Dictionary in Python In Python, a dictionary is an unordered set of data values which can be used to store and manage values like a map. Unlike other Data Types, which can only carry a single value as just an element, Dictionary can hold a key:value pair. The dictionary includes a key-value pair to raise productivity. Let us now look at various operation we can perform using dictionary.  Creating a dictionary: A Dictionary is built in Python by enclosing a succession of entries in curly braces and separating them with a comma. The Dictionary stores sets of Page 25 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics values, one of which is the Key while the other is the Key:value pair element. In a dictionary, values could be of any data type and it can be replicated, but keys cannot be copied and must be immutable. The built-in method dict may also be used to generate a dictionary (). By just putting two curly brackets, an empty dictionary may be built. Example: Page 26 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Adding elements to dictionary: The addition of items in the Python Dictionary may be done in a variety of ways one of them is Dict[Key] = ‘Value’. The built-in update() function may be used to update an existing value in a Dictionary. An existing Dictionary can also have nested key values added to it. Example: Page 27 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Removing elements from dictionary: The del keyword may be used to delete keys in the Python Dictionary. Actual values from a dictionary, as well as the entire dictionary, can be erased using the del keyword. Values inside a nested dictionary could also be removed with the del keyword and a specified nested key and value to be removed from such a nested Dictionary. The Pop() function returns and deletes the item of the provided key. The clear() function may be used to erase all elements from a dictionary at once. Page 28 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 29 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.8Arrays in Python A collection of things stored in contiguous memory spaces is referred to as an array. The objective is to group together goods of the same category. This makes calculating the position of each element easy by simply adding an offset to a base value, such as the memory address of the array's first member (often signified by the array's name). For simplicity, imagine an array as a flight of stairs with a value (let's say one among your buddies) on each level. You may use this to locate any of your pals merely by knowing how many steps they have taken. In Python, there is a module called array that deals with arrays. They're beneficial when we simply need to manipulate values of a single data type. Lists can be treated as arrays. The kind of entries recorded in a list, however, cannot be restricted by the user. While using the array package to generate arrays, all of the array's elements should be of the similar type. Let us now look at various operation we can perform using array.  Creating an array: Importing the array module in Python allows you to build an array. array (data type, value list) creates an array using the supplied data type and value list as parameters. Page 30 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 31 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  Adding elements to array: The built-in insert() method may be used to add elements to the Array. Insert is a function that allows you to add one or maybe more data elements to an array. A new element can indeed be added at the beginning, end, or just any provided index of the array, depending on the necessity. append() may also be used to append the value specified in its arguments to the array's end. Example: Page 32 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Output:  Removing elements from array: The built-in remove() method can be used to delete elements from the array, however if the element doesn't exist in the set, an error occurs. The Remove() function simply removes single element at a time; an iterator is needed to remove a range of elements. The pop() method can be used to remove and return an element from an array, but it only removes the final element by default. To remove an element from a specified place in the array, supply the index of the element as an argument to the pop() method. Page 33 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics Example: Output: Page 34 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics 1.9Summary  Python comes with a number of built-in data types.  Numeric data types such as integers, floats, and complex numbers are among these data types.  Letters, integers, spaces, and punctuation make up the string data type.  Python also includes container data types, which may hold a large number of values.  Lists, tuples, and dictionaries are examples of container data types.  Square brackets [ ] can be used to index and slice strings, lists, and tuples. 1.10 Glossary  Element: Python has elements such as strings (text), numbers (integers and floating-point values), tuples (basic sequences), lists (more flexible sequences), and dictionaries.  Index: An index is a way of organising information by constructing keywords or a list of the information.  Keyword: Keywords are reserved terms in coding that have a specific meaning for the compiler.  Iterable: Iterable is a kind of object that may be looped or iterated over using a for loop. 1.11 References  https://docs.python.org/3/  https://docs.python.org/3/library/datatypes.html Page 35 of 36 All Rights Reserved. Vol. TLE001/03-2022

Course On Python Basics  https://docs.python.org/3/library/stdtypes.html  https://www.learnpython.org/en/Variables_and_Types Page 36 of 36 All Rights Reserved. Vol. TLE001/03-2022


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook