Partial preview of the text
Download Python programming Made Easy step-by-step Notes for school students and college students and more Study notes Computer science in PDF only on Docsity!
OPEN ELECTIVE Ill (R17A0554) PYTHON PROGRAMMING OBJECTIVES: e Toread and write simple Python programs. e To develop Python programs with conditionals and loops. e To define Python functions and call them. e To use Python data structures —- lists, tuples, dictionaries. e To do input/output with files in Python. UNIT I INTRODUCTION DATA, EXPRESSIONS, STATEMENTS Introduction to Python and installation, data types: Int, float, Boolean, string, and list; variables, expressions, statements, precedence of operators, comments; modules, functions--- function and its use, flow of execution, parameters and arguments. UNIT I CONTROL FLOW, LOOPS Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else); Iteration: while, for, break, continue. UNIT Il FUNCTIONS, ARRAYS Fruitful functions: return values, parameters, local and global scope, function composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Python arrays, Access the Elements of an Array, array methods. UNIT IV LISTS, TUPLES, DICTIONARIES Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension; Dictionaries: operations and methods, comprehension; UNIT V FILES, EXCEPTIONS, MODULES, PACKAGES Files and exception: text files, reading and writing files, command line arguments, errors and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module), Explore packages. OUTCOMES: Upon completion of the course, students will be able to e Read, write, execute by hand simple Python programs. e Structure simple Python programs for solving problems. e Decompose a Python program into functions. e Represent compound data using Python lists, tuples, dictionaries. e Read and write data from/to files in Python Programs TEXT BOOKS 1.Allen B. Downey, ‘Think Python: How to Think Like a Computer Scientist**, 2nd edition, Updated for Python 3, Shroff/O*Reilly Publishers, 2016. 2.R. Nageswara Rao, “Core Python Programming”, dreamtech 3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson REFERENCE BOOKS: 1. Core Python Programming, W.Chun, Pearson. 2. Introduction to Python, Kenneth A. Lambert, Cengage 3. Learning Python, Mark Lutz, Orielly LISTS, TUPLES, DICTIONARIES 78 Lists 78 list operations 79 list slices R() list methods 8] list loop 83 mutability R5 aliasing 87 IV cloning lists RR list parameters R9 list comprehension 90 Tuples 91 tuple assignment 94 tuple as return value 95 tuple comprehension 96 Dictionaries 97 operations and methods 97 comprehension 102 V FILES, EXCEPTIONS, 103 MODULES, PACKAGES Files and exception: text files 103 reading and writing files 104 command line arguments 109 errors and exceptions 112 handling exceptions 114 modules (datetime, time, OS , calendar, 121 math module) Explore packages 134 EES 5 /|/|'|'/||:|:|:|:»||||||||sS» UNIT -I INTRODUCTION DATA, EXPRESSIONS, STATEMENTS Introduction to Python and installation, data types: Int, float, Boolean, string, and list; variables, expressions, statements, precedence of operators, comments; modules, functions-- - function and its use, flow of execution, parameters and arguments. Introduction to Python and installation: Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. * On 16 October 2000, Python 2.0 was released with many new features. * On 3rd December 2008, Python 3.0 was released with more testing and includes new features, Beginning with Python programming: 1) Finding an Interpreter: Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.con/ or http://codepad.org/ that can be used to start Python without installing an interpreter. Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) which is installed when you install the python software from http://python.org/downloads/ 2) Writing first program: # Script Begins Statement1 3. It’s free (open source) Downloading python and installing python is free and easy 4. It’s Powerful e Dynamic typing e Built-in types and tools e Library utilities e Third party utilities (e.g. Numeric, NumPy, sciPy) e Automatic memory management 5. It’s Portable e Python runs virtually every major platform used today e As long as you have a compaitable python interpreter installed, python programs will run in exactly the same manner, irrespective of platform. 6. It’s easy to use and learn e No intermediate compile e Python Programs are compiled automatically to an intermediate form called byte code, which the interpreter then reads. e This gives python the development speed of an interpreter without the performance loss inherent in purely interpreted languages. e Structure and syntax are pretty intuitive and easy to grasp. 7. Interpreted Language Python is processed at runtime by python Interpreter 8. Interactive Programming Language Users can interact with the python interpreter directly for writing the programs 9. Straight forward syntax The formation of python syntax is simple and straight forward which also makes it popular. Installation: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) which is installed when you install the python software from http://python.org/downloads/ Steps to be followed and remembered: Step 1: Select Version of Python to Install. Step 2: Download Python Executable Installer. Step 3: Run Executable Installer. Step 4: Verify Python Was Installed On Windows. 3 Step 5: Verify Pip Was Installed. Step 6: Add Python Path to Environment Variables (Optional) Ye Python 3.8.0 (64-bit) Setup = x | Install Python 3.8.0 (64-bit) Select Install Now to install Python with default settings, or choose Customize to enable or disable features. @ install Now C:\Users\ i \AppData\Local\Programs\Python\Python38 Includes IDLE, pip and documentation Creates shortcuts and file associations — Customize installation Choose location and features pytho Install launcher for all users (recommended) wind WS Add Python 3.8 to PATH Cancel Working with Python Python Code Execution: Python’s traditional runtime execution model: Source code you type is translated to byte code, which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled, but then it is interpreted. Source Byte code Runtime \ iN -—> —> c—> PVM m.py m.pyc¢ Source code extension is .py Byte code extension is .pyc (Compiled python code) There are two modes for using the Python interpreter: * Interactive Mode * Script Mode Alternatively, programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. To execute the script by the interpreter, you have to tell the interpreter the name of the file. For example, if you have a script name MyFile.py and you're working on Unix, to run the script you have to type: python MyFile.py Working with the interactive mode is better when Python programmers deal with small pieces of code as you can type and execute them immediately, but when the code is more than 2-4 lines, using the script for coding can help to modify and use the code in future. Example: Data types: The data stored in memory can be of many types. For example, a student roll number is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. >>> print(24656354687654+2) 24656354687656 >>> print(20) 20 >>> print(Ob10) 2 >>> print(0B 10) 2 >>> print(OX20) 32 >>> 20 20 >>> 0b10 2 >>> a=10 >>> print(a) 10 # To verify the type of any object in Python, use the type() function: >>> type(10) >>> a=11 >>> print(type(a)) Float: Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10. >>> y=2.8 >>> y 2.8 >>> y=2.8 >>> print(type(y)) >>> type(.4) >>> 2. >>> print(‘mrcet college’) mrcet college wow >>> rt 14/142 If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. If a string is to contain a single quote, delimit it with double quotes and vice versa: >>> print("mrcet is an autonomous (') college") mrcet is an autonomous (') college >>> print(‘mrcet is an autonomous (") college’) mrcet is an autonomous (") college Suppressing Special Character: Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character: >>> print("mrcet is an autonomous (\') college") mrcet is an autonomous (') college >>> print(‘mrcet is an autonomous (\") college’) mrcet is an autonomous (") college The following is a table of escape sequences which cause Python to suppress the usual special interpretation of a character in a string: >>> print(‘a\ wb’) a....b >>> print(‘a\ b\ c') 19:47 Ob +eme i Ti G > 4 Vv PYTHON PROGRAMMING NOTES.pdf ma in mrcet.com abc >>> print(‘a \n b') a b >>> print("mrcet \n college" pani \ Be’) 15/142 mrcet college Escape Usual Interpretation of Sequence Character(s) After Backslash “Escaped” Interpretation \' Terminates string with single quote opening delimiter —_ [Literal single quote (') character \" Terminates string with double quote opening delimiter [Literal double quote (") character \newline (Terminates input line Newline is ignored \\ Introduces escape sequence Literal backslash (\) character In Python (and almost all other common computer languages), a tab character can be specified by the escape sequence \t: >>> print("a\tb") a b List: e It is a general purpose most widely used in data structures e List is a collection which is ordered and changeable and allows duplicate members. (Grow and shrink as needed, sequence type, sortable). e To use a list, you must declare it first. Do this using square brackets and separate values with commas. e We can construct / create list in many ways. Ex: >>> listl=[1,2,3,'A’,'B',7,8,[10,11]] >>> print(list1) [1, 2, 3, 'A’, 'B', 7, 8, [10, 11]] 10 PYTHON PROGRAMMING lll YEAR/II SEM MRCET >>> x=list() >>> X 19:47 Ob +eme $i Tl G x vy, ve PROGRAMMING NOTES.pdf ma in For example — a= 100 # An integer assignment b = 1000.0 # A floating point c= "John" # A string print (a) é print (b) print (c) This produces the following result — 100 1000.0 John Multiple Assignment: Python allows you to assign a single value to several variables simultaneously. For example : a=b=c=1 Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example — a,b,c = 1,2,"mrcet* Here, two integer objects with values | and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c. Output Variables: The Python print statement is often used to output variables. Variables do not need to be declared with any particular type and can even change type after they have been set. 12 PYTHON PROGRAMMING Ill YEAR/II SEM MRCET x=5 # x is of type int x="mreet" #x is now of type str print(x) Output: mrcet 19:47 Ob +eme $i Tl G PYTHON PROGRAMMING NOTES.pdf mrcet.com x=5 # x is of type int x="mreet" #x is now of type str print(x) Output: mrcet To combine both text and a variable, Python uses the “+” character: Example 18/142 e x = "awesome" print("Python is " + x) Output Python is awesome You can also use the + character to add a variable to another variable: Example x = "Python is " y = "awesome" Z=x+y print(z) Output: Python is awesome Expressions: An expression is a combination of values, variables, and operators. An expression is evaluated using assignment operator. Examples: Y=x + 17 >>> x=10 >>> Z=x+20 >>> 30 13 PYTHON PROGRAMMING Ill YEAR/I1 SEM MRCET >>> x=10 >>> y=20 19:47 B® i> i> + Me > 4 Vv PYTHON PROGRAMMING NOTES.pdf mrcet.com Operator Token add + subtract - multiply . Integer Division / remainder % Binary left shift << Binary right shift >> and & or \ Less than < Greater than > Less than or equal to <= Greater than or equal to >= Check equality Check not equal 15 $i Tl G < A 20/142 PYTHON PROGRAMMING Some of the python expressions are: Generator expression: Syntax: ( compute(var) for var in iterable ) Il YEAR/II SEM MRCET 19:47 B® i> i> + Me > 4 Vv $i Tl G PYTHON PROGRAMMING NOTES.pdf ma in mrcet.com Some of the python expressions are: Generator expression: Syntax: ( compute(var) for var in iterable ) >>> x = (i fori in ‘abc') #tuple comprehension >>> x 21/142 at 0x033EEC30> Gi >>> print(x) at 0x033EEC30> You might expect this to print as (‘a’, 'b’, 'c') but it prints as at Ox02AAD710> The result of a tuple comprehension is not a tuple: it is actually a generator. The only thing that you need to know now about a generator now is that you can iterate over it, but ONLY ONCE. Conditional expression: Syntax: true_value if Condition else false_value >>> x= "1" if True else "2" >>> x "4" Statements: A statement is an instruction that the Python interpreter can execute. We have normally two basic statements, the assignment statement and the print statement. Some other kinds of statements that are if statements, while statements, and for statements generally called as control flows. Examples: An assignment statement creates new variables and gives them values: >>> x=10 16 PYTHON PROGRAMMING lil YEAR/II SEM MRCET >>> college="mrcet" An print statement is something which is an input from the user, to be printed / displayed on to the screen (or ) monitor. >>> print("mrcet colege")