Share E-Book

AuthorSufyan bin Uzayr

Python definitely tops the charts when it comes to ease of use and beginner-friendly learning curve in the world of programming languages. At the same time, Python is essential when it comes to writing system scripts, processing big data, performing mathematical computations, creating web applications, and rapid prototyping. With thisMasteringedition, we have focused especially on the usage of Python for Web. This book explores Python programming fundamentals with interactive projects, introduces core coding concepts and the basics of Python-based web development. The reader should be ready to dive deep into the world of Python for web development in no time. Since Python positions itself in web development as a back-end language, it is usually mixed with another front-end language to build a whole website. At the same time, reasons for using Python in web development are many: it is a flexible, versatile, and highly efficient programming language with dynamic typing capacity. This book helps readers to examine Python key back-end/front-end programming techniques and guides them through implementing them when creating professional projects. Furthermore, it also focuses on teaching readers how to solve common problems and developing web services with Python frameworks such as Django and Flask. Mastering Python for Web has a goal more ambitious than simply teaching you the ropes – it aims to help you embrace and master problem solving, which could be seen as the single most crucial skill for a coder. It offers you a focal point on starting as a beginner and growing into an expert by putting your newly acquired knowledge into practice. Programming is a hands-on skill, and this particular book helps you put your skills to test with easy to grasp tasks and examples. Learn more about our other Mastering titles at ........

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

Tags
AI categories
programming languageweb technologyeducation
ISBN: 1032135670
Publisher: CRC Press
Publish Year: 2022
Language: English
Pages: 303
File Format: PDF
File Size: 5.4 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Mastering Python for Web
For more information about this series, please visit: https:// www.routledge.com/Mastering-Computer-Science/ book-series/MCS The “Mastering Computer Science” series of books are authored by the Zeba Academy team members, led by Sufyan bin Uzayr. Zeba Academy is an EdTech venture that develops courses and content for learners primarily in STEM fields, and offers education consulting to Universities and Institutions worldwide. For more info, please visit https:// zeba.academy Mastering Computer Science Series Editor: Sufyan bin Uzayr Mastering Python for Web: A Beginner’s Guide Mathew Rooney and Madina Karybzhanova Mastering Android Studio: A Beginner’s Guide Divya Sachdeva and Reza Nafim Mastering Swift: A Beginner’s Guide Mathew Rooney and Madina Karybzhanova Mastering C++: A Beginner’s Guide Divya Sachdeva and Natalya Ustukpayeva Mastering Git: A Beginner’s Guide Sumanna Kaul, Shahryar Raz, and Divya Sachdeva Mastering Ruby on Rails: A Beginner’s Guide Mathew Rooney and Madina Karybzhanova
Mastering Python for Web A Beginner’s Guide Edited by Sufyan bin Uzayr
First edition published 2022 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2022 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www. copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf.co.uk Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. ISBN: 9781032135670 (hbk) ISBN: 9781032135656 (pbk) ISBN: 9781003229896 (ebk) DOI: 10.1201/9781003229896 Typeset in Minion by KnowledgeWorks Global Ltd.
v Contents About the Editor, xiii Chapter 1 ◾ Introduction to Python 1 PYTHON 2 VS. PYTHON 3 3 A BRIEF HISTORY OF PYTHON 11 INSTALLING AND CONFIGURING PYTHON 16 HOW TO INSTALL PYTHON ON WINDOWS 19 How to Install from the Microsoft Store 22 How to Install from the Full Installer 24 HOW TO INSTALL PYTHON ON macOS 25 How to Install from the Official Installer 28 How to Install from Homebrew 29 HOW TO INSTALL PYTHON ON LINUX 31 How to Install on Ubuntu and Linux Mint 33 How to Install on Debian Linux 34 How to Install on openSUSE 34 How to Install on CentOS and Fedora 35 How to Install on Arch Linux 35
vi ◾ Contents HOW TO BUILD PYTHON FROM SOURCE CODE 36 HOW TO INSTALL PYTHON ON iOS 39 HOW TO INSTALL PYTHON ON ANDROID 40 ONLINE PYTHON INTERPRETERS 40 REGENERATE CONFIGURE 41 Chapter 2 ◾ Python Data Type 43 Additional Methods on Integer Types 46 STRING DATA TYPE 54 SET DATA TYPE 62 Operators and Methods 62 Modifying a Set 64 NUMBERS DATA TYPE 65 Integers 67 Floating Point Numbers 67 Complex Numbers 68 Number Type Conversion 69 LIST DATA TYPE 72 Accessing Values in Lists 74 Updating Lists 74 Delete List Elements 75 Basic List Operations 76 Built-In List Functions and Methods 76 DICTIONARY DATA TYPE 77 Creating a Dictionary 78
Contents ◾ vii Accessing Values in Dictionary 78 Updating Dictionary 79 Delete Dictionary Elements 79 Properties of Dictionary Keys 80 Built-in Dictionary Functions & Methods 80 Tuple Data Type 82 Accessing Values in Tuples 83 Updating Tuples 84 Delete Tuple Elements 84 Basic Tuples Operations 85 Built-in Tuple Functions 85 Chapter 3 ◾ Python Comments and Documentation 89 SINGLE LINE, INLINE, AND MULTILINE COMMENTS 91 HOW PYTHON MULTILINE COMMENT WORKS? 94 Block Comments 95 Shebang 96 PYTHON COMMENTING BEST PRACTICES 97 When Writing Code for Yourself 97 When Writing Code for Others 99 PYTHON COMMENTING WORST PRACTICES 100 HOW TO PRACTICE COMMENTING? 104
viii ◾ Contents PROGRAMMATICALLY ACCESSING DOCSTRINGS 106 Single-Line Docstrings 106 Multi-line Docstrings 107 Docstring Formats 108 WRITE DOCUMENTATION VIA DOCSTRINGS 113 Paragraphs 115 Inline Markup 115 Sections 115 Meta-information Markup 116 Information Units 117 Inline Markup 122 Chapter 4 ◾ Programs, Algorithms, and Functions 133 PYTHON SCRIPTS AND MODULES 135 What’s the Python Interpreter? 135 Using the Python Command 137 Using the Script Filename 138 How to Run Python Scripts Interactively 139 How to Run Python Scripts from an IDE or a Text Editor 140 How to Run Python Scripts from a File Manager 141 Joining Two Strings 142 Format Floating Point in the String 142
Contents ◾ ix Raise a Number To a Power 143 Working with Boolean Types 144 Use of If-Else Statement 145 Use of AND and OR Operators 146 Locating Modules 148 Standard Modules 148 Python Packages 149 PYTHON ALGORITHMS 151 How Do You Write Algorithms? 151 Characteristics of an Algorithm 153 Brute Force 154 Divide and Conquer 155 Tree Traversal Algorithms 155 Sorting Algorithms 157 Searching Algorithms 159 Algorithm Analysis 161 BASIC FUNCTIONS 161 DYNAMIC PROGRAMMING 165 Recursive Method 168 Top-Down Method 169 Bottom Down 169 LAMBDA FUNCTIONS 170 Syntax 174 Decorators 175
x ◾ Contents Chapter 5 ◾ Python’s Executional Model 179 NAMES AND NAMESPACES 181 SCOPES 186 Using the LEGB Rule 189 Functions: The Local Scope 191 Nested Functions: The Enclosing Scope 191 Modules: The Global Scope 191 Built-In Scope 195 MODIFYING THE BEHAVIOR OF A PYTHON SCOPE 196 The Global Statement 196 The Nonlocal Statement 197 Using Enclosing Scopes as Closures 199 Bringing Names to Scope with Import 200 Reviewing Unusual Python Scopes 201 Comprehension Variables Scope 201 Exception Variables Scope 202 Class and Instance Attributes Scope 202 Using Scope-Related Built-In Functions 204 OBJECTS AND CLASSES 208 Class Objects 210 Method Objects 212 Inheritance 213
Contents ◾ xi Chapter 6 ◾ Python for Web Development 217 THE BASIC CONCEPTS AROUND WEB PROGRAMMING 220 THE DJANGO FRAMEWORK 227 Is Django Opinionated? 231 What Does Django Code Look Like? 232 Handling the Request (views.py) 234 Defining Data Models (models.py) 235 Rendering Data (HTML Templates) 236 REGULAR EXPRESSIONS 240 Regular Expression Objects 256 FLASK AND FALCON FRAMEWORKS 258 APPRAISAL, 267 INDEX, 277
(This page has no text content)
xiii About the Editor Sufyan bin Uzayr is a writer, coder, and entrepreneur with more than a decade of experience in the industry. He has authored several books in the past, pertaining to a diverse range of topics, ranging from History to Computers/IT. Sufyan is the Director of Parakozm, a multinational IT company specializing in EdTech solutions. He also runs Zeba Academy, an online learning and teaching vertical with a focus on STEM fields. Sufyan specializes in a wide variety of technologies, such as JavaScript, Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees, including ones in man- agement, IT, literature, and political science. Sufyan is a digital nomad, dividing his time between four countries. He has lived and taught in universities and educational institutions around the globe. Sufyan takes a keen interest in technology, politics, literature, history, and sports, and in his spare time, he enjoys teaching coding and English to young students. Learn more at sufyanism.com.
(This page has no text content)
1DOI: 10.1201/9781003229896-1 C h a p t e r 1 Introduction to Python IN THIS CHAPTER ➢ Introducing Python coding language ➢ Diving into the story of Python creation ➢ Explaining how to install and configure Python Python is a general-purpose coding language that is used for other types of programming and software development. It is considered a great force in web application creation and systems management and a key driver of the explosion in big data analytics and machine intelligence. To put simply, Python is generally utilized for things like: • Writing system scripts • Processing big data
2 ◾ Mastering Python for Web • Performing mathematical computations • Connecting to database systems • Reading and modifying files • Python can be used on Creating web applications on a server • Creating workflows • Rapid prototyping • Production-ready software development • Back-end web and mobile app development However, the most typical use case for Python is as a scripting and automation language. When creating scripts, Python is not considered a replacement for shell scripts or batch files but is used to automate interactions with web browsers or application graphical user interfaces (GUI). Thus, with Python, you can create both command-line and cross-platform GUI applications and deploy them as self- contained executables. Sophisticated data analysis has become one of the most flourishing areas of IT, and the majority of popular software and data science libraries used for machine learning have
Introduction to Python ◾ 3 Python interfaces, making it the most popular high-level command interface and numerical algorithms. Python’s third-party web frameworks provide fast and convenient ways to create everything from simple lines of code to full- functioning, data-driven sites. Python’s latest versions have strong support for operations, enabling sites to handle tens of thousands of requests per second. Python also works as a highly efficient code generator, making it possible to write applications that manipulate their own functions that would be difficult to implement in other languages. This coding is often described as a “glue language,” meaning it can make disparate code interoperable again. Thus, if you have applications or program domains that you would like to link with each other, you can use Python for this task. PYTHON 2 VS. PYTHON 3 Python is available in two different versions: Python 2 and Python 3. Python 2, the older branch, as of January 1, 2020, is no longer supported by its creators, the Python Software Foundation. Python 3, the current and future version of the language, has many updated features that were not included in Python 2, such as new concurrency controls, and a better interpreter. There used to be a lot of compe- tition between the two, but since version 3 incorporated few important functions, it has won over all the Python fan base. Few of those changes in Python 3 included:1 • Text vs. Data instead of Unicode vs. 8-bit. • Print is now a function. 1 https://learntowish.com/history-python-comedy-snake-programming- language/, Learntowish blog
4 ◾ Mastering Python for Web • Views and iterators instead of lists. • The rules for ordering comparisons have been sim- plified. So, a heterogeneous list cannot be sorted, because all the elements of a list must be comparable to each other. At first, Python 3 approval was slowed for some time due to a lack of third-party library support. Because most Python libraries supported only Python 2, it made the transaction to version 3 time consuming. But over the last couple of years, the number of libraries compatible with both Python 2 and Python 3 has increased. Today, Python 3 is the best, up-to-date choice for new projects. Due to its simplicity, top technology organizations like Dropbox, Google, Mozilla, Hewlett-Packard, IBM, and Cisco have implemented Python for various purposes such as developing, scripting, generation, and software test- ing. It has also been an inspiration for many other cod- ing languages such as Ruby, Cobra, Boo, CoffeeScript ECMAScript, Groovy, Swift Go, OCaml, and Julia. The success of Python rests on a strong standard library and a generous assortment of easily obtained and readily used libraries from third-party developers. Python’s stan- dard library provides modules for common programming tasks like math, string handling, file and directory access, networking, asynchronous operations, threading, and multi-process management. Additionally, it also includes modules that manage common programming tasks such as reading and writing structured file formats, manipulating compressed files, and working with internet protocols. The default Python distribution also provides a cross-platform
Introduction to Python ◾ 5 GUI library via Tkinter and an embedded access to the SQLite 3 database. There are thousands of third-party libraries available through the Python Package Index. For example: • The BeautifulSoup library provides an all-in-one toolbox for extracting HTML. • Frameworks like Flask and Django allow rapid devel- opment of web services. • Multiple cloud services can be managed through Python’s model using Apache Libcloud. • Pandas, NumPy and Matplotlib accelerate math and statistical operations, as well as create visualizations of data. With that said, it is also worth noting the tasks Python is not well suited for. To start with, Python is a high-level language, so it is not the best option for system-level pro- gramming—device drivers or OS kernels are inadmissible. It’s also not ideal for situations that call for cross-platform standalone binaries. And since everything in the language, including functions and modules themselves, are handled as objects coding comes at the expense of speed. Therefore, it is not the best choice when speed is an absolute prior- ity in every aspect of the application. For that, it is recom- mended to opt for C/C++ or another language. Like C#, Java, and Go, Python has garbage-collected memory management, meaning there is no need to implement code to track objects. Garbage collection hap- pens automatically in the background and can pose a