100% found this document useful (1 vote)
2K views

Computer Science With Python 12th Sumita Arorapdf Compress

Uploaded by

jdh dave
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
2K views

Computer Science With Python 12th Sumita Arorapdf Compress

Uploaded by

jdh dave
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 628
Textbook for Class XIl «Programming & Computational Thinking + Computer Networks os + Data Management (SQL. Django) + Society, Law and Ethics - SUMITA ARORA , DHANPAT RAI & Co. COMPUTER SCIENCE DHANPAT RAI & CO. (Pvt.) Lte EDUCATIONAL & TECHNICAL PUBLISHER GAGAN KAPUR (P) Ltd., Delhi sk, Delhi-1 10006 Published by = Dhanpat Rai & CO- Soles Office + 1710, Nal Sara Phone : 2325 0251 4576/15, Agarwal Road New Delhi-! 10002 [email protected] Regd. O'tice Dorya Garis Phone : 2324 7736, 37, 38, © Sumita Arora Sa All Trademarks Acknowledged Disclaimer Every effort has been made to avoid errors or omissions in this publication, In spite of this, some errors might have crept in. Any mistake, error or discrepancy noted may be brought to our notice which shall be taken care of in the next edition. It is notified that neither the publisher nor the author or seller will be responsible for any damage or loss of action to any one, of any kind, in any manner, therefrom. cance] Google Play EDITIONS : 1997, 1998, 2002, 2004, 2007, 2009, 2010, 2011, 2012, 2017 REPRINT : 2002, 2003, 2004, 2005, 2006, 2009, 2013, 2015, 2016, EDITION : 2014, 2019 (with Python) THIRTEENTH EDITION : 2020 (with Python) PRICE : © 595/- Combined Price (Textbook -+ Practical book) Typeseting by : Nom Delhi Computer Convention, Delhi-1 10009, [email protected] Printed ot : Notraj Offset, Delhi Preface Modern age technologies art 80 fast changing that we have to adapt to them in all spheres of life at the same pace. Education (especially Computer Science subjects} is ane such field where we see major change in the syllabi every now and then. The subject ‘Computer Science’ (code 083) saw a major curriculum change'lin the recent past to accommodate the changing needs as per the changing technologies. The'book in your hands is an updated and revised edition of the subject ‘Computer Science’ (code 083) Class 12» which now also contains objective type questions added to each chapter along with many important minor updations in ‘the content of the book ‘ a Like earlier edition, this book adheres to the CBSE curriculum for. Computer Science (083) for Class Xi. Based on the syllabus, the book has been divided into four units. % a Unit 1: Programming ond Computational Thinking (PCT=2) Unit 1 has been divided into mine chapters (chapters 1-9). It covers Python programming through revision tour, Python functions, Libraries, File handling in Python, Recursion in Python functions, Data visualization using PyPlot, Data Structures in'Python, This unit also covers basics of determining algorithm efficiency. a ‘ Unit 2: Computer Networks (CN) ‘is unit has been divided int6 two chapters (chapters 10-13). t covers computer networks’ basics such 85 types of networks, cloud technology, loT;,wired!and wireless networks, client, server networks, network devices, modulation techniques, collision in wireless networks, IPv4, IPv6, TCP, other Protocols and network tools)" Unit 3: Data Management (DM-2) This unit has-been divided into four chapters (chapters 12-15). It covers SQL revision, more on SQL commands, developing a ‘minimal Web application using Django web framework, and Python database connectivity with MySQL databases. Unit 4 : Society, Law and Ethics (SLE-2) This unit has been covered in one chapter (chapter 16). it covers ‘many topics and issues related to fociety law and ethics, such 2s PR, plagiarism, digital cights and licencing, privacy laws and cyber crime, IT act, e-waste management, challenges online and gender and disability issues. Apart from the text book, we have also provided a practical book ‘Progress In Python’ that contains Sntitional practice exercises. Although the text book contains sufficient number ot practice questions and exercises, yet the additional Practice of exercises given in the Practical book will make the foundation of programming and other concepts even stronger . . shots of Python shell used jn < the book, we have shown screen: s ed in Spy, T:In some chapters of prompt to take commands. But in text section, we hare oe IMPORTAN es Inf ] : IDE (IPython aia which is a standard way of telling that this command is given on s Python ‘commands with >: a mpt. pee sat execute the code in the same way, though IPython shell is an enhanced shell, usa in All Python sI i dl other research works. You,are free to use iversities and preferred in data sciences an i opt fre any Defi t Your hole! but we lave: irsaled Python adi Anaconda distribution win, Palen , aa Hraries along with Python. As Spyder IDE and IPython shell is available as pat op fee, Python distribution and is very easy to use, we have given screenshots) of Spyder IDE ang Anacon IPython shell in this book at times. The SIPO app for associated Digital Resources. We are launching digital resources along with this book for’ ideos/animations/illustrations ste. + Explanaiory + ‘Selective Assignment solutions Other additional resources . {0 provide visual Support for your learning. To Use.and view this content, you can use the SIPO'app, downloadable currently from Play Store,(will soon be available on App Store too )- ‘Using the SIPO app, you can scan the OR codes given in the book to play/view the associated digital content. “ ws "While writing the book, we have tried to keep the explanation simple with lots of examples, illustrations and a reader-friendly presentation. Like its predecessors, this book contains the summary of topics covered in the book inthe form of ‘Let\Us Revise’ and keyterms compiled under ‘Glossary’. Also, definitions and important paints have Parately through definition boxes and note boxes respectively. ‘wer type/revision questions in the form of Check Points giver he chapter contains many Solved Problems, Assign type questions, application based questions ieee Compete, there is always scope of improvement Thus, itis a request to our esteemed onan eeritheit feedback, suggestions, opinione ere for the improvement of the book. All your Fesponses are “wholé-Heartedly welcome. 4 ‘SUMITA ARORA E-Mail : [email protected] follow me at : twitter. com/SumitaArora Acknowledgment Acknowledgment is the most beautiful page in any project's final pages. More than @ formality, this appears to me the best opportunity to express my gratitude, Mylist can never begin without you, dear GOD. Rather than saying ‘thank you' to you, you know that | feel like saying ‘I love you’, to you, always. Le 4 Next on my thanks list are my friends, teachers, studerits who eally showered constructive feedbacks and suggestions without which this book Would/fiot have been in present form. ww > _ Special thanks to my critics who help me bring out the best. Thank You people Very Auch; your honest opinions are most welcome. | really respect your opinions? mean it”: Now it’s time to thank those people who have helped me in thisyproject. Kush, thank you for your technical support. Meenu, thank you very much forthe efforts that you put in, in the production of the book. I can never think of any project without you. God bless you. Manoj and HariChand, Thank youery:much for all that you have done. Jagdish Ji and Gagan Ji, you people are real foundations of the projects done by me. My projects would never have. been possible without your faith in me. Thank you very much. { Finally, | must say thanks to my family. All know and | repeat it every time that my husband Sandeep is the réason and real force behind my writing, Thank you Sandeep for yur faith and above all your unending support in litle-little ways from kitchen to final protbor the book ; you have always/been by my side to encourage me, support me. ‘Thank you very much’¢Kushagra and Mythil, my sweethearts, l love you and thank you for your support. You have always tried not to disturb me whenever | am stuck in something. | feel proud at & “understanding ways and maturity. God bless you. Love you. \I,cannot end this list, without thanking the esteemed readers of the book who keep sending me their honest opinions, feedback, suggestions, complaints etc. Thank you for yyouriove, your ‘support. Just keep connected. ‘SUMITA ARORA, E-Mail : arora.sumitaegmail.com follow me at : twitter.com/SumitaArora Syllabus pistibution of Marks unit No. Unit Name Programming and Computational Thinking-2 as PRTC A Ta oe is eR Gans eae i 2 Data Management—2 5 Practicals Total & Revision of the basics of Python i Functions: scope, parameter passing, mutable/immutable properties of data objects, pass arrays to functions, retur values, functions using libraries : matliematicalyand string functions. % File handling: open and close a file, read, writ@and|append to a filé, standard input, output and error Ye, streams, relative and absolute paths. = Yp. ~ Using Python libraries: create and import Pythoflibrari > Recursion: simple algorithms with,recursion: factorial, Fib > Idea of efficiency: performanée defined asinversely proportional to the wall clock time, count the number of operations a piece of code is performing, 6nd measure the time taken by a program. Example: take two different programs forthe same problem, en derstand how the efficient one takes less time. + Data visualization ising Pyplot line chart, pie chart, and bar chart. + Data-structures: lists, stacks, queues, Q . bs .cci numbers; recursion on arrays: binary search. Unit 2: Compiiter Natv SC N) (30 Theory + 10 Practical) + Structure bfa network Types of'networks: local area and wide area (web and internet), new technologies ouidjand IoT, public vs private cloud, wired and wireless networks; concept of a client and server- S¢Networl IC, switch, hub, router, and access point. stack; amplituc is id frequency modulation, collision in wireless networks, error checking, and the pce iain idea of routing. IP addresses: (v4 and v6), routing table, router, DNS, and wed sic idea of retransmission, and rate modulation when there is congestion (analogy to a road pean = 2G, 3G, AG, Wi-Fi. What makes a protocol have a higher bandwidth ? ‘ols: traceroute, ping, ipconfig, nslookup, whois, speed-t + Applicatic ‘ Pe ee Pe ation layer: HTTP (basic idea), working of email, secure communication : encryption and certificates GITPS), netw * (easte Yorn nec applications: remote desktop, remote login, HTTP, FTP, SCP, SSH, POP/IMAP, SMTP, Unit 3: Data Man. agement (DM-2} . > Write a minimal See a ) (20 Theory + 20 Practical) * file - flatfile and CSV file. web application that parses a GET and POST. request, and writes the fields 04 Uerface Python with an SQL database * SQL command : ‘aggregation functions — having, group by, order by. | Unit 4: Society, Law and Ethics (SLE-2) (10 Theory) + Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL and Apache), open source, open data, privacy + Privacy’ laws, fraud; cyber-crime, phishing, illegal downloads, child pornography, seams; cyber forensics, IT Act, 2000. & Technology and socioty: understanding, of societal issues 4 Exwaste management : proper disposal of used electronic gadgets Identity theft, unique ids, and biometrics. Gonder and disability igsues while teaching and using computers. nd cultural changes induced by technology. PRACTICAL [Unit No. Unit Name 2 P Marks 1 Lab Test (10 marks) | | Python program (60% logic + 20% documentation 20% code quality) 7 | | ‘Small Python program that sends a SQL query to a databace and 3 | displays the result, A stub program can be provided fez Report File + Viva (9 marks) » Report file : Minimum 21 Python programs: Out of this at least 4 7 programs should send SQL commands to a database and retrieve the | | result; at least 1 program should implement the web server to write | user data to a CSV file. ‘ Viva voce : (based onthe report file). 2 3. Project + Viva (11 marks) Project (that uses most of the concepts that have been learnt) gt | Projec vietioe | Programming in Python Reeursively find the factorial of a natural number. Read a file line by line and print it. Remove all the lines that contain the character ‘a’ in a file and write it to another file, Write a Python function sin (x, n) to calculate the value of sin (x) using its Taylor series expansion up to 1 terms. Compare the values of sin (x) for different values of with the correct value. Write a random number generator that generates random numbers between T and 6 Write a'recursive code to find the sum of all elements of alist. Write a recursive code to compute the 1 Fibonacci number. Write a Python program to implement a stack and queue using a list date-structure, Write a recursive Python program to test if a string is a palindrome or not, Write a Python program to plot the function y= x* using the pyplot or matplotlib libraries. Create a graphical application that accepts user inputs, performs some operation on them, and then writes the output on the screen. For example, write a small calculator. Use the thinter library (Open a webpage using the urllib library. (Compute EMIs for a Joan using the numpy or scipy libraries. ‘Take a sample of 10 phishing e-mails and find the most common words. Data Management : SQL and Web-Server Find the min, max, sum, and average of the marks in a student marks table. + Find the total number of customers from each country in the table (customer ID, customer name, country) using group by. (simulates a dice). Hod FHSS HHH CHES is) table in descending order of the marks. (student ID, ing the MySQL. module. fh user request (POST), and write it to a CSV file to order the python by imper! { yer to parse L query 1 with asodt web serv + Write a SQ! > Integrate § Write a Diange ible and useful. This should be done in gs vet is tv create something, that is tangibl groups of clas piety py ater at Teas 6 months befre the submission deadline. The amy and should Pe sryom that is worthwhile to solve. Students are encouraged 19 visit local eal orm For example, if a business is finding it hard about the problems that they are fa for fling GST aims, then students can do a project that lakes the raw data (list of coicos for fii 3 oon cctions by category, accounts for the GST tax rates and creates invoices in the be extremely creative here. They can use a wide variety of Python libraries mes, software for their school, software for their disabled fellow ional learning is required; Project & Theaimof the puisinesces and ask I to create in oneactions), BROUPS depart formal Students cM Pom reuser friendly applications such as pols oerete we mobile applications. Of course todo some ofthis projects some add eee yaad be encouraged, Students should know how to teach themselves: : tethee people work on a project for 6 months, atleast 500 lines of code is expected. The committee has also doers aware about the degree of plagiarism in such projects. Teachers should take a very strict look at TR ation and take very strict disciplinary action against stuclents who are cheating on lab assignments, or vccts or using pirated software to do the same. Everything that is proposed can be achieved using Sbsolutely free, and legitimate open source software. The)SIPO. app for Digital Content linked with this book Deor Students f Get hold of Linked Learning Resources (explanatory videos/ r illustrations/images/text solutions) for FREE, by scanning QR codes ‘ Hi given in the chapters using our integrated learning app i, cm S tipo Linked resources include : ® explanatory videos animations illustrations So, re what are you wailing for ? Download SIPO now. 1 -40 Python Revision Tour 1.1 Introduction 1.2. Tokens in Python 1.2.1 Keywords 2 41.2.2 Identifiers (Nantes) 2 41.2.3 Literals/Valwes 3 1.24 Operators 4 1.25 Punctuators 4 1.3. Barebones ofa Python Program 1.4. Variablesand Assignments 14. Dynamic Typing 6 14.2 Multiple Assignments 6 1.5. Simple Input and Output Output Through prini() Statement 8 1.6 Data Types 1.7, Mutableand Immutable Types 1.8. Expressions 1.8.1 Evaluating Arithmetic Operations. 14 1.8.2. Evaluating Relationnd Expressions 15 1.83) Evaluating Logical Expressions 16 4.8.4 Type Costing (Explicit Type Conversion) 16 seo 1.8.5 Math Library Functions. 37 1.9 Statement Flow Control 10 The if Conditionals S 1.10.1 Plain if Conditional Statement 20 8 4.10.2 The if-else Conditional Statement 20 1.103, Tie if-lif Conditional Statement 21 1.104 Nested if Statements 25, 4105 Storing Conditions 23 1.11. Looping Statements “S LILT The for Loop 24 1.112 The while Loop 26 1.12 Jump Statements breakand continue ‘The break Statement 26 The cominne Statement 2? 1.13 More on Loops 1.13.1 Loop else Staten 1.132 Nested Loops 29 Y | Contents 10 12 14 19 20 2 26 28 jsion Tour-H on Revi a 2 21. Introduction 44 40% in Python are eon Assignment no! Supported 42 string 42 221 2.22 Traversing 4 23 siring Operators 42 224 string stces 45 2.25 String Functions 46 23. Lists in Python 51 ‘2.31 Crenting Lists 51 2.3.2 Lists vs. Strings 52 233. List Operations 53 2.34 List Manipulation 55 2.35 Making True Copy ofa List 56 23.6. List Functions 56 24 Tuplesin Python 2.41 Creating Tuples. 60 24.2 Tuples vs. Lists 61 24.3 Tuple Operations 62 60 25 Detain RQ, Ale. . 66 253° Ch 254. Dictona opto el 255¢Dietionary ae cond et 26 Sorting Techniques 78 Ey. Sort te 6.2 Ins ‘ % g with Functions Ne Rega Functions - ling/Invoking/LIsing « Function 95 * 22 Python Function Types. 96 Defining Functions in Python -_ a Structure of a Python Program 99 ° ! ‘ow of Execution ina Function Call 3.41 Arguments and Pa . 's and Parameters 108 35. Passing Parameters 106 3. 38 1 PositionelMRequired Arguments. 106 32 Default Argumenis. 107 Keyrord (Named) Arguments 108 3.54 Using My "8 Multiple Argument Types Together 109 a-_p 3.6. Returning Values From Functions 6.1 Returning Multiple Volues 113 37 Composition 38 Scope of Variables 38.1 Nome Resotution (Resolving Scape of a Name) 120 3.9. Mutable/Immutable Properties of Passed Data Objects RO.D Mutalitity/ioomutablity of ArgumentsParameters and Function Calls 125 [) Using Python Libraries | 4a Introduction 4.2 Whatisa Library? 4.2.1 What isa Module 2154 4.3. Importing Modules ina Python Program 43:1 Importing Entire Module. 158 4.3.2 Importing Select Objects from a Module 159 153 ~ 186 43.3. Python's Processing of import Command 159) 4.4 Using Python Standard Library's Functions and Modules 44.1 Using Python’ Builtin Functions. 182 44.2 Working with Some Standard Litrary Modulus 168 4.5. Creatinga Python Library 4.5.41 Structure of a Package 4.5.2 Procedure for Creating Packages 172 4.5.3. Using/tmporting Pyttin Libraries. 17% Useful Additional Information (UAI) Object Oriented Programming Concepts (UAl-1) 5 File Handling 195-228 5.1 Introduction 52. Data Files % 5.3, Opening and Closing Files 5.1 Opening Files 196 ~ 5.3.2) Closing Files 199 “) 5A) Reading and Writing Files 54.1 Reading from Files 199 542 Writing onto Files 205 54.3 The flush( ) Function SAA. Removing Whitespace after Reading from File 209 BAS. Significance of File Poin ‘ile Handling 201 55. Standard Input, Output and Error Streams 6 [Recursion 229 -— 264 6.1 Introduction 6.2. Recursive Function | = | 110 us 115 123 153 154 157 162 a7 187-194 195 196 196 199 212 229 230 M63 How Recursion Works hon 6a_ Recursion In Pyt 641 Some Recursive Coles 243 ‘62 Binary Senreh 246 64. Recursine Binary Search 260 233 240 251 65. Recursion vsiteration ae jdea of Algorithmic Efficiency : 5 7.1. Introduction ; eae fr Whatis Computational Complexity? pe | 73. Estimating Complexity of Algorithms 71. Big-O Notation 26 5.3.2 Guidelines for Computing Complexity 268 74 Best, Averageand Worst Case Complexity 21 8 Data Visualization using Pyplot 285 - 332 8.1 Whatis Data Visualization? 285 82. Using Pyplot of Matplotlib Lib 286 4.21 Inseling and Importing ninipletib 286 8.2.2 Working with PyPlob Me fetiads 287, : 83 Creating Charts with’ atplotib Library's pyplot Interface 293 8.3.1 Line Charf}293 Ry 833 The Pie Cart 309 ie 84 Cust ingot 314 natomy of a Chat 314 42 Aang Tle 315 3 Setting.x and Y Laos, Limits and Ticks 315 pends 319 jug a Figtte 321 hart Types aa fseful Additional Information (UAI) 333-340 List Comprehension And Nested Lists (UAI-2) 9 ff Datastructures : Stacks and Queues using Lists 341 - 384 9.1 Introduction ma 92 Blementary Data Representation aaa 93. Different Data Structures aad 93.1 Linear Lists Arrays 343 93.2 Stacks 343 93.3 Queues 343 93-4 Linked Lists 343 93.5 Trees 344 94 Operations on Data Structures 95 Stacks 9.5.1 Implementing Stack in Python 347 95.2 Siack Applications 350 9.6 Queues 9.6.1 Implementing Queues in Pytion 360 9.6.2 Variations in Queues 363 9.6.3 Quewe Applications 364 10 | Computer Networks - I 10.1. Introduction 10.2. Computer Networks ~ An Introduction 10.2.1 Components of a Computer Network 387 10.3. Types of Networks 103.1 Types of Networks based on ner * 10.3.2 Types of Networks by Component Rolés, 390 104.1 NIC (Network Interface Gift) 386, 1042. Wii Card 396 1043 Hub 397 1044 1045 2046 1047 °3 104.8 Access Poi 105 TheGloud Modulation Techniques > 11.2.1 Major Types of Modulation £10 11.3 Collision in Wireless Networks 11.3.1 How CSMAICA Works 413 11.4 ERROR Checking (Error Detection) 11.5 Main Idea of Routing 11.6 TCP/IP 11.6.1 Network Congestion and Retransmission in TCP 424 IL7 Addresses ona Network ILIA The Domain Name arid DNS 428 344 345 358 385 386 388 396 399 400 409 410 412 415 420 423 425 11.8 Cellular/Wireless Connectivity Protocols 11.9. Basic Network Tools 0 i S TRACEROUTE (for Linus) or TRACERT (for Win 11.93 NSLOOKUP 431 1194 IPCONFIG Command 432 11.9.5 WHOIS Command 433 11.96 Speed Test 433 © 11.10. Various Protocols Used on Networks 11.11 HowHTTP Works - A Basic Idea 11.12, Working of Email Pp 11.13. Secure Communication : 1113.1 HTTPS 439 . 11.132 Secure Sockets Layer (SSL) 439 11.14 Network Applications dows) 431 MySQL SQL Revision Tour 12.1 Introduction 12.2. Relational Data Model Referentil Integrity 456. 12.3. MySQL~ A Popular Relational DataBase Management System, 12.3.1 MySQL and SQL 457 12.3.2 Connon MySQL Data Types 458 124 Accessing Database in MySQL 125 Creating Tables in MySQL. 12.6 Inserting Data Into Table Gnserting NULL vals 460 co nseting Dates 460 27° Making Simple Queries Through Select Command \ 1274 selecting'alt Data 460 % 12.7.2 Selecting Particular Rows 460 %, “Qu273 Selecting Particular Columns 461 7:4 «Bliminating Redundant Data (with Keyoord DISTINCT) 461 = 2275" Selecting From All the Rows ~ ALL Keyword 461 & 127.6 Viewing Structure ofa Table 461 “1277. Performing Simple Calculations. 462 ‘127.8 Using Column Aliases 462 127.5 Condition Based on a Range 462 12.7.10 Cowdition Based on a List 462 127.11 Condition Based on Pattern Matches 462 127.12 Searching for NULL 463 128 Creating Tables with SQL. Constraints 1281 SQL Constraints 464 12.82 Applying Table Constraints 468 a=. 429 430 434 436 437 438 4a 455 456 457 458 459 459 460 464 12.9 ViowingaTable Structure 12.10 Inserting Data Into Another Table 12.11 Modifying Data in Tables, 12.12 Deleting Data from Tables 1213 Altering Tables: 12.14 Dropping Tables IAS. SQL joins 1216 Indexes in Database 13 i More on SQL 13.1 Introduction 483 - 505 13.2. Ordering Records in Result ~ Order by Clause ~N 1321 Reealling SQL SELECT ORDER BY Clause $83 \) 132.2. Ordering Data on Multiple Columns 485 13.2.3 Ordering Data on the Basis of an Expression, 13.24. Specifying Custom Sort Order 486 13.3 Aggregate Functions 13.4 Types of SQL Functions. 13.5. Grouping Result - GROUP BY 2 135.1. Nested Groups ~ Grouping on Multipte Columns 4920) 13.5.2. Placing Conditions on Grows HAVING Clause 493 135.3 Non-Group Expressions wit GROUP BY 14 | Creating a Django based Basic Web Application 507-546 14.1. Introduction 14.2. WhatisWeb Framework? Wel Framework vs, Lary S08 = 143 How Web, Websites and Web-applications Work? 14.4 Introducing Django Why Django ? 510 “44,5: Installing Django Re iy What ispirtuaewe and Why to use it? 510 ee = 45.1 Installing Dia “(4.6 Activating Virtual Environment “147. Django Basics and Project Structure “© 14.2.1 What are ‘Project’ and “App' in Django ? 516 72 Underst 520 14.8 Steps to Createa Basic Django Web Application 149 Creating Models, Viewsand Templates M491 Creating Models 522 14.9.2 Creating Templates 923 14.9.3. Creating Views 524 M94. Creating URL Confs 525 468 469 469 469 470 471 471 472 483 483 488 491 491 507 507 508 510 510 sis 515 s2t 522 {4.10 Writing Dictionary Data to CSV and Text Files A toad Wit into a CSV File 528 i ext File 529 14.102. Writing info 0 Text a pieatly Processing GET and POST Reaves: ua 15 Interface Python with MySQL si } sion 5621S Introduce 547 Sis 15.2. Comnecting to MySQL from Python - cacitstsed 152.1. Steps for Crating Database Connectivity AppHenons 4 153 Parameterised Queries & a 154. Performing insert and update Queries Mm, a @ ai ’ ys ' Society, Law and Ethics ¢ 16.1 Introduction = r 563 16.2 Ethical Issues a 564 j 16.2.1. Intellectual Property Righs 564 16.2.2 Plagiarism 564 * 1623. Digital Property Rights, 565. 163. Open Source Philosophy and Software Licences 566 163.1 Terminology 566, 16.3.2 Philésophy of Open Source 567 1633. Definitions 568, Ys) DLicenses aud Donieins of Open Source Tectmology 570 Q 572 572 .7 Computer Forensics S74 3 : 576 576 87 6.5 ‘echnologyand Society Q ya 21 Economic Benefits 578 -Waste Management p01 E-Waste Disposal Process 578 7 16102 Bongfisofe Waste Recycling 579 16.14 Identity Theft 16.12. Gender Issues while ‘Teaching/Using Computers cei 16.12.1 Gender Issues 581 “ 16.13 Disability Issues while ‘Teaching and using Computers 583 = Appendices A1-A26 Appendix A: Utility of Module’s _name_ Appendix B: Working with A Useful Python Library ~ tkinter Appendix + Django Installation on Ubuntu Linux Appendix D: Creating (data) Models for Django apps Appendix #2; Installing MySQL. Python Connector Appendix F: Project Creation and Distribution Appendix G: Additional Problems on Networking Answers to Objective Type Questions (OTQs) @-@) Additional Resource 1 Additional Resource 2 Additional Resource 3 ERS (Bae aR a : U AL Az AS AS ALO AAL Aly sts OF QR CODES ists oF QR COPES Bubble Sort in action 75 Insertion Sort inaction 76 Function Anatomy in action 95 Part of a Function in action 95 Working of a Function in action 101 Flow of Execution in action 103 Function Parameters in action 106 Variable Scope in action 118 Name Resolution in action 120 For Selective Assignment Solutions Two Ways of Import in action 761 For Selective Assignment Solutions Reading from File in action 201 working of File Pointer in action 217 For Selective Assignment Solutions 226 47 (82 Recursion in action 233 Recursion in action 238 For Selective Assignment Solutions 267 Loops Complexity 268 Consecutive Statements Complexity 269 Nested Loops Complexity 269 Itelse Complexity 270 Logarithmic Complexity 270 For Selective Assignment Solutions 282 These Graphs in action 301 This Graph in action 308 These Graphs in action 373 For Selective Assi Stacks in action 345 ‘semen! Solaons 230 Queues in action 259 Circular Queues in action 363 For Selective Assignment Solutions 392 Development of Django Web Application 539 | To Kushagra and Mythili, With Love 11 1.1 Introduction 1.8 Expressions 1.2. Tokens in Python 1.9 Statement Flow Control 1.3 Barebones of a Python Program 1.10 The if Conditionals 1.4. Variables and Assignments 1.11 Looping Statements 1.5 Simple Input and Output 1.12 Jump Statements — break and continue 1.8 Data Types 1.13 More on Loops 1.7. Mutable and Immutable Types INTRODUCTION ‘You must have enjoyed learning Python in class XI. Python programming language, developed by Guido Van Rossum in early 1990s, has become a very popular programming language among beginners as well as developers. The joumey of Python that you started in class XI will continexe iy class XII as well. In class XIL, you shall learn more about Python and some advanced concepts, Before we start with newer topics and concepts in Python, let us revise all that you have earntin class X1. And this chapter will be doing just the same, ie,, take you to the revision tour of Python that you learnt in your previous class. COMPUTER SCIENCE WITH Pyruoyil 1.2. TOKENS IN PYTHON —_ . ‘The smallest individual unit in a pro} — q " rogram oP ora lexical unit. roan "" Python has following tokens ¢ ()Keyworts (i) Kdentifiers (Names) (iv) Operators gram is known asa Toker (iii) Literals (v) Punctuators 4A sample Python program for at_in range(1,,18) 4 punctuators if a2 i senodé a eas int (al. FSS te ‘identifiers: Figure 1.1 Some tokens in a Python program. Let us revise our understanding of tokens. 1.2.1 Keywords TERT : = Keywords are predefined words with special meaning to the ‘A keyword is a word language compiler or interpreter. These are reserved for special meaning reserved 6 special purpose and must not be used as normal identifier programming language. names. Python programming language contains the following keywords : False assert del for in or while None break lif from is pass with True class else global lambda raise yield and continue except if nonlocal return as def finally import not try 1.2.2 Identifiers (Names) Identifiers are the names given to different Junctions, lists, dictionaries and so forth, ‘The naming rules for Python identifiers can be © Variable names must only be NO spaces in between, © Variable names must numbers, Parts of the program viz, variables, objects, dass summarized as follows : a non-keyword word with be mad and underscore (_), © Variable names cannot begin wi egin with a nu; they can contain numbers mer eho ‘© Up of only letters, (Chapter 1: PYTHON REVISION TOUR 3 a The following are some ‘The following are some jrrvalid identifiers valid identifiers : DATA-REC contains special character - (hyphen) Myfile DATES_7_77, (other than A - Z,a- 2 and _ (underscore) ) MYFILE as 29cLcT Starting with a digit chk a break reserved keyword zarezs — _HOTB_IK My. file contains special character dot ( -) 1.2.3. Literals/Values Literals are data items that have a fixéd/constant value. Python allows several kinds of literals, which are being given below. (i) String Literals A string literal is a sequence of characters surrounded by quotes (single or double or triple quotes). String literals can either be single line strings or multi-line strings. © Single line strings must terminate in one line ie,, the closing quotes should be on the same line as that of the opening quotes. (See below) © Multiline strings are strings spread across multiple lines. With single and double quotes, each line other that the concluding line has an end character as \ (backslash) but with triple quotes, no backslash is needed at the end of intermediate lines. (see below) : >>> Texti = "Hello World" <——__ 2 Single line string Hello\ =—S— Multi-line string Text3="*'Hello#— World’ ** ‘No buckslash needed! Instrings, you can include non-graphic characters through escape sequences. Escape sequences are given in following table : | Escape What it does Escape What it does sequence. [Non-graphic character] ___|__ sequence [Non-graphic character] M Backslash (\) \r Carriage Return (CR) \ Single quote (’) \t Horizontal Tab (TAB) x Double quote (”) \woox Character with 16-bit hex value xxx (Unicode only) \a ASCII Bell (BEL) \Uxxxxxxxx | Character with 32-bit hex value sonxxx (Unicode only) \b ASCII Backspace (BS) \W ASCII Vertical Tab (VT) \f ASCII Formfeed (FF) \o00 Character with octal value 000 \n New line character \xhh Character with hex value hh \N{name} Character named name in the Unicode database (Unicode only) COMPUTER SCIENCE WITH PYTHON — 4 Numeric Literals Numeric literals are numeric val ten called just integers or ints, n be one of the following types : ues and these ca are positive or negative whole (a) int (signed integers) ofte numbers with no decimal point. i itten in : The integer literals can be wri — Lid we ‘© Decimal form : an integer beginning with digits 1-9. €8- lan iti cad © Octal form : an integer beginning with Oo (zero followed by letter 0) ¢.g., 0035, 0077 ete, ct : ‘ | Here do remember that for Octal, 8 and 9 are invalid digits. Hexadecimal form : an integer beginning with Ox (zero followed by letter X) e.g., 0x73, oar ate. Here remember that valid digits/etters for hexadecimal numbers are 0-9 and AF. (@ Floating Point Literals. Floating point literals or real literals floats represent real numbers and are written with a decimal point dividing the integer and fractional parts are numbers having fractional parts. These can be written in fractional form ¢.g., -13.0, .75, 7. ete. or in Exponent form e.g,, 0.17E5, 3.£2, .6E4 etc. (© Complex number literals are of the form a+bJ, where a and b are floats and J (or j) represents /-1, which is an imaginary number). a is the real part of the number, and b is the imaginary part. ) Boolean Literals A Boolean literal in Python is used to represent one of the two Boolean values i.e,, True (Boolean true) or False (Boolean false). A Boolean literal can either have value as True or as False. (iv) Special Literal None Python has one special literal, which is None. The None literal is used to indicate absence o value, Python can also store literal collections, in the form of tuples and lists ete. 1.2.4 Operators Operators are tokens that trigger s i ; t igger some comput: i i emanate ™mputation / action when applied to variables and other The operators can be arithmetic operators ( operators (<<, >>), identity operators (is, operators (and, or), assignment ope arithmetic-assignment operators (/=, =" 1, %,**, //), bitwise operator: i 5 %," I, (Se, *, 1), shift isnot), relational operators (>, e ><, ‘ I+), foie ts *) i ator ¢ » membership operators (in, not in), and 1.2.5. Punctuators Punctuators are s) ymbols that are used i sy in i Seucknes, and indicate the shythn and ummmee nn aie emphasis of ex is languages to organize sente! Pressions, statements, and prograil Most common punctuators of : ythor OTe ne PeIINE language are:

You might also like