Python for Programmers - Mercury Learning and Information - E-Book

Python for Programmers E-Book

Mercury Learning and Information

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book is designed for developers with little to no experience in Python or Pandas, providing a fast-paced introduction to Python programming and practical solutions to various tasks. The journey begins with a quick tour of basic Python 3, followed by a deep dive into loops and conditional logic. The text covers data structures extensively, and includes tasks involving strings and arrays.
As the reader progresses, object-oriented programming concepts are introduced with illustrative code samples, along with an exploration of recursion and fundamental topics in combinatorics. An appendix provides an introduction to Pandas, equipping readers with essential tools for data manipulation and analysis.
This book offers a comprehensive yet concise learning path, reinforced by numerous code samples and companion files available for download. It is an invaluable resource for beginners seeking to master Python and Pandas, providing a solid foundation for further exploration in programming and data science.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 278

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



PYTHONFORPROGRAMMERS

LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

By purchasing or using this book and companion files (the “Work”), you agree that this license grants permission to use the contents contained herein, including the disc, but does not give you the right of ownership to any of the textual content in the book / disc or ownership to any of the information or products contained in it. This license does not permit uploading of the Work onto the Internet or on a network (of any kind) without the written consent of the Publisher. Duplication or dissemination of any text, code, simulations, images, etc. contained herein is limited to and subject to licensing terms for the respective products, and permission must be obtained from the Publisher or the owner of the content, etc., in order to reproduce or network any portion of the textual material (in any media) that is contained in the Work.

MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and anyone involved in the creation, writing, or production of the companion disc, accompanying algorithms, code, or computer programs (“the software”), and any accompanying Web site or software of the Work, cannot and do not warrant the performance or results that might be obtained by using the contents of the Work. The author, developers, and the Publisher have used their best efforts to ensure the accuracy and functionality of the textual material and/or programs contained in this package; we, however, make no warranty of any kind, express or implied, regarding the performance of these contents or programs. The Work is sold “as is” without warranty (except for defective materials used in manufacturing the book or due to faulty workmanship).

The author, developers, and the publisher of any accompanying content, and anyone involved in the composition, production, and manufacturing of this work will not be liable for damages of any kind arising out of the use of (or the inability to use) the algorithms, source code, computer programs, or textual material contained in this publication. This includes, but is not limited to, loss of revenue or profit, or other incidental, physical, or consequential damages arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to replacement of the book and/or disc, and only at the discretion of the Publisher. The use of “implied warranty” and certain “exclusions” vary from state to state, and might not apply to the purchaser of this product.

Companion files for this title are available by writing to the publisher at [email protected].

PYTHONFORPROGRAMMERS

OSWALD CAMPESATO

MERCURY LEARNING AND INFORMATIONDulles, VirginiaBoston, MassachusettsNew Delhi

Copyright ©2022 by MERCURY LEARNINGAND INFORMATION LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scanning, without prior permission in writing from the publisher.

Publisher: David PallaiMERCURY LEARNINGAND INFORMATION22841 Quicksilver DriveDulles, VA [email protected]

O. Campesato. Python for Programmers.ISBN: 978-1-68392-817-1

The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property of others.

Library of Congress Control Number: 2022940434

222324321 This book is printed on acid-free paper in the United States of America.

Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc. For additional information, please contact the Customer Service Dept. at 800-232-0223(toll free).

All of our titles are available in digital format at academiccourseware.com and other digital vendors. Companion files (figures and code listings) for this title are available by contacting [email protected]. The sole obligation of MERCURY LEARNING AND INFORMATION to the purchaser is to replace the disc, based on defective materials or faulty workmanship, but not based on the operation or functionality of the product.

I’d like to dedicate this book to my parents – may this bring joy and happiness into their lives.

CONTENTS

Preface

Chapter 1: Introduction to Python

Tools for Python

Python Installation

Setting the PATH Environment Variable (Windows Only)

Launching Python on Your Machine

Python Identifiers

Lines, Indentation, and Multilines

Quotation and Comments in Python

Saving Your Code in a Module

Some Standard Modules in Python

The help() and dir() Functions

Compile Time and Runtime Code Checking

Simple Data Types in Python

Working With Numbers

Working With Fractions

Unicode and UTF-8

Working With Unicode

Working With Strings

Uninitialized Variables and the Value None in Python

Slicing and Splicing Strings

Search and Replace a String in Other Strings

Remove Leading and Trailing Characters

Printing Text Without NewLine Characters

Text Alignment

Working With Dates

Exception Handling in Python

Handling User Input

Command-Line Arguments

Summary

Chapter 2: Conditional Logic in Python

Precedence of Operators in Python

Python Reserved Words

Working With Loops in Python

Nested Loops

The split() Function With for Loops

Using the split() Function to Compare Words

Using the split() Function to Print Justified Text

Using the split() Function to Print Fixed Width Text

Using the split() Function to Compare Text Strings

Using the split() Function to Display Characters in a String

The join() Function

Python while Loops

Conditional Logic in Python

The break/continue/pass Statements

Comparison and Boolean Operators

Local and Global Variables

Scope of Variables

Pass by Reference versus Value

Arguments and Parameters

Using a while Loop to Find the Divisors of a Number

User-Defined Functions in Python

Specifying Default Values in a Function

Functions With a Variable Number of Arguments

Summary

Chapter 3: Data Structures in Python

Working With Lists

Sorting Lists of Numbers and Strings

Concatenating a List of Words

The Python range() Function

Lists and the append() Function

Working With Lists and the split() Function

Counting Words in a List

Iterating Through Pairs of Lists

List Slices

Other List-Related Functions

Working With Vectors

Working With Matrices

Queues

Tuples (Immutable Lists)

Sets

Dictionaries

Dictionary Functions and Methods

Ordered Dictionaries

Other Sequence Types in Python

Mutable and Immutable Types in Python

Packing/Unpacking Sequences

Lambda Expressions

Functional Programming in Python: The map() Function

Functional Programming in Python: The filter() Function

Summary

Chapter 4: Strings and Arrays

Time and Space Complexity

Task: Maximum and Minimum Powers of an Integer

Task: Binary Substrings of a Number

Task: Common Substring of Two Binary Numbers

Task: Multiply and Divide via Recursion

Task: Sum of Prime and Composite Numbers

Task: Count Word Frequencies

Task: Check if a String Contains Unique Characters

Task: Insert Characters in a String

Task: String Permutations

Task: Find All Subsets of a Set

Task: Check for Palindromes

Task: Check for Longest Palindrome

Working With Sequences of Strings

Task: Longest Sequences of Substrings

Working With 1D Arrays

Task: Invert Adjacent Array Elements

Working With 2D Arrays

The Transpose of a Matrix

Search Algorithms

Well-Known Sorting Algorithms

Merge Sort

Summary

Chapter 5: Built-In Functions and Custom Classes

A Python Module versus Package

Python Functions versus Methods

Functionally Oriented Programming in Python

Importing Custom Python Modules

How to Create Custom Classes

Construction and Initialization of Objects

Compiled Modules

Classes, Functions, and Methods in Python

Accessors and Mutators versus @property

Creating an Employee Custom Class

Working With a List of Employees

Working With Linked Lists in Python

Custom Classes and Linked Lists

Custom Classes and Dictionaries

Custom Classes and Priority Queues

Overloading Operators

Serialize and Deserialize Data

Encapsulation

Single Inheritance

A Concrete Example of Inheritance

Inheritance and Overriding Methods

Multiple Inheritance

Polymorphism

The Python abc Module

Summary

Chapter 6: Recursion and Combinatorics

What Is Recursion?

Arithmetic Series

Geometric Series

Factorial Values

Fibonacci Numbers

Task: Reverse an Array of Strings via Recursion

Task: Check for Balanced Parentheses

Task: Calculate the Number of Digits

Task: Determine if a Positive Integer is Prime

Task: Find the Prime Factorization of a Positive Integer

Task: Goldbach’s Conjecture

Task: Calculate the GCD (Greatest Common Divisor)

Task: Calculate the LCM (Lowest Common Multiple)

What Is Combinatorics?

Task: Calculate the Sum of Binomial Coefficients

The Number of Subsets of a Finite Set

Summary

Appendix: Introduction to Pandas

Index

PREFACE

WHAT IS THE PRIMARY VALUE PROPOSITION FOR THIS BOOK?

This book contains a fast-paced introduction to Python and Python-based solutions to various tasks. Some topics are presented in a high-level manner for two main reasons. First, it’s important that you be exposed to these concepts. In some cases you will find topics that might pique your interest, and hence motivate you to learn more about them through self-study; in other cases you will probably be satisfied with a brief introduction. In other words, you will decide whether or not to delve into more detail regarding the topics in this book.

Second, a full treatment of all the topics that are covered in this book would significantly increase the size of this book, and few people are interested in reading technical tomes.

THE TARGET AUDIENCE

This book is intended primarily for developers who have little or no experience with Python and are interested in learning about Python as well as an introduction to Pandas.

This book is also intended to reach an international audience of readers with highly diverse backgrounds in various age groups. While many readers know how to read English, their native spoken language is not English (which could be their second, third, or even fourth language). Consequently, this book uses standard English rather than colloquial expressions that might be confusing to those readers. As you know, many people learn by different types of imitation, which includes reading, writing, or hearing new material. This book takes these points into consideration in order to provide a comfortable and meaningful learning experience for the intended readers.

WHAT WILL I LEARN FROM THIS BOOK?

The first chapter contains a quick tour of basic Python3, followed by a chapter that shows you how to work with loops and conditional logic in Python. The third chapter discusses data structures in Python, followed by a chapter that contains code samples for tasks that involve strings and arrays in Python.

The fifth chapter contains fundamental concepts in OOP (object-oriented programming), along with code samples that illustrate how they are implemented in Python. The sixth chapter introduces you to recursion and some fundamental topics in combinatorics. Finally, the Appendix contains an introduction to Pandas.

GETTING THE MOST FROM THIS BOOK

Some programmers learn well from prose, others learn well from sample code (and lots of it), which means that there’s no single style that can be used for everyone.

Moreover, some programmers want to run the code first, see what it does, and then return to the code to delve into the details (and others use the opposite approach).

Consequently, there are various types of code samples in this book: some are short, some are long, and other code samples “build” from earlier code samples.

WHAT DO I NEED TO KNOW FOR THIS BOOK?

Current knowledge of Python 3.x is the most helpful skill. Knowledge of other programming languages (such as Java) can also be helpful because of the exposure to programming concepts and constructs. The less technical knowledge that you have, the more diligence will be required in order to understand the various topics that are covered.

If you want to be sure that you can grasp the material in this book, glance through some of the code samples to get an idea of how much is familiar to you and how much is new for you.

DON’T THE COMPANION FILES OBVIATE THE NEED FOR THIS BOOK?

The companion files contain all the code samples to save you time and effort from the error-prone process of manually typing code into a text file. In addition, there are situations in which you might not have easy access to the files. Furthermore, the code samples in the book provide explanations that are not available on the companion files.

DOES THIS BOOK CONTAIN PRODUCTION-LEVEL CODE SAMPLES?

The primary purpose of the code samples in this book is to show you Python-based libraries for solving a variety of data-related tasks in conjunction with acquiring a rudimentary understanding of statistical concepts. Clarity has higher priority than writing more compact code that is more difficult to understand (and possibly more prone to bugs). If you decide to use any of the code in this book in a production website, you ought to subject that code to the same rigorous analysis as the other parts of your code base.

WHAT ARE THE NON-TECHNICAL PREREQUISITES FOR THIS BOOK?

Although the answer to this question is more difficult to quantify, it’s very important to have strong desire to learn about Python, along with the motivation and discipline to read and understand the code samples.

HOW DO I SET UP A COMMAND SHELL?

If you are a Mac user, there are three ways to do so. The first method is to use Finder to navigate to Applications > Utilities and then double click on the Utilities application. Next, if you already have a command shell available, you can launch a new command shell by typing the following command:

open /Applications/Utilities/Terminal.app

A second method for Mac users is to open a new command shell on a MacBook from a command shell that is already visible simply by clicking command+n in that command shell, and your Mac will launch another command shell.

If you are a PC user, you can install Cygwin (open source https://cygwin.com/) that simulates bash commands, or use another toolkit such as MKS (a commercial product). Please read the online documentation that describes the download and installation process. Note that custom aliases are not automatically set if they are defined in a file other than the main start-up file (such as .bash_login).

COMPANION FILES

All the code samples and figures in this book may be obtained by writing to the publisher at [email protected].

WHAT ARE THE “NEXT STEPS” AFTER FINISHING THIS BOOK?

The answer to this question varies widely, mainly because the answer depends heavily on your objectives. If you are primarily interested in machine learning, there are some subfields of machine learning, such as deep learning and reinforcement learning (and deep reinforcement learning) that might appeal to you. Fortunately, there are many resources available, and you can perform an Internet search for those resources. One other point: the aspects of machine learning for you to learn depend on who you are: the needs of a machine learning engineer, data scientist, manager, student or software developer are all different.

CHAPTER 1

INTRODUCTION TO PYTHON

This chapter contains an introduction to Python, with information about useful tools for installing Python modules, basic Python constructs, and how to work with some data types in Python.

The first part of this chapter covers how to install Python, some Python environment variables, and how to use the Python interpreter. You will see Python code samples and also how to save Python code in text files that you can launch from the command line. The second part of this chapter shows you how to work with simple data types, such as numbers, fractions, and strings. The final part of this chapter discusses exceptions and how to use them in Python scripts.

NOTE

The Python scripts in this book are for Python 3.

TOOLS FOR PYTHON

The Anaconda Python distribution available for Windows, Linux, and Mac is downloadable here:

http://continuum.io/downloads

Anaconda is well-suited for libraries such as NumPy (discussed in Chapter 3) and SciPy (not discussed in this book). Also, if you are a Windows user, Anaconda appears to be a better alternative.

easy_install and pip

Both easy_install and pip are very easy to use when you need to install Python modules. Whenever you need to install a Python module (and there are many in this book), use either easy_install or pip with the following syntax:

easy_install <module-name>

pip install <module-name>

NOTE

Python-based modules are easier to install, whereas modules with code written in C are usually faster but more difficult in terms of installation.

virtualenv

The virtualenv tool enables you to create isolated Python environments, and its home page is here:

http://www.virtualenv.org/en/latest/virtualenv.html

virtualenv addresses the problem of preserving the correct dependencies and versions (and indirectly permissions) for different applications. If you are a Python novice you might not need virtualenv right now, but keep this tool in mind.

IPython

Another very good tool is IPython (which won a Jolt award), and its home page is here:

http://ipython.org/install.html

Type ipython to invoke IPython from the command line:

ipython

The preceding command displays the following output:

Python 3.9.13 (main, May 24 2022, 21:28:12)

Type 'copyright', 'credits' or 'license' for more information

IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

Type a question mark (“?”) at the prompt and you will see some useful information, a portion of which is here:

IPython -- An enhanced Interactive Python

IPython offers a fully compatible replacement for the standard Python interpreter, with convenient shell features, special commands, command history mechanism and output results caching.

At your system command line, type 'ipython -h' to see the command line options available. This document only describes interactive features.

GETTING HELP

------------

Within IPython you have various way to access help:

  ?         -> Introduction and overview of IPython's features (this screen).

  object?   -> Details about 'object'.

  object??  -> More detailed, verbose information about 'object'.

  %quickref -> Quick reference of all IPython specific syntax and magics.

  help      -> Access Python's own help system.

If you are in terminal IPython you can quit this screen by pressing `q`.

Finally, simply type quit() at the command prompt and you will exit the ipython shell.

The next section shows you how to check whether or not Python is installed on your machine, and also where you can download Python.

PYTHON INSTALLATION

Before you download anything, check if you have Python already installed on your machine (which is likely if you have a Macbook or a Linux machine) by typing the following command in a command shell:

python -V

The output for the Macbook used in this book is here:

Python 3.9.1

NOTE

Install Python 3.9.13 (or as close as possible to this version) on your machine so that you will have the same version of Python that was used to test the Python scripts in this book.

If you need to install Python on your machine, navigate to the Python home page and select the downloads link or navigate directly to this website:

http://www.python.org/download/

In addition, PythonWin is available for Windows, and its home page is here:

http://www.cgl.ucsf.edu/Outreach/pc204/pythonwin.html

Use any text editor that can create, edit, and save Python scripts and save them as plain text files (don’t use Microsoft Word).

After you have Python installed and configured on your machine, you are ready to work with the Python scripts in this book.

SETTING THE PATH ENVIRONMENT VARIABLE (WINDOWS ONLY)

The PATH environment variable specifies a list of directories that are searched whenever you specify an executable program from the command line. A good guide to setting up your environment so that the Python executable is always available in every command shell is to follow the instructions here:

http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/

LAUNCHING PYTHON ON YOUR MACHINE

There are three different ways to launch Python:

•Use the Python Interactive Interpreter

•Launch Python scripts from the command line

•Use an IDE

The next section shows you how to launch the Python interpreter from the command line, and later in this chapter you will learn how to launch Python scripts from the command line and also about Python IDEs.

NOTE

The emphasis in this book is to launch Python scripts from the command line or to enter code in the Python interpreter.

The Python Interactive Interpreter

PYTHON IDENTIFIERS

A Python identifier is the name of a variable, function, class, module, or other Python object, and a valid identifier conforms to the following rules:

•It starts with a letter A to Z, a to z, or an underscore (_)

•It includes zero or more letters, underscores, and digits (0 to 9)

NOTE

Python identifiers cannot contain characters such as @, $, and %.

Python is a case-sensitive language, so Abc and abc different identifiers in Python.

In addition, Python has the following naming convention:

•Class names start with an uppercase letter and all other identifiers with a lowercase letter

•An initial underscore is used for private identifiers

•Two initial underscores are used for strongly private identifiers

A Python identifier with two initial underscore and two trailing underscore characters indicates a language-defined special name.

LINES, INDENTATION, AND MULTILINES

QUOTATION AND COMMENTS IN PYTHON

SAVING YOUR CODE IN A MODULE

SOME STANDARD MODULES IN PYTHON

The Python Standard Library provides many modules that can simplify your own Python scripts. A list of the Standard Library modules is here:

http://www.python.org/doc/

Some of the most important Python modules include cgi, math, os, pickle, random, re, socket, sys, time, and urllib.

The code samples in this book use the modules math, os, random, re, socket, sys, time, and urllib. You need to import these modules in order to use them in your code. For example, the following code block shows you how to import four standard Python modules:

import datetime

import re

import sys

import time

The code samples in this book import one or more of the preceding modules, as well as other Python modules.

THE HELP() AND DIR() FUNCTIONS

An internet search for Python-related topics usually returns a number of links with useful information. Alternatively, you can check the official Python documentation site: docs.python.org

In addition, Python provides the help() and dir() functions that are accessible from the Python interpreter. The help() function displays documentation strings, whereas the dir() function displays defined symbols.

For example, if you type help(sys) you will see documentation for the sys module, whereas dir(sys) displays a list of the defined symbols.

Type the following command in the Python interpreter to display the string-related methods in Python:

>>> dir(str)

The preceding command generates the following output:

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

The preceding list gives you a consolidated “dump” of built-in functions (including some that are discussed later in this chapter). Although the max() function obviously returns the maximum value of its arguments, the purpose of other functions such as filter() or map() is not immediately apparent (unless you have used them in other programming languages). In any case, the preceding list provides a starting point for finding out more about various Python built-in functions that are not discussed in this chapter.

Although dir() does not list the names of built-in functions and variables, you can obtain this information from the standard module __builtin__ that is automatically imported under the name __builtins__:

>>> dir(__builtins__)

The following command shows you how to get more information about a function:

help(str.lower)

The output from the preceding command is here:

Help on method_descriptor:

lower(...)

    S.lower() -> string

    

    Return a copy of the string S converted to lowercase.

(END)

Check the online documentation and also experiment with help() and dir() when you need additional information about a particular function or module.

COMPILE TIME AND RUNTIME CODE CHECKING

SIMPLE DATA TYPES IN PYTHON

Python supports primitive data types, such as numbers (integers, floating point numbers, and exponential numbers), strings, and dates. Python also supports more complex data types, such as lists (or arrays), tuples, and dictionaries. The next several sections discuss some of the Python primitive data types, along with code snippets that show you how to perform various operations on those data types.

WORKING WITH NUMBERS

Working With Other Bases

The chr() Function

The round() Function in Python

The Pythonround() function enables you to round decimal values to the nearest precision:

>>> round(1.23, 1)

1.2

>>> round(-3.42,1)

-3.4

Formatting Numbers in Python