025060301-ME-RO-Python Programming-Handbook (1).pdf

Full Transcript

Diploma in Mechanical Engineering Diploma in Automation & Robotics Python Programming Python Programming Python 3 is a truly versatile programming language, loved both by web developers, data scientists and the engineers. And there are several good reasons for that! Python is open-so...

Diploma in Mechanical Engineering Diploma in Automation & Robotics Python Programming Python Programming Python 3 is a truly versatile programming language, loved both by web developers, data scientists and the engineers. And there are several good reasons for that! Python is open-source and has a great support community, Plus, extensive support libraries. Its data structures are user-friendly. Once you get a hang of it, your development speed & productivity will soar! PYTHON PROGRAMMING Department of Mechanical Engineering Automation & Robotics Prepared and Compiled by Department of Mechanical Engineering Automation & Robotics Disclaimer This handbook is compiled to provide subject information to the students. Every effort has been made to avoid errors & omissions and ensure accuracy. Any error noted may be brought to the notice of the compiler, which shall be taken care of in the updated edition of this handbook. The sources of information/material are provided in the appendix. The information contained in this handbook is strictly for education and learning purposes and not for any commercial use. Furthermore, The University reserves the right to unilaterally and without notice make changes to this handbook at any time. Course Course Title Python Programming Course Type HSSC BSC ESC PCC OEC PEC Legends: HSSC: Humanities and Social Sciences Courses BSC: Basic Science Courses ESC: Engineering Science Courses PCC: Program Core Courses OEC: Open Elective Courses PEC: Program Elective Courses Teaching and Evaluation Scheme Evaluation Scheme Teaching Hours / Week Theory Marks Practical Marks Total Total Marks L T P ESE CA PA Total PV TW Total Credit 2 0 4 4 50 10 40 100 20 30 50 150 Legends: ESE: End Semester Exam CA: Continuous Assessment (Attendance + Activity) PA: Progressive Assessment PV: Practical Viva TW: Term Work Suggested Specification Table with Hours Distribution of Topics According to Bloom’s Unit Teaching Chapter Name Taxonomy No. Hours R U App C E An % % % % % % 1. Python Introduction 04 40 30 20 - 5 5 Control Flow and Function in 2. 04 30 30 20 - 10 10 Python 3. Data Structures in Python 08 10 30 20 20 10 10 4. Classes and Modules in Python 06 20 20 20 10 15 15 5. Python Standard Libraries 06 20 20 30 10 10 10 Legends: R: Remembering U: Understanding App: Applying C: Creating E: Evaluating An: Analyzing Detailed Syllabus Unit Learning % Topics Sub-Topics Hours No. Outcomes Weightage 1.1 What is Python To understand what is Python Python interpreter, and its extension & applications are, implementations Installation of 1.2 Python installation Python 1.3 Variables, programming Python language and its strings, formatted interpreter, IDE. 1 Introduction & 15% 4 strings & string To understand Basic Syntax methods the primitive data 1.4 Escape sequence types available in 1.5 Working with Python and how numbers to use methods 1.6 Type conversion associated with them. 1.7 Basic operators 2.1 Conditional To understand statements the syntax of conditional and 2.2 Looping looping statements statements in Python and their 2.3 Iterables use along with Control flow the syntax of user 2 and Functions 15% 4 2.4 Defining functions defined function in Python with its type. 2.5 Types of functions Different types of arguments like 2.6 Keyword keyword arguments, arguments and Default arguments default arguments. 3.1 List To understand different types of 3.2 Tuple Data Structures data structures 3 available in 30% 8 in Python 3.3 Dictionary Python and their 3.4 Set built-in methods. 4.1 Class To understand the basic concepts of 4.2 Attribute and object-oriented method programming 4.3 OOP concept language and implementations in their Classes & Python 4 Modules in implementation, 20% 6 4.4 Creating module modules, Python 4.5 Compiled Python packages, and files commands like 4.6 Packages and Pypi and Pip to subpackages import libraries. 4.7 Pypi and Pip 5.1 Working with path, To learn the use of files, and some of the directories standard libraries Python 5.2 Working with CSV available in 5 Standard Python 20% 6 5.3 Working with time, Libraries datetimes and timestamps. 5.4 Sending emails Total 28 Hours Introduction Python is a scripting language that has become the most widely used language today. Its vast range of applications includes Artificial Intelligence including Machine Learning, Natural Language Processing, Robotics, Facial Identification & many others. It can also be used for web application development. While learning this subject, students would get a solid knowledge base of Python language to write programs for Artificial Intelligence applications or web applications. Objectives ✓ Develop a Python program to display a message and demonstrate the use of operators. ✓ Perform operations on data structures in Python. ✓ Develop functions for a given problem. ✓ Design classes for a given problem. Subject’s Learning Outcomes ✓ Student should be able to install essential environment to run Python programs. ✓ Student should be able to prepare basic and advanced level programs using syntax and different data structures supported by Python. ✓ Student should be able to use some of the Python standard libraries. Evaluation Methodology Theory Marks PA: Progressive Assessment Units’ examinations will be conducted during the semester. Each unit examination is compulsory. Unit examination may be taken from objectives, short questions, long questions, etc. Unit-1 Exam: Maximum Marks 10 Unit-2 Exam: Maximum Marks 10 Unit-3 Exam: Maximum Marks 10 Unit-4 Exam: Maximum Marks 10 _________________________________________ Total Marks 40 ESE: End Semester Exam End semester examination will be conducted from all Five (5) units and it is compulsory. It may be taken in the form of objectives, short questions, long questions etc. End Semester Exam: Maximum Marks 50 CA: Continuous Assessment Continuous assessment will be evaluated from the activity assigned in the semester and the attendance of that particular subject. Activity Assessment / Attendance: Maximum Marks 10 Practical Marks PV: Practical Viva Practical viva will be conducted through group task. Thereafter viva will be conducted individually based on the given task of the concerned subject. Practical Viva: Maximum Marks 20 TW: Term Work Term work will be considered from the assignment and laboratory work done by the student during the semester of that particular subject. Term Work: Maximum Marks 30 About Bloom’s Taxonomy Bloom’s Taxonomy is a classification of the different objectives and skills that educators set for their students (learning objectives). The taxonomy was proposed in 1956 by Benjamin Bloom, an educational psychologist at the University of Chicago. The terminology has been recently updated to include the following six levels of learning. These 6 levels can be used to structure the learning objectives, lessons, and assessments of your course. 1. Remembering: Retrieving, recognizing, and recalling relevant knowledge from long‐term memory. 2. Understanding: Constructing meaning from oral, written, and graphic messages through interpreting, exemplifying, classifying, summarizing, inferring, comparing, and explaining. 3. Applying: Carrying out or using a procedure for executing, or implementing. 4. Analyzing: Breaking material into constituent parts, determining how the parts relate to one another and to an overall structure or purpose through differentiating, organizing, and attributing. 5. Evaluating: Making judgments based on criteria and standards through checking and critiquing. 6. Creating: Putting elements together to form a coherent or functional whole; reorganizing elements into a new pattern or structure through generating, planning, or producing. Contents Unit Page Unit Name Hours No. No. 1. Python Introduction 1 4 What is Python? 1 What is Python used for? 1 Why Python is so popular? 2 Python interpreter, extension & implementations 2 Python Installation 3 Python Program Execution 3 Values and Types 6 Variables 6 String 9 Escape Characters 14 Operators 17 Practical List 23 Short Questions 23 Long Questions 23 Essential Assignments 24 Desirable Assignments 24 Activities 24 Learning Outcomes 24 2. Control Flow & Function in Python 25 4 Conditional Execution 25 Looping Statements 28 Iterables 32 Functions 33 Types of Arguments 34 Pass by Reference 36 Practical List 37 Short Questions 37 Long Questions 37 Essential Assignments 38 Desirable Assignments 38 Activities 38 Learning Outcomes 38 3. Data Structures in Python 39 8 List 39 Tuples 44 Dictionary 48 Set 52 Practical List 57 Short Questions 57 Long Questions 57 Essential Assignments 58 Desirable Assignments 58 Activities 58 Learning Outcomes 58 4. Classes & Modules in Python 59 6 Python Classes/Objects 59 Modules 67 Packages 68 pip and pypi 70 Practical List 71 Short Questions 72 Long Questions 72 Essential Assignments 72 Desirable Assignments 72 Activities 72 Learning Outcomes 72 5. Python Standard Libraries 73 6 Working with paths, directories and files 73 Working with CSV 76 Working with time, datetime and timestamps 77 Sending emails 78 Practical List 80 Short Questions 80 Long Questions 80 Essential Assignments 80 Desirable Assignments 81 Activities 81 Learning Outcomes 81 Appendix Total Hours: 28 Python Introduction Unit-1 Python Introduction What is Python? Python, one of the most popular programming languages in the world, has created everything from Netflix’s recommendation algorithm to the software that controls self-driving cars. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It’s a general purpose language, meaning it can be used to create a variety of different programs and isn’t specialized for any specific problems. This versatility, along with its beginner- friendliness, has made it one of the most-used programming languages today. What is Python used for? Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Here’s a closer look at some of the common ways Python is used. Data analysis and machine learning Python has become a staple in data science, allowing data analysts and other professionals to use the language to conduct complex statistical calculations, create data visualizations, build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks. Python can build a wide range of different data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras. Web development Python is often used to develop the back end of a website or application—the parts that a user doesn’t see. Python’s role in web development can include sending data to and from servers, processing data and communicating with databases, URL routing, and ensuring security. Python offers several frameworks for web development. Commonly used ones include Django and Flask. Automation or scripting If you find yourself performing a task over and over again, you could work more efficiently by automating it with Python. Writing code used to build these automated processes is called scripting. In the coding world, automation can be used to check for errors across multiple files, convert files, execute simple math, and remove duplicates in data. Software testing and prototyping In software development, Python can aid in tasks like build control, bug tracking, and testing. With Python, software developers can automate testing for new products or features. Some Python tools used for software testing include Green and Requestium. LJ Polytechnic Page 1 of 81 Python Programming Everyday tasks Python isn't only for programmers and data scientists. Learning Python can open new possibilities for those in less data-heavy professions, like journalists, small business owners, or social media marketers. Python can also enable non-programmer to simplify certain tasks in their lives. Here are just a few of the tasks you could automate with Python: Keep track of stock market or crypto prices Send yourself a text reminder to carry an umbrella anytime it’s raining Update your grocery shopping list Renaming large batches of files Converting text files to spreadsheets Randomly assign chores to family members Fill out online forms automatically Why is Python so popular? Python is popular for a number of reasons. Here’s a deeper look at what makes it so versatile and easy to use for coders. It has a simple syntax that mimics natural language, so it’s easier to read and understand. This makes it quicker to build projects, and faster to improve on them. It’s versatile. Python can be used for many different tasks, from web development to machine learning. It’s beginner friendly, making it popular for entry-level coders. It’s open source, which means it’s free to use and distribute, even for commercial purposes. Python’s archive of modules and libraries—bundles of code that third-party users have created to expand Python’s capabilities—is vast and growing. Python has a large and active community that contributes to Python’s pool of modules and libraries, and acts as a helpful resource for other programmers. The vast support community means that if coders run into a stumbling block, finding a solution is relatively easy; somebody is bound to have run into the same problem before. Python interpreter, extension & implementations Typically, every novice learns to write a Python script on the command line first, then moves to execute the script from the command line wherein the script is usually written in a text editor and is run from the command line. Computers cannot understand code in the way humans write it and hence, you need an interpreter between the computer and the human written code. The job of the interpreter is to convert the code into a format that computers can then understand and process. The interpreter processes the code in the following ways: Processes the Python script in a sequence. Compiles the code into a byte code format which is a lower-level language understood by the computers. LJ Polytechnic Page 2 of 81 Python Introduction Unit-1 The Python Virtual Machine (PVM) iterates over the instructions of low-level byte code to run them one by one. The Python script is saved with a.py extension which informs the computer that it is a Python program script. Python Installation Unlike Windows, the Unix based operating systems such as Linux and Mac come with pre- installed Python. Also, the way Python scripts are run in Windows and Unix operating systems differ. Installing Python on Windows takes a series of few easy steps. Step 1 − Select Version of Python to Install Python has various versions available with differences between the syntax and working of different versions of the language. We need to choose the version which we want to use or need. Step 2 − Download Python Executable Installer On the web browser, in the official site of python www.python.org , move to the Download for Windows section. All the available versions of Python will be listed. Select the version required by you and click on Download. Step 3 − Run Executable Installer Run the installer. The installation process will take few minutes to complete. Step 4 − Verify Python is installed on Windows To ensure if Python is successfully installed on your system. Follow the given steps − Open the command prompt. Type ‘python’ and press enter. The version of the python which you have installed will be displayed if the python is successfully installed on your windows. Step 5 − Verify Pip was installed Pip is a powerful package management system for Python software packages. Thus, make sure that you have it installed. To verify if pip was installed, follow the given steps − Open the command prompt. Enter pip –V to check if pip was installed. The following output appears if pip is installed successfully. Note: For all users, especially Windows OS users, it is highly recommended that you install Anaconda, which can be downloaded from https://www.anaconda.com/ Python Program Execution Here are the ways with which we can run a Python script. LJ Polytechnic Page 3 of 81 Python Programming Interactive Mode In Interactive Mode, you can run your script line by line in a sequence. To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter. Run the following line one by one in the interactive mode: a=1 b=3 if a > b: print("a is Greater") else: print("b is Greater") LJ Polytechnic Page 4 of 81 Python Introduction Unit-1 On a Mac system, it is very straight-forward. All you need to do is open Launchpad and search for Terminal, and in the terminal, type Python and boom, it will give you an output with the Python version. Like the Mac system, accessing terminal on a Linux system is also very easy. Right click on the desktop and click Terminal and in terminal type Python and that's all! Command Line Create a file having extension.py Write Python script in created file To run a Python script store in a ‘.py’ file in command line, write ‘python’ keyword before the file name in the command prompt. python hello.py Note: You can write your own file name in place of ‘hello.py’. # File Name:- hello.py # File Path:- C:\Users\Anonymous\Desktop\GfG\hello.py print("Hello World!") LJ Polytechnic Page 5 of 81 Python Programming Values and types A value is one of the basic things a program works with, like a letter or a number. A value may be characters i.e. ‘Hello, World!’ or a number like 1, 2.2 etc. To print the value print() function is used. >>> print('Hello, World!') Hello, World! >>> print(1) 1 >>> print(2.2) 2.2 >>> print('Abc@123') Abc@123 type() is a function which returns class type of the argument (object) passed as parameter. This function is mostly used for debugging purposes. >>> type('Hello, World!') >>> type(1) >>> type(2.2) >>> print(''Abc@123'') Variable One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. An assignment statement creates new variables and gives them values: >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.14 This example makes three assignments. The first assigns a string to a new variable named message; the second assigns the integer 17 to n; the third assigns the float 3.14 to pi. To display the value of a variable, you can use a print statement: >>> print(n) 17 >>> print(pi) 3.14 The type of a variable is the type of the value it refers to. LJ Polytechnic Page 6 of 81 Python Introduction Unit-1 >>> type(message) >>> type(n) >>> type(pi) Rules for creating variables in Python: 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 (name, Name and NAME are three different variables). The reserved words (keywords) cannot be used naming the variable. >>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax 76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what’s wrong with class? It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python reserves 35 keywords: and del from None True continue lambda as elif global nonlocal try def is assert else if not while finally return break except in or with for async class False import pass yield raise await A Re-declare the Variable: We can re-declare the python variable once we have declared the variable already. Assigning a single value to multiple variables: Python allows assigning a single value to several variables simultaneously with “=” operators. LJ Polytechnic Page 7 of 81 Python Programming >>> a = b = c = 100 >>> print(a) 100 >>> print(b) 100 >>> print(c) 100 Assigning different values to multiple variables: Python allows adding different values in a single line with “,”operators. >>> a, b, c = 1, 2.2, 'ABC' >>> print(a) 1 >>> print(b) 2.2 >>> print(c) ABC Can we use the same name for different types? If we use the same name, the variable starts referring to a new value and type. >>> a = 100 >>> a = 'ABC' >>> print(a) ABC How does + operator work with variables? >>> a = 10 >>> b = 20 >>> print(a+b) 30 >>> a = 'LJ' >>> b = 'KU' >>> print(a+b) LJKU Can we use + for different types also? No using for different types would produce error. >>> a = 10 >>> b = 'KU' >>> print(a+b) TypeError: unsupported operand type(s) for +: 'int' and 'str' LJ Polytechnic Page 8 of 81 Python Introduction Unit-1 String: In Python, Strings 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. >>> s = 'P' >>> print(s) P >>> type(s) >>> language = 'Python' >>> print(language) Python >>> type(language) Square brackets can be used to access elements of the string. >>> language = 'Python' >>> letter = language The second statement extracts the character at index position 1 from the language variable and assigns it to the letter variable The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). But you might not get what you expect: >>> print(letter) y For most people, the first letter of “Python” is “P”, not “y”. But in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero. >>> letter = language >>> print(letter) P So “P” is the 0th letter (“zero-th”) of “Python”, “y” is the 1th letter (“one-th”), and “t” is the 2th (“two-th”) letter. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get: >>> letter = language [1.5] TypeError: string indices must be integers P y t h o n [-6] [-5] [-4] [-3] [-2] [-1] LJ Polytechnic Page 9 of 81 Python Programming Length of a string: To find the length if the string len() function is used. len() is a built-in function that returns the number of characters in a string: >>> language = 'Python' >>> len(language) 6 To get the last letter of a string, you might be tempted to try something like this: >>> length = len(language) >>> last = language[length] IndexError: string index out of range The reason for the IndexError is that there is no letter in “Python” with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length: >>> last = language[length-1] >>> print(last) n Alternatively, you can use negative indices, which count backward from the end of the string. The expression language[-1] yields the last letter ‘n’, language [-2] yields the second to last letter ‘o’, and so on. String slices: A segment of a string is called a slice. Selecting a slice is similar to selecting a character: >>> s = 'Monty Python' >>> print(s[0:5]) Monty >>> print(s[6:12]) Python The operator returns the part of the string from the “n-th” character to the “m-th” character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string: >>> s = 'Monty Python' >>> print(s[0:5]) Monty >>> print(s[6:12]) Python If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: LJ Polytechnic Page 10 of 81 Python Introduction Unit-1 >>> language = 'Python' >>> language[3:3] '' An empty string contains no characters and has length 0, but other than that, it is the same as any other string. We can specify start, stop and step(optional) within the square brackets as: string[start:stop:step] start: It is the index from where the slice starts. The default value is 0. stop: It is the index at which the slice stops. The character at this index is not included in the slice. The default value is the length of the string. step: It specifies the number of jumps to take while going from start to stop. It takes the default value of 1. >>> language = 'Python' >>> language[::2] 'Pto' In python, the string data types are immutable. Which means a string value cannot be updated. >>> greeting = 'Hello, world!' >>> greeting = 'J' TypeError: 'str' object does not support item assignment The best you can do is create a new string that is a variation on the original: >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print(new_greeting) Jello, world! This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string. String methods Everything in Python is an object. A string is an object too. Python provides us with various methods to call on the string object. Note: Note that none of these methods alters the actual string. They instead return a copy of the string. This copy is the manipulated version of the string. capitalize([]) This method is used to capitalizes a string. >>> s = 'heLlo pYthOn' >>> s2 = s.capitalize() >>> print(s2) Hello python LJ Polytechnic Page 11 of 81 Python Programming lower([]) This method converts all alphabetic characters to lowercase. >>> s = 'heLlo pYthOn' >>> s2 = s.lower() >>> print(s2) hello python upper([]) This method converts all alphabetic characters to uppercase. >>> s = 'heLlo pYthOn' >>> s2 = s.upper() >>> print(s2) HELLO PYTHON title() This method converts the first letter of each word to uppercase and remaining letters to lowercase >>> s = 'heLlo pYthOn' >>> s2 = s.title() >>> print(s2) Hello Python title([]) This method converts the first letter of each word to uppercase and remaining letters to lowercase >>> s = 'heLlo pYthOn' >>> s2 = s.title() >>> print(s2) Hello Python swapcase([]) This method swaps case of all alphabetic characters. >>> s = 'HeLlo PyThOn' >>> s2 = s.swapcase () >>> print(s2) hElLO pYtHoN count([, [, ]]) This method returns the number of time occurs in string. LJ Polytechnic Page 12 of 81 Python Introduction Unit-1 >>> s = 'Python Programming' >>> s.count('P') 2 >>> s.count('mm') 1 >>> print('P',3,10) 1 find([, [, ]]) This method returns the index of the first occurrence of in s. Returns -1 if the substring is not present in the string. >>> s = 'Python Programming' >>> s.find('Pro') 7 >>> s.find('on',3,10) 4 lstrip([]) This method removes leading characters from a string. Removes leading whitespaces if you don’t provide a argument. >>> s = ' Python ' >>> s.lstrip() 'Python ' rstrip([]) This method removes trailing characters from a string. Removes trailing whitespaces if you don’t provide a argument. >>> s = ' Python ' >>> s.rstrip() ' Python' strip([]) This method removes leading and trailing characters from a string. Removes leading and trailing whitespaces if you don’t provide a argument >>> s = ' Python ' >>> s.strip() 'Python' LJ Polytechnic Page 13 of 81 Python Programming join() This method joins elements of an iterable into a single string. Here, s is the separator string. >>> s = ' '.join('We','are','coders') >>> print(s1) 'We are coders' s = '_'.join('We','are','coders') >>> print(s1) 'We_are_coders' split(sep=None,maxsplit=-1) This method splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it splits based on whitespaces. >>> s = 'Python Programming' >>> s.split() ['Python', 'Programming'] >>> s = 'Python Programming' >>> s.split('o') ['Pyth', 'n Pr', 'gramming'] Strings can be concatenated (glued together) with the + operator, and repeated with *: >>> 3 * 'un' 'ununun' >>> 'Py' 'thon' 'Python' >>> 'Py'+'thon' 'Python' Escape Characters 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. You will get an error if you use double quotes inside a string that is surrounded by double quotes: >>> s = ''we are the so-called ''Vikings'' from the north'' SyntaxError: invalid syntax To fix this problem, use the escape character \" >>> s = ''we are the so-called \''Vikings\'' from the north'' ' we are the so-called ''Vikings'' from the north' LJ Polytechnic Page 14 of 81 Python Introduction Unit-1 List of escape sequences available in Python 3: Code Result Code Result \' Single Quote \t Tab \\ Backslash \b Backspace \n New Line \f Form Feed \r Carriage Return \ooo Octal value \xhh Hex value A Numbers There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them: >>> x = 1 #int >>> y = 2.8 #float >>> z = 1j >>>print(type(x)) >>>print(type(y)) >>>print(type(z)) Int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. >>> x = 1 >>> y = 35656222554887711 >>> z = -3255522 >>> print(type(x)) >>> print(type(y)) >>> print(type(z)) LJ Polytechnic Page 15 of 81 Python Programming Float Float, or "floating point number" is a number, positive or negative, containing one or more decimals. >>> x = 1.10 >>> y = 1.0 >>> z = -35.59 >>> print(type(x)) >>> print(type(y)) >>> print(type(z)) Float can also be scientific numbers with an "e" to indicate the power of 10. >>> x = 35e3 >>> y = 12E4 >>> z = -87.7e100 >>> print(type(x)) >>> print(type(y)) >>> print(type(z)) Complex Complex numbers are written with a "j" as the imaginary part: >>> x = 3+5j >>> y = 5j >>> z = -5j >>> print(type(x)) >>> print(type(y)) >>> print(type(z)) Type Conversion You can convert from one type to another with the int(), float(), and complex() methods: LJ Polytechnic Page 16 of 81 Python Introduction Unit-1 >>> x = 1 # int >>> y = 2.8 # float >>> z = 1j # complex #convert from int to float: >>> a = float(x) #convert from float to int: >>> b = int(y) #convert from int to complex: >>> c = complex(x) >>> print(a) 1.0 >>> print(type(a)) >>> print(b) 2 >>> print(type(b)) >>> print(c) (1+0j) Operators Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. Arithmetic Operators Arithmetic operators are used to performing mathematical operations like addition, subtraction, multiplication, and division. Operator Description Syntax + Addition: adds two operands x+y - Subtraction: subtracts two operands x-y * Multiplication: multiplies two operands x*y / Division (float): divides the first operand by the x/y second LJ Polytechnic Page 17 of 81 Python Programming // Division (floor): divides the first operand by the x // y second % Modulus: returns the remainder when the first x%y operand is divided by the second ** Power: Returns first raised to power second x ** y Comparison Operators Comparison of Relational operators compares the values. It either returns True or False according to the condition. Operator Description Syntax > Greater than: True if the left operand is greater than x>y the right < Less than: True if the left operand is less than the x= Greater than or equal to True if the left operand is x >= y greater than or equal to the right > # Examples of Relational Operators >>> a, b = 13, 33 >>> # a > b is False >>> print(a > b) False >>> # a < b is True >>> print(a < b) True >>> # a == b is False >>> print(a == b) False >>> # a != b is True >>> print(a != b) True LJ Polytechnic Page 18 of 81 Python Introduction Unit-1 Logical Operators Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements. Operator Description Syntax and Logical AND: True if both the operands are true x and y or Logical OR: True if either of the operands is true x or y not Logical NOT: True if the operand is false not x Bitwise Operators Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers. Operator Description Syntax & Bitwise AND x&y | Bitwise OR x|y ~ Bitwise NOT ~x ^ Bitwise XOR x^y >> Bitwise right shift x>> > # Examples of Bitwise operators >>> a = 10 >>> b = 4 >>> # Print bitwise AND operation >>> print(a & b) 0 >>> # Print bitwise OR operation >>> print(a | b) 14 >>> # Print bitwise NOT operation >>> print(~a) -11 LJ Polytechnic Page 19 of 81 Python Programming >>> # print bitwise XOR operation >>> print(a ^ b) 14 >>> # print bitwise right shift operation >>> print(a >> 2) 2 >>> # print bitwise left shift operation >>> print(a >= Performs Bitwise right shift on operands and a >>= b assign value to left operand a = a >> b > b = 20 >>> c = a >>> print(a is not b) True >>> print(a is c) True Membership Operators in and not in are the membership operators; used to test whether a value or variable is in a sequence. Operator Description in True if value is found in the sequence in not True if value is not found in the sequence LJ Polytechnic Page 21 of 81 Python Programming #membership_ex.py x = 24 y = 20 list = [10, 20, 30, 40, 50] if (x not in list): print("x is NOT present in given list") else: print("x is present in given list") if (y in list): print("y is present in given list") else: print("y is NOT present in given list") Precedence and Associativity of Operators Operator precedence and associativity determine the priorities of the operator. Operator Precedence This is used in an expression with more than one operator with different precedence to determine which operation to perform first. >>> # Precedence of '+' & '*' >>> expr = 10 + 20 * 30 >>> print(expr) 610 >>> # Precedence of 'or' & 'and' >>> name = "Alex" >>> age = 0 >>> if name == "Alex" or name == "John" and age >= 2:... print("Hello! Welcome.")... else:... print("Good Bye!!") Hello! Welcome. Operator Associativity If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left. LJ Polytechnic Page 22 of 81 Python Introduction Unit-1 Practical List 1. Install and configure Python IDE. 2. Write a Python program to display a message on the screen. 3. Write simple Python program using operators: A) arithmetic operators B) logical operators 4. Write a Python program to demonstrate different string methods. 5. Write a Python program to demonstrate formatted strings. 6. Write a Python program to demonstrate type conversion. Short Questions Sr. Questions Bloom’s No. Taxonomy 1. Define Python. Remember 2. What is Python interpreter? Understand 3. What is the difference between intermediate mode and script Understand mode? 4. What is meant by value in Python? Understand 5. List the standard data types in Python. Remember 6. What is meant by Python numbers? Understand 7. What is String? How do u create a string in Python? Apply 8. What is a variable? Understand 9. What are keywords? Understand 10. Which operators are supported by Python? Remember 11. What is an Arithmetic operator? Understand 12. What is the use of comparison operator? Understand 13. What are assignment statements? Remember Long Questions Sr. Questions Bloom’s No. Taxonomy 1. Illustrate interpreter and interactive mode in Python with Understand example. 2. Give the features of Python. Remember 3. Explain the data types in Python. Understand 4. Explain briefly constant, variables, expression, keywords and Remember, statements available in Python. Understand 5. What are the rules for naming a variable? Remember 6. What are the rules for writing an identifier? Remember 7. Explain about string slicing with examples. Understand 8. Write short notes on types of operators in Python with Remember, appropriate example. Understand 9. What are the two operators that are used in string functions? Remember LJ Polytechnic Page 23 of 81 Python Programming 10. What is the use of str.upper() and str.lower() functions in Understand string? 11. Explain string comparison with an example. Understand 12. How to split strings and what function is used to perform that Understand operation? 13. What are logical operators and Bitwise operators? Understand 14. Mention the features of identity operators? Remember 15. Give the characteristics of membership operator? Remember 16. How to perform a user input in Python? Explain with example. Apply Essential Assignments 1. Write a Python script to define variables of different data types, initialize them and display their values. 2. Write a Python script to demonstrate use of different operators. Desirable Assignments 1. Write a Python script to demonstrate strings and methods associated with them. 2. Write a Python script to demonstrate formatted strings. Activities 1. Install Python into your system and run a “Hello World” Program. Learning Outcomes ❖ To know what Python is and why it is used. ❖ To learn the installation of Python and environment required to run a Python script. ❖ To learn basic syntax of Python and prepare simple programs. LJ Polytechnic Page 24 of 81 Control flow & Function in Python Unit-2 Control flow & Function in Python Conditional execution In order to write useful programs, we almost always need the ability to check conditions and change the behaviour of the program accordingly. Conditional statements give us this ability. if statement if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statement is executed otherwise not. if (condition) : # Statements to execute if # condition is true Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also. As we know, python uses indentation to identify a block. So the block under an if statement will be identified as shown in the below example: if (condition) : statement1 statement2 # Here if the condition is true, if block # will consider only statement1 to be inside # its block. There is no limit on the number of statements that can appear in the body, but there must be at least one. Occasionally, it is useful to have a body with no statements (usually as a place holder for code you haven’t written yet). In that case, you can use the pass statement, which does nothing. if (condition) : pass # Python program to illustrate If statement i = 10 if (i > 15): print("10 is less than 15") print("I am not in if") LJ Polytechnic Page 25 of 81 Python Programming I am not in if As the condition present in the if statement is false. So, the block below the if statement is not executed. if-else The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false. if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false # Python program to illustrate If else statement i = 20 if (i < 15): print("I is smaller than 15") print("I'm in if Block") else: print("I is greater than 15") print("I'm in else Block") print("I'm not in if and not in else Block") I is greater than 15 I'm in else Block I'm not in if and not in else Block The block of code following the else statement is executed as the condition present in the if statement is false after calling the statement which is not in block(without spaces). Nested-if A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement. if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here LJ Polytechnic Page 26 of 81 Control flow & Function in Python Unit-2 # Python program to illustrate nested If statement i = 10 if (i == 10): # First if statement if (i < 15): print("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i < 12): print("i is smaller than 12 too") else: print("i is greater than 15") i is smaller than 15 i is smaller than 12 too If-elif-else ladder The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if (condition): statement elif (condition): statement.. else: statement # Python program to illustrate if-elif-else ladder i = 15 if (i == 10): print("i is 10") elif (i == 15): print("i is 15") else: print("i is not present") LJ Polytechnic Page 27 of 81 Python Programming i is 15 Looping statements In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. while loop In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. while (expression) : statement(s) All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. # Python program to illustrate while loop count = 0 while count < 3 : count = count + 1 print("Hello World") Hello World Hello World Hello World As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. # Python program to illustrate combining else with while count = 0 while (count < 1) : count = count + 1 print("Hello World") else: print("In Else Block") Hello World In Else Block LJ Polytechnic Page 28 of 81 Control flow & Function in Python Unit-2 for loop For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i>> list("I am a cow") ['I', ' ', 'a', 'm', ' ', 'a', ' ', 'c', 'o', 'w'] >>> sum([1, 2, 3]) 6 >>> sorted("gheliabciou") ['a', 'b', 'c', 'e', 'g', 'h', 'i', 'i', 'l', 'o', 'u'] >>> any((0, None, [], 0)) False >>> all([1, (0, 1), True, "hi"]) True >>> max((5, 8, 9, 0)) 9 >>> min("hello") 'e' Functions Python Functions is a block of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again. Functions can be either built-in or user-defined. It helps the program to be concise, non- repetitive, and organized. def function_name(parameters): statement(s) return expression Creating a function We can create a Python function using the def keyword. # A simple Python function def fun(): print("Python Programming") LJ Polytechnic Page 33 of 81 Python Programming Calling a function After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function. # A simple Python function def fun(): print("Python Programming") # Driver code to call a function fun() Python Programming Types of Arguments Python supports various types of arguments that can be passed at the time of the function call. Let’s discuss each type in detail. Default arguments A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument. The following example illustrates Default arguments. # Python program to demonstrate default arguments def myFun(x, y=50): print("x: ", x) print("y: ", y) # Driver code (We call myFun() with only argument) myFun(10) x: 10 y: 50 Keyword arguments The idea is to allow the caller to specify the argument name with values so that caller does not need to remember the order of parameters. # Python program to demonstrate Keyword Arguments def student(firstArg, lastArg): print(firstArg, lastArg) # Keyword arguments student(firstArg ='Python', lastArg ='Practice') student(lastArg ='Practice', firstArg ='Python') LJ Polytechnic Page 34 of 81 Control flow & Function in Python Unit-2 Python Practice Python Practice Variable-length arguments In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args(Non-Keyword Arguments) # Python program to illustrate *args for variable number of arguments def myFun(*argv): for arg in argv: print(arg) myFun('Hello', 'Welcome', 'to', 'Python Programming') Hello Welcome to Python Programming As in the above example we are not sure about the number of arguments that can be passed to a function. Python has *args which allow us to pass the variable number of non-keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments. The arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the parameter excluding asterisk *. **kwargs(Keyword Arguments) # Python program to illustrate *kwargs for variable number of keyword arguments def myFun(**kwargs): for key, value in kwargs.items(): print("%s == %s" % (key, value)) # Driver code myFun(first='Programming', mid='in', last='Python') first == Programming mid == in last == Python Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function. LJ Polytechnic Page 35 of 81 Python Programming In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **. *args and **kwargs are special keyword which allows function to take variable length argument. *args passes variable number of non-keyword arguments list and on which operation of the list can be performed. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed. *args and **kwargs make the function flexible. The return statement The function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller. return [expression_list] The return statement can consist of a variable, an expression, or a constant which is returned to the end of the function execution. If none of the above is present with the return statement a None object is returned. # This function returns the square value of the entered number def square_value(num): return num**2 print(square_value(2)) print(square_value(-4)) 4 16 Pass by Reference In Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. # Here x is a new reference to same list lst def myFun(x): x = 20 # Driver Code (Note that lst is modified after function call.) lst = [10, 11, 12, 13, 14, 15] myFun(lst) print(lst) [20, 11, 12, 13, 14, 15] When we pass a reference and change the received reference to something else, the connection between the passed and received parameter is broken. For example, consider the below program. LJ Polytechnic Page 36 of 81 Control flow & Function in Python Unit-2 def myFun(x): # After below line link of x with previous object gets broken. # A new object is assigned to x. x = [20, 30, 40] # Driver Code (Note that lst is not modified after function call. lst = [10, 11, 12, 13, 14, 15] myFun(lst) print(lst) [10, 11, 12, 13, 14, 15] Practical List 1. Write a Python program to identify a digit as even or odd. 2. Write a Python program to calculate the sum of all numbers till 100 which are divisible by 3 and 5. 3. Write a Python program to print the sum of all digits of a given number using function. 4. Write a Python program to demonstrate the use of keyword argument. Short Questions Sr. Questions Bloom’s No. Taxonomy 1. What is Boolean value? Understand 2. What do Iterables mean in Python? Understand 3. What is meant by conditional If? Understand 4. What is the difference between break and continue statement? Understand Long Questions Sr. Questions Bloom’s Taxonomy No. 1. What is chained conditional statement? Understand 2. Write the syntax and usage of for loop. Remember,Understand 3. Write the syntax and usage of while loop. Remember,Understand 4. Explain Python break statement? Understand 5. Explain Python continue statement? Understand 6. Explain Python pass statement? Understand 7. What is a function? Mention the type of function and use. Remember 8. Mention the types of arguments in Python. Understand 9. Explain call by value and call by reference. Understand LJ Polytechnic Page 37 of 81 Python Programming Essential Assignments 1. Decide if given year is leap year or not. 2. Print First 10 natural numbers using while loop. 3. Calculate sum of first 20 odd digits. 4. Find the area of rectangle using user-defined function. Desirable Assignments 1. Print First 100 digits divisible by 3 and 5. 2. Find a factorial of a given number using user-defined function. Activities 1. Convert Celsius to Fahrenheit. 2. Reverse a given integer number. 3. Calculate the sum of digits of a number. 4. Take a number as input from user and print it in words. Learning Outcomes ❖ To learn the conditional statements available in Python. ❖ To learn the looping statements in Python. ❖ To learn the syntax of user-defined function in Python and how to use it. LJ Polytechnic Page 38 of 81 Data Structures in Python Unit-3 Data Structures in Python Python has four basic inbuilt data structures namely Lists, Tuple, Dictionary and Set. List Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items. There are several ways to create a new list; the simplest is to enclose the elements in square brackets (“[” and “]”) # Creating a List List = [] print("Blank List: ", List) Blank List: [] # Creating a List of numbers List = [10, 20, 30] print("List of numbers: ") print(List) List of numbers: [10, 20, 30] # Creating a List of strings and accessing using index List = ["Programming", "in", "Python"] print("List Items: ") print(List) print(List) List Items: Programming Python # Creating a Multi-Dimensional List (By Nesting a list inside a List) List = [['Programming', 'in'] , ['Python']] print("Multi-Dimensional List: ") print(List) LJ Polytechnic Page 39 of 81 Python Programming Multi-Dimensional List: [['Programming', 'in'], ['Python']] A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation. # Creating a List with the use of Numbers (Having duplicate values) List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print("List with the use of Numbers: ") print(List) List with the use of Numbers: [1, 2, 4, 4, 3, 3, 3, 6, 5] # Creating a List with mixed type of values (Having numbers and strings) List = [1, 2, 'Programming', 4, 'in', 6, 'Python'] print("List with the use of Mixed Values: ") print(List) List with the use of Mixed Values: [1, 2, 'Programming', 4, 'in', 6, 'Python'] Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. # Updating a List elements (List are mutable) Numbers = [17, 123] print("Before: ", Numbers) Numbers = 5 print("After: ", Numbers) Before: [17, 123] After: [17, 5] Using len() function we can find the length (no. of elements in list) of list. # Creating a List of numbers and finding the length List = [10, 20, 14] print(len(List)) 3 LJ Polytechnic Page 40 of 81 Data Structures in Python Unit-3 List operation # The + operator concatenates lists a = [1, 2, 3] b = [4, 5, 6] c=a+b print(c) [1, 2, 3, 4, 5, 6] # The * operator repeats a list a given number of times a = a=a*3 print(a) [1, 1, 1] List slices # The slice operator List = ['a', 'b', 'c', 'd', 'e', 'f'] print(List[1:3]) print(List[:4]) print(List[3:]) ['b', 'c'] ['a', 'b', 'c', 'd'] ['d', 'e', 'f'] If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list. List = ['a', 'b', 'c', 'd', 'e', 'f'] print(List[:]) ['a', 'b', 'c', 'd', 'e', 'f'] A slice operator on the left side of an assignment can update multiple elements. List = ['a', 'b', 'c', 'd', 'e', 'f'] List[1:3] = ['x', 'y'] print(List) ['a', 'x', 'y', 'd', 'e', 'f'] LJ Polytechnic Page 41 of 81 Python Programming List methods Python has a set of built-in methods that you can use on lists. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list # append() fruits = ['apple', 'banana', 'cherry'] fruits.append("orange") fruits ['apple', 'banana', 'cherry', 'orange'] # clear() fruits = ['apple', 'banana', 'cherry', 'orange'] fruits.clear() fruits [] # copy() fruits = ['apple', 'banana', 'cherry', 'orange'] x = fruits.copy() x ['apple', 'banana', 'cherry', 'orange'] LJ Polytechnic Page 42 of 81 Data Structures in Python Unit-3 # count() fruits = ['apple', 'banana', 'cherry'] x = fruits.count("cherry") x 1 #extend() fruits = ['apple', 'banana', 'cherry']; cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) fruits ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo'] #index() fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry") x 2 #insert() fruits = ['apple', 'banana', 'cherry'] fruits.insert(1, "orange") fruits ['apple', 'orange', 'banana', 'cherry'] #pop() fruits = ['apple', 'banana', 'cherry'] fruits.pop(1) fruits ['apple', 'cherry'] #remove() fruits = ['apple', 'banana', 'cherry'] fruits.remove("banana") fruits ['apple', 'cherry'] LJ Polytechnic Page 43 of 81 Python Programming #reverse() fruits = ['apple', 'banana', 'cherry'] fruits.reverse() fruits ['apple', 'cherry'] #sort() cars = ['Ford', 'BMW', 'Volvo'] cars.sort() cars ['BMW', 'Ford', 'Volvo'] Tuples A tuple is a sequence of immutable (A tuple is a collection which is ordered and unchangeable) Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example # creating a tuple tup1 = ('ABC', 'pqr', 1000, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; print(tup1) print(tup2) print(tup3) ('ABC', 'pqr', 1000, 2000) (1, 2, 3, 4, 5) ('a', 'b', 'c', 'd') The empty tuple is written as two parentheses containing nothing tup1 = (); To write a tuple containing a single value you have to include a comma, even though there is only one value tup1 = (50,); Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on. LJ Polytechnic Page 44 of 81 Data Structures in Python Unit-3 Accessing Values in Tuples To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example # accessing a tuple tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print("tup1: ", tup1) print("tup2[1:5]: ", tup2[1:5]) tup1: physics tup2[1:5]: (2, 3, 4, 5) Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates # updating a tuple tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); # following action is not valid for tuples # tup1 = 100; # so let's create a new tuple as follows tup3 = tup1 + tup2; print(tup3) (12, 34.56, 'abc', 'xyz') Delete Tuple Elements Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement. For example # deleting a tuple tup = ('ABC', 'pqr', 1997, 2000); print(tup) del tup; print("After deleting tup : ") print(tup) This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more LJ Polytechnic Page 45 of 81 Python Programming ('ABC', 'pqr', 1997, 2000) After deleting tup : --------------------------------------------------------------------- NameError Traceback (most recent call last) in 3 del tup; 4 print("After deleting tup : ") ----> 5 print(tup) NameError: name 'tup' is not defined Tuple Operations Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string Python Expression Results Description len((1, 2, 3)) 3 Length (1, 2, 3)+(4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!',)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1,2,3) True Membership for x in (1, 2, 3): print(x) 123 Iteration Indexing, Slicing, Matrices Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input L = ('spam', 'Spam', 'SPAM!') Python Expression Results Description L 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections Tuple methods Method Description cmp(tuple1, tuple2) Compares elements of both tuples len(tuple) Gives the total length of the tuple max(tuple) Returns item from the tuple with max value LJ Polytechnic Page 46 of 81 Data Structures in Python Unit-3 min(tuple) Returns item from the tuple with min value tuple(seq) Converts a list into tuple Python includes the following tuple functions # cmp() a = (1, 2, 1) b = (1, 2, 2) print(cmp(a, b)) -1 Here the third element in the first tuple is lower than the third element in the second tuple. Hence returned -1. # cmp() c = ('a', 'b', 'e') d = ('a', 'b', 'd') print(cmp(c, d)) -1 Here the third element of the first tuple is greater than the third element of the second tuple. Hence returned 1. # len() tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc') print("First tuple length : ", len(tuple1)) print("Second tuple length : ", len(tuple2)) First tuple length : 3 Second tuple length : 2 # max() tuple1, tuple2 = ('123', 'xyz', 'zara', 'abc'), (456, 700, 200) print("Max value element : ", max(tuple1)) print("Max value element : ", max(tuple2)) Max value element : zara Max value element : 700 LJ Polytechnic Page 47 of 81 Python Programming # tuple() aList = [123, 'xyz', 'zara', 'abc'] aTuple = tuple(aList) print("Tuple elements : ", aTuple) Tuple elements : (123, 'xyz', 'zara', 'abc') Dictionary A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} You can create dictionary in the following way as well: dict1 = { 'abc': 456 }; dict2 = { 'abc': 123, 98.6: 37 }; Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as string s, numbers, or tuples. Accessing Values in Dictionary To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example # accessing a dictionary dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print("dict1['Name']: ", dict1['Name']); print("dict1['Age']: ", dict1['Age']); print("dict1['Class']: ", dict1['Class']); dict1['Name']: Zara dict1['Age']: 7 dict1['Class']: First If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows LJ Polytechnic Page 48 of 81 Data Structures in Python Unit-3 dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print("dict1['Alice']: ", dict1['Alice']) KeyError Traceback (most recent call last) in 1 dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; ----> 2 print("dict1['Alice']: ", dict1['Alice']) KeyError: 'Alice' Updating Dictionary You can update a dictionary by adding a new entry or item (i.e., a key-value pair), modifying an existing entry, or deleting an existing entry as shown below in the simple example # updating dictionary dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict1['Age'] = 8; # update existing entry dict1['School'] = "LJP"; # Add new entry print ("dict1['Age']: ", dict1['Age']) print ("dict1['School']: ", dict1['School']) dict1['Age']: 8 dict1['School']: LJP Deleting Dictionary Elements To explicitly remove an entire dictionary, just use the del statement. # deleting dictionary dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; del dict1['Name']; # remove entry with key 'Name' dict1.clear(); # remove all entries in dict del dict1 ; # delete entire dictionary print("dict1['Age']: ", dict1['Age']) print("dict1['School']: ", dict1['School']) NameError Traceback (most recent call last) in 3 dict1.clear(); # remove all entries in dict 4 del s ; # delete entire dictionary ----> 5 print("dict1['Age']: ", dict1['Age']) 6 print("dict1['School']: ", dict1['School']) NameError: name 'dict1' is not defined LJ Polytechnic Page 49 of 81 Python Programming Build-in Dictionary Functions & Methods Python includes the following dictionary functions Method Description dict.clear() Removes all elements of dictionary dict dict.copy() Returns a shallow copy of dictionary dict dict.fromkeys() Create a new dictionary with keys from seq and values set to value dict.get(key, default=None) Returns the value of the item with the specified key dict.items() Returns a list of dict's (key, value) tuple pairs dict.keys() Returns list of dictionary dict's keys dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already indict dict.update(dict2) Adds dictionary dict2's key-values pairs to dict dict.values() Returns list of dictionary dict's values # clear() dict = {'Name': 'Zara', 'Age': 7}; print("Start Len : %d" % len(dict)) dict.clear() print("End Len : %d" % len(dict)) Start Len : 2 End Len : 0 # copy() dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print("New Dictionary : %s" % str(dict2)) New Dictionary : {'Name': 'Zara', 'Age': 7} # fromkeys() seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) print("New Dictionary : %s" % str(dict)) LJ Polytechnic Page 50 of 81 Data Structures in Python Unit-3 dict = dict.fromkeys(seq, 10) print("New Dictionary : %s" % str(dict)) New Dictionary : {'name': None, 'age': None, 'sex': None} New Dictionary : {'name': 10, 'age': 10, 'sex': 10} # get() dict = {'Name': 'Zabra', 'Age': 7} print("Value : %s" % dict.get('Age')) print("Value : %s" % dict.get('Education', "Never")) Value : 7 Value : Never # items() dict = {'Name': 'Zara', 'Age': 7} print("Value : %s" % dict.items()) Value : dict_items([('Name', 'Zara'), ('Age', 7)]) # keys() dict = {'Name': 'Zara', 'Age': 7} print("Value : %s" % dict.keys()) Value : dict_keys(['Name', 'Age']) # setdefault() dict = {'Name': 'Zara', 'Age': 7} print("Value : %s" % dict.setdefault('Age', None)) print("Value : %s" % dict.setdefault('Sex', None)) Value : 7 Value : None # update() dict1 = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female'} dict1.update(dict2) print("Value : %s" % dict1) Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'} LJ Polytechnic Page 51 of 81 Python Programming # values() dict = {'Name': 'Zara', 'Age': 7} print("Value : %s" % dict.values()) Value : dict_values(['Zara', 7]) Set Sets are used to store multiple items in a single variable. A set is a collection which is unordered, unchangeable, and unindexed. Sets are written with curly brackets. Set items are unchangeable, but you can remove items and add new items. # creating set thisset = {"apple", "banana", "cherry"} print(thisset) {'banana', 'apple', 'cherry'} Note: Sets are unordered, so you cannot be sure in which order the items will appear. Duplicates Not Allowed Sets cannot have two items with the same value. # creating set thisset = {"apple", "banana", "cherry"} print(thisset) {'banana', 'apple', 'cherry'} Set Items - Data Types Set items can be of any data type. # string, int and boolean data types set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} A set can contain different data types. # set with strings, integers and boolean values set1 = {"abc", 34, True, 40, "male"} print(set1) {True, 'abc', 34, 40, 'male'} LJ Polytechnic Page 52 of 81 Data Structures in Python Unit-3 Access Items You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. # loop through the set, and print the values thisset = {"apple", "banana", "cherry"} for x in thisset: print(x, end=",") cherry,banana,apple, # check if "apple" is present in the set: thisset = {"apple", "banana", "cherry"} print("apple" in thisset) True Add Items Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the add() method. # add an item to a set, using the add() method thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) {'cherry', 'orange', 'banana', 'apple'} To add items from another set into the current set, use the update() method. # add elements from tropical into thisset thisset = {"apple", "banana", "cherry"} tropical = {"pineapple", "mango", "papaya"} thisset.update(tropical) print(thisset) {'banana', 'mango', 'apple', 'cherry', 'papaya', 'pineapple'} Add Any Iterable The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.). # add elements of a list to at set LJ Polytechnic Page 53 of 81 Python Programming # add elements from tropical into thisset thisset = {"apple", "banana", "cherry"} mylist = ["kiwi", "orange"] thisset.update(mylist) print(thisset) {'cherry', 'kiwi', 'orange', 'banana', 'apple'} Remove Item To remove an item in a set, use the remove(), or the discard() method. # remove "apple" by using the remove() method thisset = {"apple", "banana", "cherry"} thisset.remove("apple") print(thisset) {'cherry', 'banana'} # remove "apple" by using the discard() method thisset = {"apple", "banana", "cherry"} thisset.discard("apple") print(thisset) {'cherry', 'banana'} You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item. # remove the last item by using the pop() method thisset = {"apple", "banana", "cherry"} x = thisset.pop() print(x) print(thisset) cherry {'banana', 'apple'} # clear() method empties the set thisset = {"apple", "banana", "cherry"} thisset.clear() print(thisset) LJ Polytechnic Page 54 of 81 Data Structures in Python Unit-3 set() # del keyword will delete the set completely thisset = {"apple", "banana", "cherry"} del thisset print(thisset) NameError Traceback (most recent call last) in 1 thisset = {"apple", "banana", "cherry"} 2 del thisset ----> 3 print(thisset) NameError: name 'thisset' is not defined Join Sets There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another. # union() method returns a new set with all items from both sets set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) {1, 'c', 2, 3, 'a', 'b'} # update() method inserts the items in set2 into set1 set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set1.update(set2) print(set1) {1, 'c', 2, 3, 'a', 'b'} Note: Both union() and update() will exclude any duplicate items. Keep ONLY the Duplicates The intersection_update() method will keep only the items that are present in both sets. # keep the items that exist in both set x, and set y x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} LJ Polytechnic Page 55 of 81 Python Programming x.intersection_update(y) print(x) {'apple'} The intersection() method will return a new set, that only contains the items that are present in both sets. # return a set that contains the items that exist in both set x, and set y x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z) {'apple'} Keep All, But NOT the Duplicates The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. # keep the items that are not present in both sets x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(x) {'google', 'cherry', 'microsoft', 'banana'} The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets. # return a set that contains all items from both sets, except items that are present in both x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) print(z) {'google', 'cherry', 'microsoft', 'banana'} LJ Polytechnic Page 56 of 81 Data Structures in Python Unit-3 Practical List 1. Write a Python program to declare a list and display it. 2. Write a Python program to perform the following operations on the list: a) Insert b) Update c) Delete d) Search 3. Write a Python program to declare a tuple and display it. 4. Write a Python program to perform the following operations on a tuple: a) Search b) Merge 5. Write a Python program to declare a dictionary and display it. 6. Write a Python program to perform the following operations on the dictionary: e) Insert f) Update g) Delete h) Search 7. Write a Python program to declare a set and display it. 8. Write a Python program to perform different operations using two sets. Short Questions Sr. Questions Bloom’s Taxonomy No. 1. What is tuple? What is the difference between list and Understand tuple? 2. What are tuples in Python? Understand 3. What is the difference between tuples and lists in Python? Understand 4. Explain what is range() function and how it is used in lists? Remember,Understand 5. What are the advantages of Tuple over List? Remember 6. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 Apply , 2.23, 'john', 70.2 )? 7. What is the output of print tuple + tinytuple if tuple = ( Apply 'abcd', 786 , 2.23, 'john', 70.2 ) and tinytuple = (123, 'john')? Long Questions Sr. Questions Bloom’s Taxonomy No. 1. Mention the features of lists in Python. Remember 2. Give the features of Python dictionaries. Remember 3. Explain lists in Python. Understand 4. Explain tuples in Python. Understand 5. Explain dictionaries in Python. Understand 6. Explain sets in Python. Understand LJ Polytechnic Page 57 of 81 Python Programming 7. What is the difference between lists, tuples and Remember, Understand dictionaries? Give an example for their usage. 8. How lists are updated in Python? Apply 9. What are the basic list operations that can be performed in Remember, Understand Python? Explain each operation with its syntax and example. 10. What is indexing and negative indexing in tuple? Understand 11. What are the methods that are used in Python Tuple? Remember, Understand 12. Is tuple comparison possible? Explain how with example. Understand 13. What is Dictionary? Explain Python dictionaries in detail Remember, Understand discussing its operations and methods. 14. How does del operation work on dictionaries? Give an Understand example. 15. What is the difference between modify and copy operations Understand performed in dictionary? Essential Assignments 1. Remove and add item in a tuple. 2. Remove and add item in a list. 3. Remove and add item in a dictionary. Desirable Assignments 1. Slice list into 3 equal chunks and reverse each chunk. 2. Create a Python set such that it shows the element from both lists in a pair. 3. Find the intersection (common) of two sets and remove those elements from the first set. Activities 1. Reverse the given tuple. 2. Search the given value in tuple. 3. Turn every item of a list into its square. 4. Concatenate two list in a given order. 5. Add a new item in the list after given item. 6. Convert two lists into dictionary. 7. Check if a value exists in a dictionary. 8. Add a list of elements in a set. 9. Get unique items from two sets. Learning Outcome ❖ To learn different data structures in Python. ❖ To be able to perform various operations on members of data structures in Python. LJ Polytechnic Page 58 of 81 Classes & Modules in Python Unit-4 Classes & Modules in Python Python Classes/Objects Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Create a Class To create a class, use the keyword class # create a class named MyClass, with a property named x class MyClass: x=5 Create Object Now we can use the class named MyCl

Use Quizgecko on...
Browser
Browser