Google gemini for python: coding with bard oswald campesato book PDF download complete version

Page 1


Google Gemini for Python: Coding with BARD Oswald Campesato

Visit to download the full and correct content document: https://textbookfull.com/product/google-gemini-for-python-coding-with-bard-oswald-ca mpesato/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Python Programming For Beginners: Python Mastery in 7 Days: Top-Secret Coding Tips with Hands-On Exercises for Your Dream Job 1st Edition Oswald Thornton

https://textbookfull.com/product/python-programming-forbeginners-python-mastery-in-7-days-top-secret-coding-tips-withhands-on-exercises-for-your-dream-job-1st-edition-oswaldthornton/

The Python Book: The Ultimate Guide to Coding with Python Imagine Publishing

https://textbookfull.com/product/the-python-book-the-ultimateguide-to-coding-with-python-imagine-publishing/

Good Habits for Great Coding: Improving Programming Skills with Examples in Python Michael Stueben

https://textbookfull.com/product/good-habits-for-great-codingimproving-programming-skills-with-examples-in-python-michaelstueben/

Good Habits for Great Coding: Improving Programming Skills with Examples in Python 1st Edition Michael Stueben

https://textbookfull.com/product/good-habits-for-great-codingimproving-programming-skills-with-examples-in-python-1st-editionmichael-stueben/

Learn Python Visually Creative Coding with Processing py 1st Edition Tristan Bunn

https://textbookfull.com/product/learn-python-visually-creativecoding-with-processing-py-1st-edition-tristan-bunn/

Coding for Kids Python Learn to Code with 50 Awesome Games and Activities 2019th Edition Adrienne B. Tacke

https://textbookfull.com/product/coding-for-kids-python-learn-tocode-with-50-awesome-games-and-activities-2019th-editionadrienne-b-tacke/

Coding with AI For Dummies Chris Minnick

https://textbookfull.com/product/coding-with-ai-for-dummieschris-minnick/

Coding Games in Python 1st Edition Carol Vorderman

https://textbookfull.com/product/coding-games-in-python-1stedition-carol-vorderman/

Practical Python AI Projects: Mathematical Models of Optimization Problems with Google OR-Tools 1st Edition Serge Kruk

https://textbookfull.com/product/practical-python-ai-projectsmathematical-models-of-optimization-problems-with-google-ortools-1st-edition-serge-kruk/

GOOGLE GEMINI FOR PYTHON

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” varies 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 info@merclearning.com.

GOOGLE GEMINI FOR PYTHON

Coding with Bard

Oswald Campesato

MERCURY LEARNING AND INFORMATION

Boston, Massachusetts

Copyright ©2024 by MERCURY LEARNING AND INFORMATION. An Imprint of DeGruyter Inc. 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 Pallai

MERCURY LEARNING AND INFORMATION

121 High Street, 3rd Floor Boston, MA 02110 info@merclearning.com www.merclearning.com 800-232-0223

O. Campesato. Google® Gemini for Python: Coding with Bard. ISBN: 978-1-50152-274-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: 2024930869 242526321 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 info@merclearning.com. The sole obligation of MERCURY LEARNING AND INFORMATION to the purchaser is to replace the files, 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 3

Tools for Python

easy_install and pip

virtualenv

IPython

Python Installation

Setting the PATH Environment Variable (Windows Only)

Launching Python on Your Machine

The Python Interactive Interpreter

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 Other Bases

The chr() Function

The round() Function in Python

Formatting Numbers in Python

Working With Fractions

Unicode and UTF-8

Working With Unicode

Working With Strings

Comparing Strings

Formatting Strings in Python

Slicing and Splicing Strings

Testing for Digits and Alphabetic Characters

Search and Replace a String in Other Strings

Remove Leading and Trailing Characters

Printing Text without NewLine Characters

Text Alignment

Working With Dates

Converting Strings to Dates

Exception Handling in Python

Handling User Input

Command-Line Arguments

Summary

Chapter 2: Conditional Logic, Loops, and Functions

Precedence of Operators in Python

Python Reserved Words

Working with Loops in Python

Python for Loops

A for Loop with try/except in Python

Numeric Exponents 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

The in/not in/is/is not Comparison Operators

The and, or, and not Boolean Operators

Local and Global Variables

Uninitialized Variables and the Value None

Scope of Variables

Pass by Reference Versus Value

Arguments and Parameters

Using a while loop to Find the Divisors of a Number

Using a while loop to Find Prime Numbers

User-Defined Functions in Python

Specifying Default Values in a Function

Returning Multiple Values From a Function

Functions With a Variable Number of Arguments

Lambda Expressions

Recursion

Calculating Factorial Values

Calculating Fibonacci Numbers

Calculating the GCD of Two Numbers

Calculating the LCM of Two Numbers

Summary

Chapter 3: Python Data Structures

Working with Lists

Lists and Basic Operations

Reversing and Sorting a List

Lists and Arithmetic Operations

Lists and Filter-Related Operations

Sorting Lists of Numbers and Strings

Expressions in Lists

Concatenating a List of Words

The Bubble Sort in Python

The Python range() Function

Counting Digits and Uppercase and Lowercase Letters

Arrays and the append() Function

Working with Lists and the split() Function

Counting Words in a List

Iterating Through Pairs of Lists

Other List-Related Functions

Using a List as a Stack and a Queue

Working with Vectors

Working with Matrices

The NumPy Library for Matrices

Queues

Tuples (Immutable Lists)

Sets

Dictionaries

Creating a Dictionary

Displaying the Contents of a Dictionary

Checking for Keys in a Dictionary

Deleting Keys from a Dictionary

Iterating Through a Dictionary

Interpolating Data from a Dictionary

Dictionary Functions and Methods

Dictionary Formatting

Ordered Dictionaries

Sorting Dictionaries

Python Multi Dictionaries

Other Sequence Types in Python

Mutable and Immutable Types in Python

The type() Function

Working with Bard

Counting Digits and Uppercase and Lowercase Letters

Bard Python Code for a Queue

Bard Python Code for a Stack

Summary

Chapter 4: Introduction to NumPy and Pandas

What is NumPy?

Useful NumPy Features

What are NumPy arrays?

Working with Loops

Appending Elements to Arrays (1)

Appending Elements to Arrays (2)

Multiply Lists and Arrays

Doubling the Elements in a List

Lists and Exponents

Arrays and Exponents

Math Operations and Arrays

Working with “-1” Subranges with Vectors

Working with “–1” Subranges with Arrays

Other Useful NumPy Methods

Arrays and Vector Operations

NumPy and Dot Products (1)

NumPy and Dot Products (2)

NumPy and the “Norm” of Vectors

NumPy and Other Operations

NumPy and the reshape() Method

Calculating the Mean and Standard Deviation

Calculating Quartiles With Numpy

What is Pandas?

Pandas Data Frames

DataFrames and Data Cleaning Tasks

A Labeled Pandas DataFrame

Pandas Numeric DataFrames

Pandas Boolean DataFrames

Transposing a Pandas DataFrame

Pandas DataFrames and Random Numbers

Combining Pandas DataFrames (1)

Combining Pandas DataFrames (2)

Data Manipulation with Pandas DataFrames (1)

Data Manipulation with Pandas DataFrames (2)

Data Manipulation with Pandas DataFrames (3)

Pandas DataFrames and CSV Files

Pandas DataFrames and Excel Spreadsheets

Select, Add, and Delete Columns in DataFrames

Pandas DataFrames and Scatterplots

Pandas DataFrames and Simple Statistics

Useful One-Line Commands in Pandas

Working with Bard

A Pandas DataFrame with Random Values

Pandas DataFrame and a Bar Chart

Pandas DataFrames and Statistics

Summary

Chapter 5: Generative AI, Bard, and Gemini

What is Generative AI?

Key Features of Generative AI

Popular Techniques in Generative AI

What Makes Generative AI Unique

Conversational AI Versus Generative AI

Primary Objective

Applications

Technologies Used

Training and Interaction

Evaluation

Data Requirements Is Gemini Part of Generative AI?

DeepMind

DeepMind and Games

Player of Games (PoG)

OpenAI

Cohere

Hugging Face

Hugging Face Libraries

Hugging Face Model Hub

AI21

InflectionAI

Anthropic

What is Prompt Engineering?

Prompts and Completions

Types of Prompts

Instruction Prompts

Reverse Prompts

System Prompts Versus Agent Prompts

Prompt Templates

Poorly-Worded Prompts

What is Gemini?

Gemini Ultra Versus GPT-4

Gemini Strengths

Gemini’s Weaknesses

Gemini Nano on Mobile Devices

What is Bard?

Sample Queries and Responses from Bard

Alternatives to Bard

YouChat

Pi from Inflection

CoPilot (OpenAI/Microsoft)

Codex (OpenAI)

Apple GPT

Claude 2

Summary

Chapter 6: Bard and Python Code

CSV Files for Bard

Simple Web Scraping

Basic Chatbot

Basic Data Visualization

Basic Pandas

Generating Random Data

Recursion: Fibonacci Numbers

Generating a Python Class

Asynchronous Programming

Working with Requests in Python

Image Processing with PIL

Exception Handling

Generators in Python

Roll 7 or 11 with Two Dice

Roll 7 or 11 with Three Dice

Roll 7 or 11 with Four Dice

Mean and Standard Deviation

Summary

Index

PREFACE

This book starts with an introduction to fundamental aspects of Python programming, which include various data types, number formatting, Unicode and UTF-8 handling, and text manipulation techniques. In addition. you will learn about loops, conditional logic, and reserved words in Python. You will also see how to handle user input, manage exceptions, and work with command-line arguments.

Next, the text transitions to the realm of Generative AI, discussing its distinction from Conversational AI. Popular platforms and models, including Bard and its competitors, are presented to give readers an understanding of the current AI landscape. The book also sheds light on the capabilities of Bard, its strengths, weaknesses, and potential applications. In addition, you will learn how to generate a variety of Python 3 code samples via Bard.

In essence, this book provides a modest bridge between the worlds of Python programming and AI, aiming to equip readers with the knowledge and skills to navigate both domains confidently.

THE TARGET AUDIENCE

This book is intended primarily for people who want to learn both Python and how to use Bard with Python. This book is also intended to reach an international audience of readers with highly diverse backgrounds in various age groups. In addition, this book uses standard English rather than colloquial expressions that might be confusing to those readers. This book provides a comfortable and meaningful learning experience for the intended readers.

DO I NEED TO LEARN THE THEORY PORTIONS OF THIS BOOK?

The answer depends on the extent to which you plan to become involved in working with Bard and Python, perhaps involving LLMs and generative AI. In general, it’s probably worthwhile to learn the more theoretical aspects of LLMs that are discussed in this book.

WHAT DO I NEED TO KNOW FOR THIS BOOK?

Although this book is introductory in nature, some knowledge of Python 3.x with certainly be helpful for the code samples. Knowledge of other programming languages (such as Java) can also be helpful because of the exposure to programming concepts and constructs.

DOES THIS BOOK CONTAIN PRODUCTION-LEVEL CODE SAMPLES?

This book contains basic code samples that are written in Python, and their primary purpose is to familiarize you with basic Python to help you understand the Python code generated via Bard. Moreover, 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, you ought to subject that code to the same rigorous analysis as the other parts of your code base.

COMPANION FILES

All the code samples and figures in this book may be obtained by writing to the publisher at info@merclearning.com.

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 will depend on your career: the needs of a machine

learning engineer, data scientist, manager, student, or software developer are all different.

January 2024

Oswald Campesato

INTRODUCTION TO PYTHON 3

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 files in this book are for Python 3.x.

TOOLS FOR PYTHON

The Anaconda Python distribution is available for Windows, Linux, and Mac, and it’s downloadable here: http://continuum.io/downloads

Anaconda is well-suited for modules such as numpy and scipy, and if you are a Windows user, Anaconda appears to be a better alternative than working from the command line.

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 than modules with code written in C because they are usually faster. However, they are 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

Two very nice features of IPython are tab expansion and “?,” and an example of tab expansion is shown here:

$ ipython3

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

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

IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help. In [1]:

In [1]: di

%dirs dict dir divmod

In the preceding session, if you type the characters di, iPython responds with the following line that contains all the functions that start with the letters di:

%dirs dict dir divmod

If you enter a question mark (“?”), ipython provides textual assistance, the first part of which is here:

IPython -- An enhanced Interactive Python

IPython offers a combination of convenient shell features, special commands and a history mechanism for both input (command history) and output (results caching, similar to Mathematica). It is intended to be a fully compatible replacement for the standard Python interpreter, while offering vastly improved functionality and flexibility.

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 already have Python 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 (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 files 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 very 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-uppython-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 files from the command line or to enter code in the Python interpreter.

The Python Interactive Interpreter

Launch the Python interactive interpreter from the command line by opening a command shell and typing the following command:

python

You will see the following prompt (or something similar):

Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec 7 2020, 12:44:01)

[Clang 12.0.0 (clang-1200.0.32.27)] on darwin Type "help", "copyright", "credits" or "license" for more information.

>>>

Now type the expression 2 + 7 at the prompt:

>>> 2 + 7

Python displays the following result: 9

>>>

Press ctrl-d to exit the Python shell.

You can launch any Python script from the command line by preceding it with the word “python.” For example, if you have a Python script myscript.py that contains Python commands, launch the script as follows:

python myscript.py

As a simple illustration, suppose that the Python script myscript.py contains the following Python code:

print('Hello World from Python') print('2 + 7 = ', 2+7)

When you launch the preceding Python script, you will see the following output:

Hello World from Python 2 + 7 = 9

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 or 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

Unlike other programming languages (such as Java or Objective-C), Python uses indentation instead of curly braces for code blocks. Indentation must be consistent in a code block, as shown here: if True: print("ABC") print("DEF") else: print("ABC") print("DEF")

Multiline statements in Python can terminate with a new line or the backslash (“\”) character, as shown here:

total = x1 + \ x2 + \ x3

Obviously you can place x1, x2, and x3 on the same line, so there is no reason to use three separate lines; however, this functionality is available in case you need to add a set of variables that do not fit on a single line. You can specify multiple statements in one line by using a semicolon (“;”) to separate each statement, as shown here:

a=10; b=5; print(a); print(a+b)

The output of the preceding code snippet is here:

NOTE The use of semi-colons and the continuation character are discouraged in Python

QUOTATION AND COMMENTS IN PYTHON

Python allows single ('), double (") and triple ('" or """) quotes for string literals, provided that they match at the beginning and the end of the string. You can use triple quotes for strings that span multiple lines. The following examples are legal Python strings:

word = 'word'

line = "This is a sentence."

para = """This is a paragraph. This paragraph contains more than one sentence."""

A string literal that begins with the letter “r” (for “raw”) treats everything as a literal character and “escapes” the meaning of meta characters, as shown here:

a1 = r'\n'

a2 = r'\r'

a3 = r'\t'

print('a1:',a1,'a2:',a2,'a3:',a3)

The output of the preceding code block is here:

a1: \n a2: \r a3: \t

You can embed a single quote in a pair of double quotes (and vice versa) in order to display a single quote or a double quote. Another way to accomplish the same result is to precede a single or double quote with a backslash (“\”) character. The following code block illustrates these techniques:

b1 = "'"

b2 = '"'

b3 = '\''

b4 = "\""

print('b1:',b1,'b2:',b2)

print('b3:',b3,'b4:',b4)

The output of the preceding code block is here:

b1: ' b2: "

b3: ' b4: "

A hash sign (#) that is not inside a string literal is the character that indicates the beginning of a comment. Moreover, all characters after the # and up to the physical line end are part of the comment (and ignored by the Python interpreter). Consider the following code block:

#!/usr/bin/python

# First comment print("Hello, Python!") # second comment

This will produce following result:

Hello, Python!

A comment may be on the same line after a statement or expression:

name = "Tom Jones" # This is also comment

You can comment multiple lines as follows:

# This is comment one

# This is comment two # This is comment three

A blank line in Python is a line containing only white space, a comment, or both.

SAVING YOUR CODE IN A MODULE

Earlier you saw how to launch the Python interpreter from the command line and then enter Python commands. However, that everything that you type in the Python interpreter is only valid for the current session: if you exit the interpreter and then launch the interpreter again, your previous definitions are no longer valid. Fortunately, Python enables you to store code in a text file, as discussed in the next section.

A module in Python is a text file that contains Python statements. In the previous section, you saw how the Python interpreter enables you to test code snippets whose definitions are valid for the current session. If you want to retain the code snippets and other definitions, place them in a text file so that you can execute that code outside of the Python interpreter.

The outermost statements in a Python are executed from top to bottom when the module is imported for the first time, which will then set up its variables and functions.

A Python module can be run directly from the command line, as shown here:

python first.py

As an illustration, place the following two statements in a text file called first.py:

x = 3 print(x)

Now type the following command:

python first.py

The output from the preceding command is 3, which is the same as executing the preceding code from the Python interpreter.

When a Python module is run directly, the special variable __name__ is set to __main__. You will often see the following type of code in a Python module:

if __name__ == '__main__': # do something here print('Running directly')

The preceding code snippet enables Python to determine if a Python module was launched from the command line or imported into another Python 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:

Another random document with no related content on Scribd:

THE AMERICAN.

The Leading Exponent of Bimetallism and Protection in the United States

A national weekly journal, Truthful, Fearless and Aggressive in the discussion of Public Affairs and other events of general interest, in which those who are literary, as well as those who desire to be fully informed on current events of Public Importance will find what they want.

WHARTON BARKER, Editor.

The American is fighting the battle of the masses against those who would fix the gold standard permanently upon the country; holding that the supreme duty of the American People is to conserve, protect and fortify the interests of the United States. $2.00 per annum. Sample copies free.

$3.00 for $2.00.

JUST THINK OF IT! For $2, the regular price of subscription, we will send The American and any one of these well-known periodicals: To Date. Munsey’s. Cosmopolitan. The Black Cat. McClure’s. Peterson’s. Book Buyer. Godey’s. Romance. American Sentinel. Farm Journal. American Agriculturist. Rural New Yorker. Art in Advertising.

Ladies’ Home Journal.

Sunday School Times.

American Gardening.

National Temperance Advocate.

American Woman’s Magazine.

The name of the subscriber must be one not now on our list. Mention this advertisement.

THE AMERICAN, No. 119 SOUTH FOURTH St., PHILADELPHIA.

Little Journeys

SERIES FOR 1896

Little Journeys to the Homes of American Authors.

The papers below specified were, with the exception of that contributed by the editor, Mr. Hubbard, originally issued by the late G. P. Putnam, in 1853, in a book entitled Homes of American Authors. It is now nearly half a century since this series (which won for itself at the time a very noteworthy prestige) was brought before the public; and the present publishers feel that no apology is needed in presenting to a new generation of American readers papers of such distinctive biographical interest and literary value.

No. 1, Emerson, by Geo. W. Curtis. ” 2, Bryant, by Caroline M. Kirkland.

” 3, Prescott, by Geo. S. Hillard. ” 4, Lowell, by Charles F. Briggs.

” 5, Simms, by Wm. Cullen Bryant. ” 6, Walt Whitman, by Elbert Hubbard. ” 7, Hawthorne, by Geo. Wm. Curtis.

” 8, Audubon, by Parke Godwin.

” 9, Irving, by H. T. Tuckerman.

” 10, Longfellow, by Geo. Wm. Curtis.

” 11, Everett, by Geo. S. Hillard.

” 12, Bancroft, by Geo. W. Greene.

The above papers will form the series of Little Journeys for the year 1896.

They will be issued monthly, beginning January, 1896, in the same general style as the series of 1895, at 50 cents a year, and single copies will be sold for 5 cents, postage paid.

G. P. PUTNAM’S SONS, NEW YORK AND LONDON

Quarterly. Illustrated.

“If Europe be the home of Art, America can at least lay claim to the most artistically compiled publication devoted to the subject that we know of. This is Modern Art.”—Galignani Messenger (Paris).

“The most artistic of American art periodicals. A work of art itself.”—Chicago Tribune.

Fifty Cents a Number. Two Dollars a Year Single Copies (back numbers) 50 Cents in Stamps. Illustrated Sample Page Free.

Arthur W. Dow has designed a new poster for Modern Art. It is exquisite in its quiet harmony and purely decorative character, with breadth and simplicity in line and mass, and shows the capacity of pure landscape for decorative purposes.—The Boston Herald.

Price, 25 Cents in Stamps, Sent Free to New Subscribers to Modern Art.

L. Prang & Company, Publishers. 286 ROXBURY STREET, BOSTON.

RUSSIAN FAIRY TALES: Translated by R. Nisbit Bain. Illustrated by C. M. Gere. 8vo., Ornamental Cloth, gilt top, $1.50.

OLD ENGLISH FAIRY TALES: By S. Baring Gould. With illustrations by F. D. Bedford. Octavo. Cloth, $2.00. London: Methuen & Co.

SHELLEY’S TRANSLATION OF THE BANQUET OF PLATO: A dainty reprint of Shelley’s little-known translation of “The Banquet of Plato,” prefaced by the poet’s fragmentary note on “The Symposium.” Title-page and decorations by Mr. Bruce Rogers. 16mo., $1.50. Seventy-five copies on hand-made paper, $3.00 net.

HAND AND SOUL: By Dante Gabriel Rossetti. Printed by Mr. William Morris at the Kelmscott Press.

This book is printed in the “Golden” type, with a specially designed title-page and border, and in special binding. “Hand and Soul” first appeared in “The Germ,” the short-lived magazine of the Pre-Raphælite Brotherhood. A few copies also on Vellum.

For sale by all booksellers, or mailed postpaid by the publishers, on receipt of price.

WAY & WILLIAMS, Monadnock Block. Chicago.

1. RUBAIYAT OF OMAR KHAYYAM.

RENDERED INTO ENGLISH VERSE BY EDWARD FITZGERALD.

This is not a mere reprint of “The Bibelot” edition, but has been edited with a view to making FitzGerald’s wonderful version indispensable in its present shape.

The following are special features that as a whole can only be found in edition:

I. An entirely new biographical sketch of Edward FitzGerald by Mr. W. Irving Way of Chicago.

II. Parallel texts of the First and Fourth editions, printed the one in Italic and the other in Roman type on opposite pages, the better to distinguish them.

III. Variorum readings giving all textual changes occurring in the Second, Third and Fourth editions.

IV. The omitted quatrains of the rare Second Edition of 1868. To the student of literature these cancelled readings are of the greatest interest and value.

V. A bibliography of all English versions and editions revised to date.

VI. Finally, three poems upon Omar and FitzGerald, not generally known, are here given, just as in The Bibelot Edition, two poems were there reprinted as fitting foreword and finale.

925 copies on Van Gelder’s hand-made paper at $1.00 net.

100 ” ” Japan Vellum (numbered) at $2 50 ”

Address

THOMAS B. MOSHER, Portland, Maine.

A

SHELF OF BOOKS.

To the Homes of Good Men and Great.

By Elbert Hubbard. Series 1895, handsomely bound. Illustrated with twelve portraits, etched and in photogravure. 16mo., printed on deckle-edge paper, gilt top. $1.75.

THE ELIA SERIES.

A Selection of Famous Books, offered as specimens of the best literature and of artistic typography and bookmaking. Printed on deckle-edge paper, bound in full ooze calf, with gilt tops, 16mo., (6½ x 4½ inches), each volume (in box), $2.25.

⁂ There are three different colors of binding—dark green, garnet and umber.

First group: The Essays of Elia, 2 vols. The Discourses of Epictetus. Sesame and Lilies. Autobiography of Franklin. Thoughts of Marcus Aurelius.

NO ENEMY: BUT HIMSELF.

The Romance of a Tramp. By Elbert Hubbard. Twenty-eight fullpage illustrations. Second edition. Bound in ornamental cloth, $1.50.

EYES LIKE THE SEA.

By Maurus Jokai. (The great Hungarian Novelist.) An Autobiographical Romance. Translated from the Hungarian by Nisbet Bain. $1.00.

G. P. PUTNAM’S SONS, NEW YORK AND LONDON.

FOOTLIGHTS,

that weekly illustrated paper published in Philadelphia (pity, isn’t it?), is a clean (moderately so) paper, chock full of such uninteresting topics as interviews with actor and actress (bless ’em); book gossip, news from Paris and London, (dear, old Lunnon), woman’s chatter, verse and lots more of idiocy that only spoils white paper. It sells for five cents a copy, or $2.00 a year.

VERY SPECIAL: Send two dollars and Footlights and T P will be sent you for one year. Address

THE PHILISTINE, East Aurora, N. Y.

THE ROYCROFT

PRINTING SHOP at this time desires to announce a sister book to the Song of Songs: which is Solomon’s. It is the Journal of Koheleth: being a Reprint of the Book of Ecclesiastes with an Essay by Mr. Elbert Hubbard. The same Romanesque types are used that served so faithfully and well in the Songs, but the initials, colophon and rubricated borders art special designs. After seven hundred and twelve copies are printed the types will be distributed and the title page, colophon and borders destroyed.

In preparation of the text Mr Hubbard has had the scholarly assistance of his friend, Dr. Frederic W. Sanders, of Columbia University. The worthy pressman has also been helpfully counseled by several Eminent Bibliophiles.

The seven hundred copies that are printed on Holland handmade paper are offered at two dollars each, and the twelve copies on Japan Vellum at five dollars. Every book will be numbered and signed by Mr. Hubbard. Orders are now being recorded, but Book Lovers are requested not to send remittances until the volume is in their hands.

THE ROYCROFT PRINTING SHOP, East Aurora, New York.

CATHOLICITY IN ART.

All’s one, all’s one! the critic learns, Though hostile tastes be frowning; That poets’ flame where Bobby burns, Where, too, is Robert, browning.

W S B.

*** END OF THE PROJECT GUTENBERG EBOOK THE PHILISTINE

***

Updated editions will replace the previous one—the old editions will be renamed.

Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution.

START: FULL LICENSE

THE FULL PROJECT GUTENBERG LICENSE

PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license.

Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works

1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.

1.C. The Project Gutenberg Literary Archive Foundation (“the Foundation” or PGLAF), owns a compilation copyright in the collection of Project Gutenberg™ electronic works. Nearly all the individual works in the collection are in the public domain in the United States. If an individual work is unprotected by copyright law in the United States and you are located in the United States, we do not claim a right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the work as long as all references to Project Gutenberg are removed. Of course, we hope that you will support the Project Gutenberg™ mission of promoting free access to electronic works by freely sharing Project Gutenberg™ works in compliance with the terms of this agreement for keeping the Project Gutenberg™ name associated with the work. You can easily comply with the terms of this agreement by keeping this work in the same format with its attached full Project Gutenberg™ License when you share it without charge with others.

1.D. The copyright laws of the place where you are located also govern what you can do with this work. Copyright laws in most countries are in a constant state of change. If you are outside the United States, check the laws of your country in addition to the terms of this agreement before downloading, copying, displaying, performing, distributing or creating derivative works based on this work or any other Project Gutenberg™ work. The Foundation makes no representations concerning the copyright status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other immediate access to, the full Project Gutenberg™ License must appear prominently whenever any copy of a Project Gutenberg™ work (any work on which the phrase “Project Gutenberg” appears, or with which the phrase “Project

Gutenberg” is associated) is accessed, displayed, performed, viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files containing a part of this work or any other work associated with Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without prominently displaying the sentence set forth in paragraph 1.E.1 with active links or immediate access to the full terms of the Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive

Foundation at the address specified in Section 4, “Information about donations to the Project Gutenberg Literary Archive Foundation.”

• You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™ License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work.

• You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual

property infringement, a defective or damaged disk or other medium, a computer virus, or computer codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGESExcept for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH

1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,

WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of Project Gutenberg™

Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org.

Section 3. Information about the Project Gutenberg Literary Archive Foundation

The Project Gutenberg Literary Archive Foundation is a nonprofit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact

Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation

Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.