100% нашли этот документ полезным (9 голосов)
22 просмотров

Full download (Ebook) C and Python Applications: Embedding Python Code in C Programs, SQL Methods, and Python Sockets by Philip Joyce ISBN 9781484277737, 1484277732 pdf docx

Документ представляет собой рекламный материал для различных электронных книг, включая 'C and Python Applications' Филипа Джойса, который охватывает внедрение кода Python в программы на C, методы SQL и сокеты Python. Он также включает ссылки на другие книги по программированию на Python и C, а также ресурсы для скачивания. В документе содержится информация о доступных форматах и возможностях чтения на различных устройствах.

Загружено:

kamarformaj7
Авторское право
© © All Rights Reserved
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (9 голосов)
22 просмотров

Full download (Ebook) C and Python Applications: Embedding Python Code in C Programs, SQL Methods, and Python Sockets by Philip Joyce ISBN 9781484277737, 1484277732 pdf docx

Документ представляет собой рекламный материал для различных электронных книг, включая 'C and Python Applications' Филипа Джойса, который охватывает внедрение кода Python в программы на C, методы SQL и сокеты Python. Он также включает ссылки на другие книги по программированию на Python и C, а также ресурсы для скачивания. В документе содержится информация о доступных форматах и возможностях чтения на различных устройствах.

Загружено:

kamarformaj7
Авторское право
© © All Rights Reserved
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 58

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) C and Python Applications: Embedding


Python Code in C Programs, SQL Methods, and Python
Sockets by Philip Joyce ISBN 9781484277737,
1484277732
https://ebooknice.com/product/c-and-python-applications-
embedding-python-code-in-c-programs-sql-methods-and-python-
sockets-36380876

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Optimizing Visual Studio Code for Python


Development: Developing More Efficient and Effective
Programs in Python by Sufyan bin Uzayr ISBN 9781484273432,
1484273435
https://ebooknice.com/product/optimizing-visual-studio-code-for-
python-development-developing-more-efficient-and-effective-programs-
in-python-34775482
ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com
(Ebook) Functional Python Programming...Efficient Python
Code by Lott S.

https://ebooknice.com/product/functional-python-programming-efficient-
python-code-56115518

ebooknice.com

(Ebook) C++ & Python, Tricks And Tips ISBN 9781912847549,


191284754X

https://ebooknice.com/product/c-python-tricks-and-tips-22061858

ebooknice.com

(Ebook) C++ & Python, Tricks And Tips - 5th Edition 2021
by ,,,,

https://ebooknice.com/product/c-python-tricks-and-tips-5th-
edition-2021-38188902

ebooknice.com

(Ebook) A Python Data Analyst’s Toolkit: Learn Python and


Python-based Libraries with Applications in Data Analysis
and Statistics by Gayathri Rajagopalan ISBN 9781484263983,
9781484263990, 1484263987, 1484263995
https://ebooknice.com/product/a-python-data-analysts-toolkit-learn-
python-and-python-based-libraries-with-applications-in-data-analysis-
and-statistics-22156588
ebooknice.com

(Ebook) Dead Simple Python: Idiomatic Python for the


Impatient Programmers by Jason C. McDonald ISBN
9781718500921, 1718500920
https://ebooknice.com/product/dead-simple-python-idiomatic-python-for-
the-impatient-programmers-46488368

ebooknice.com
C and
Python
Applications
Embedding Python Code in C Programs,
SQL Methods, and Python Sockets

Philip Joyce
C and Python
Applications
Embedding Python Code in
C Programs, SQL Methods,
and Python Sockets

Philip Joyce
C and Python Applications: Embedding Python Code in C Programs, SQL Methods,
and Python Sockets

Philip Joyce
Crewe, UK

ISBN-13 (pbk): 978-1-4842-7773-7 ISBN-13 (electronic): 978-1-4842-7774-4


https://doi.org/10.1007/978-1-4842-7774-4

Copyright © 2022 by Philip Joyce


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin Suresh John
Development Editor: James Markham
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Pixabay
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or
visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is
Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware
corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback,
or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484277737. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi


Acknowledgments������������������������������������������������������������������������������������������������� xiii

Introduction�������������������������������������������������������������������������������������������������������������xv

Chapter 1: Python Programming������������������������������������������������������������������������������ 1


Definition of Variables������������������������������������������������������������������������������������������������������������������� 1
Real (Float) Numbers��������������������������������������������������������������������������������������������������������������� 5
Characters������������������������������������������������������������������������������������������������������������������������������� 6
Reading in Data����������������������������������������������������������������������������������������������������������������������������� 6
Arrays�������������������������������������������������������������������������������������������������������������������������������������������� 8
Inserting into an Array������������������������������������������������������������������������������������������������������������� 9
Deleting (Removing) from an Array��������������������������������������������������������������������������������������� 10
Searching������������������������������������������������������������������������������������������������������������������������������ 10
Updating an Array������������������������������������������������������������������������������������������������������������������ 11
Appending to an Array����������������������������������������������������������������������������������������������������������� 11
Strings����������������������������������������������������������������������������������������������������������������������������������������� 12
Lists�������������������������������������������������������������������������������������������������������������������������������������������� 14
Reading Entries in a List�������������������������������������������������������������������������������������������������������� 15
Updating a List����������������������������������������������������������������������������������������������������������������������� 16
Deleting an Element from List����������������������������������������������������������������������������������������������� 16
Appending to a List���������������������������������������������������������������������������������������������������������������� 16
Dictionaries��������������������������������������������������������������������������������������������������������������������������������� 17
Creating a Dictionary������������������������������������������������������������������������������������������������������������� 17
Appending to a Dictionary����������������������������������������������������������������������������������������������������� 17
Amending a Dictionary���������������������������������������������������������������������������������������������������������� 18

iii
Table of Contents

Deleting from a Dictionary����������������������������������������������������������������������������������������������������� 19


Searching Through a Dictionary�������������������������������������������������������������������������������������������� 19
Tuples������������������������������������������������������������������������������������������������������������������������������������������ 20
Creating a Tuple��������������������������������������������������������������������������������������������������������������������� 21
Concatenating Two Tuples����������������������������������������������������������������������������������������������������� 22
Creating Nested Tuples���������������������������������������������������������������������������������������������������������� 22
Creating Repeated Tuples������������������������������������������������������������������������������������������������������ 22
Converting a List or a String into a Tuple������������������������������������������������������������������������������� 23
Creating Single-Element Tuple���������������������������������������������������������������������������������������������� 23
Reading Tuple������������������������������������������������������������������������������������������������������������������������ 23
Searching Within a Tuple������������������������������������������������������������������������������������������������������� 23
Deleting a Tuple��������������������������������������������������������������������������������������������������������������������� 24
Using Tuple to Create Variables��������������������������������������������������������������������������������������������� 24
If Then Else��������������������������������������������������������������������������������������������������������������������������������� 25
Loops (For and While)����������������������������������������������������������������������������������������������������������������� 26
For Loops������������������������������������������������������������������������������������������������������������������������������� 26
While Loops��������������������������������������������������������������������������������������������������������������������������� 28
Switches������������������������������������������������������������������������������������������������������������������������������������� 29
Arithmetic Operations Using Numpy������������������������������������������������������������������������������������������� 30
Numpy Calculations��������������������������������������������������������������������������������������������������������������� 34
Mathematical Graph Functions��������������������������������������������������������������������������������������������������� 38
User-Written Functions��������������������������������������������������������������������������������������������������������������� 43
File Access���������������������������������������������������������������������������������������������������������������������������������� 45
Regressions�������������������������������������������������������������������������������������������������������������������������������� 52
Summary������������������������������������������������������������������������������������������������������������������������������������ 57
Exercises������������������������������������������������������������������������������������������������������������������������������������� 57

Chapter 2: C Programming������������������������������������������������������������������������������������� 59
C Program Format����������������������������������������������������������������������������������������������������������������������� 59
Adding Two Numbers������������������������������������������������������������������������������������������������������������������ 60
Multiply and Divide Two Numbers����������������������������������������������������������������������������������������������� 62
For Loops������������������������������������������������������������������������������������������������������������������������������������ 63
iv
Table of Contents

Do While Loops��������������������������������������������������������������������������������������������������������������������������� 65
Switch Instruction����������������������������������������������������������������������������������������������������������������������� 66
If Else������������������������������������������������������������������������������������������������������������������������������������������ 67
If Else If��������������������������������������������������������������������������������������������������������������������������������������� 68
Data Arrays��������������������������������������������������������������������������������������������������������������������������������� 70
Functions������������������������������������������������������������������������������������������������������������������������������������ 81
Strings����������������������������������������������������������������������������������������������������������������������������������������� 86
Structures����������������������������������������������������������������������������������������������������������������������������������� 88
Size of Variables�������������������������������������������������������������������������������������������������������������������������� 91
Goto Command��������������������������������������������������������������������������������������������������������������������������� 92
Common Mathematical and Logical Symbols����������������������������������������������������������������������������� 93
File Access���������������������������������������������������������������������������������������������������������������������������������� 94
Student Records File������������������������������������������������������������������������������������������������������������� 95
Summary���������������������������������������������������������������������������������������������������������������������������������� 105
Exercises����������������������������������������������������������������������������������������������������������������������������������� 106

Chapter 3: SQL in C����������������������������������������������������������������������������������������������� 107


Review of SQL and SQLite��������������������������������������������������������������������������������������������������������� 107
Creating the Database�������������������������������������������������������������������������������������������������������������� 108
Creating a Table������������������������������������������������������������������������������������������������������������������������ 110
Inserting Rows�������������������������������������������������������������������������������������������������������������������������� 113
Insert a Preset Row������������������������������������������������������������������������������������������������������������� 113
Inserting a User-Entered Row���������������������������������������������������������������������������������������������� 114
Selecting Rows������������������������������������������������������������������������������������������������������������������������� 117
Selecting a Row Preset������������������������������������������������������������������������������������������������������� 117
Selecting All Rows��������������������������������������������������������������������������������������������������������������� 120
Selecting Rows by Age�������������������������������������������������������������������������������������������������������� 122
Amending Rows������������������������������������������������������������������������������������������������������������������������ 125
Deleting Rows��������������������������������������������������������������������������������������������������������������������������� 128
Summary���������������������������������������������������������������������������������������������������������������������������������� 130
Exercises����������������������������������������������������������������������������������������������������������������������������������� 130

v
Table of Contents

Chapter 4: SQL in Python�������������������������������������������������������������������������������������� 131


Review of SQL��������������������������������������������������������������������������������������������������������������������������� 131
Create a Table���������������������������������������������������������������������������������������������������������������������� 133
Mechanism for Inserting a Row������������������������������������������������������������������������������������������� 134
Update a Row���������������������������������������������������������������������������������������������������������������������� 139
Delete a Row����������������������������������������������������������������������������������������������������������������������� 148
Read a Table������������������������������������������������������������������������������������������������������������������������ 149
Summary���������������������������������������������������������������������������������������������������������������������������������� 150
Exercises����������������������������������������������������������������������������������������������������������������������������������� 150

Chapter 5: Embedded Python������������������������������������������������������������������������������� 151


Basic Mechanism���������������������������������������������������������������������������������������������������������������������� 151
Plot a 2D Line���������������������������������������������������������������������������������������������������������������������������� 153
Plot Two 2D Lines���������������������������������������������������������������������������������������������������������������������� 155
Plot Trigonometric Curves��������������������������������������������������������������������������������������������������������� 158
Enter Data to Plot���������������������������������������������������������������������������������������������������������������������� 160
2D Center of Mass Plot������������������������������������������������������������������������������������������������������������� 170
Histograms�������������������������������������������������������������������������������������������������������������������������������� 177
Importing a Picture������������������������������������������������������������������������������������������������������������������� 179
Summary���������������������������������������������������������������������������������������������������������������������������������� 181
Exercise������������������������������������������������������������������������������������������������������������������������������������ 181

Chapter 6: Sockets����������������������������������������������������������������������������������������������� 183


A Closer Look at Sockets���������������������������������������������������������������������������������������������������������� 183
Basic Client-Server������������������������������������������������������������������������������������������������������������������� 185
Server-Client Pair to Send-Receive a File��������������������������������������������������������������������������������� 187
Threaded Programs������������������������������������������������������������������������������������������������������������������ 191
Closing Down a Threaded Server���������������������������������������������������������������������������������������������� 194
Chat Programs�������������������������������������������������������������������������������������������������������������������������� 197
Summary���������������������������������������������������������������������������������������������������������������������������������� 199
Exercise������������������������������������������������������������������������������������������������������������������������������������ 199

vi
Table of Contents

Appendix A: Answers to Examples����������������������������������������������������������������������� 201


C
 hapter 1���������������������������������������������������������������������������������������������������������������������������������� 201
Chapter 2���������������������������������������������������������������������������������������������������������������������������������� 206
Chapter 3���������������������������������������������������������������������������������������������������������������������������������� 212
Chapter 4���������������������������������������������������������������������������������������������������������������������������������� 219
Chapter 5���������������������������������������������������������������������������������������������������������������������������������� 223
Chapter 6���������������������������������������������������������������������������������������������������������������������������������� 228

Index��������������������������������������������������������������������������������������������������������������������� 231

vii
About the Author
Philip Joyce has 28 years of experience as a software engineer, working on control of
steel production, control of oil refineries, communications software (pre-Internet), office
products (server software), and computer control of airports. He programs in Assembler,
COBOL, Coral 66, C, and C++ with SQL. He served as a mentor to new graduates in the
Ferranti Company. He obtained an MSc in computational physics (including augmented
matrix techniques and Monte Carlo techniques using Fortran) from Salford University in
1996. He is also a chartered physicist and a member of the Institute of Physics (member
of the Higher Education Group).

ix
About the Technical Reviewer
Swathi Sutrave is a self-professed tech geek. She has been
a subject matter expert for several different programming
languages, including Python, C, and SQL, for corporations,
startups, and universities.

xi
Acknowledgments
Thanks to my wife, Anne, for her support, my son Michael, and my daughter Katharine.
All three have mathematics degrees. Thanks to everyone on the Apress team who helped
me with the publication of this, my third book.

xiii
Introduction
The C and Python programming languages are important languages in many computer
applications. This book will demonstrate how to use the C and Python languages to write
applications in SQL. It will demonstrate how to embed a Python program within a C
program. Finally, the reader will learn how to create Python socket programs which can
communicate with each other on different computers (these are called “sockets”).
A basic familiarity with mathematics is assumed along with some experience of the
basics of computer programs. The first two chapters review the basics of C and Python.
The chapters following these are grouped into SQL techniques, embedded Python, and
sockets applications. There are exercises in each chapter with answers and suggested
code at the end of the book.

xv
CHAPTER 1

Python Programming
This is the first of two chapters in which you’ll review both Python and C programming
languages. A basic understanding of computing and what programs are about is
assumed although no prior knowledge of either Python or C is needed.
In this chapter, we will start with the basics of Python. This will include how items
used in a program are stored in the computer, basic arithmetic formats, handling strings
of characters, reading in data that the user can enter on the command line, etc. Then
we will work up to file access on the computer, which will lead us up to industrial/
commercial-level computing by the end of the book.
If you don’t already have a Python development environment on your computer,
you can download it and the Development Kit, free of charge, from www.python.org/
downloads/. Another way you can access Python is by using Visual Studio. Again, a
version of this can be downloaded.

D
 efinition of Variables
This section looks at the different types of store areas that are used in Python. We refer
to these store areas as “variables.” The different types can be numbers (integers or
decimals), characters, and different types of groups of these (strings, arrays, dictionaries,
lists, or tuples).
In these examples, you can go to the command line and enter “Python” which starts
up the Python environment and produces “>>>” as the prompt for you to enter Python
code.

1
© Philip Joyce 2022
P. Joyce, C and Python Applications, https://doi.org/10.1007/978-1-4842-7774-4_1
Chapter 1 Python Programming

In Python, unlike C, you don’t define the variable as a specific type. The different
types are integer, floating point, character, string, etc. The type is assigned when you give
the variable a value. So try the following code:

>>> a1 = 51
>>> print(type(a1))
We get the output
<class 'int'>
>>>

Here we are defining a variable called “a1” and we are assigning the integer value 51
to it.
We then call the function “print” with the parameter “type” and “a1” and we get the
reply “class ‘int’”. “type” means that we want to display whether the variable is an integer,
floating point, character, string, etc.
We can now exit the Python environment by typing “quit()”.
We will now perform the same function from a program.
Create a file called “typ1a.py”.
Then enter the following two lines of Python code:

a1=51
print(type(a1))

Now on the command line, enter “python typ1a.py”.


And you should get the output

<class 'int'>

which is the same as our first example.


This is just demonstrating the equivalence of the two methods.
Obviously, if you want to run a program with many lines of code and possibly run it
many times, then having the code in a file is more efficient.
We can demonstrate different data types being stored in the same variable using the
following code:

a1=51
print(type(a1))

a1=51.6
print(type(a1))
2
Chapter 1 Python Programming

a1='51'
print(type(a1))

When we run this, we get

<class 'int'>
<class 'float'>
<class 'str'>

The 51 entered is an int. The 51.6 is a float (decimal) type, and ‘51’ is a string.
We can make the results a little clearer if we use print(“a1 is”, type(a1)).
So our program now reads

a1=51
print("a1 is",type(a1))

a1=51.6
print("a1 is",type(a1))

a1='51'
print("a1 is",type(a1))

and the output is

a1 is <class 'int'>
a1 is <class 'float'>
a1 is <class 'str'>

We can put a comment on our line of code by preceding it with the “#” character.

a1='51' #assign string containing 51 to variable a1


print("a1 is",type(a1)) # print the type assigned to a1

Some simple arithmetic operations are shown in the following.


The following code is held in the file “arith1.py”:

arith1a.py

Initialize the variables v1, v2, v3, and v4 with integer values.

v1= 2
v2 = 4
v3 = 7
v4 = 8
3
Chapter 1 Python Programming

Add v1 to v2 and store the result in v5.

v5 = v1 + v2
print(v5)

The result is

You can combine the adding with the print as follows:

print(v1+v2)

Giving the same answer:

Now a subtraction:

v6 = v4 - v3
print(v6)
giving
1

Now a multiplication:

v7 = v4 * v3

print(v7)
giving
56

Now a division:

v8 = v4 / v1
print(v8)
giving
4.0

v10 = v3 % v2 # the % sign means show the remainder of the division


print(v10)
gives
3

4
Chapter 1 Python Programming

Raise by the power 2.

v11 = v2 ** 2
print(v11)
gives
16

Raise to the power held in variable v1.


Here v2 contains 4 and v1 contains 2.

v11 = v2 ** v1
print(v11)
gives
16

Show how Python obeys the rules of BODMAS (BIDMAS).


Here v2 contains 4, v1 contains 2, v3 contains 7, and v4 contains 8.

v11 = v1 + v2 * v4 - v3 # show BODMAS


print(v11)
gives
27

Show how Python obeys the normal algebra rules.

v11 = (v1 + v2) * (v4 - v3)


print(v11)
gives
6

Real (Float) Numbers


This type of number contains a decimal point. So, for the following assignments

V1 = 2
V2 = 3.5
V3 = 5.1
V4 = 6.75

5
Chapter 1 Python Programming

we get

print(type(V1))
<class 'int'>
print(type(V2))
<class 'float'>
print(type(V3))
<class 'float'>
print(type(V4))
<class 'float'>

Characters
In Python, you can also assign characters to locations, for example:

c1 = 'a'
print(type(c1))
produces
<class 'str'>

which means that c1 is classed as a string.


Now that we know what different types of variables we can have, we will look at how
we use them.

Reading in Data
Now that we can display a message to the person running our program, we can ask them
to type in a character, then read the character, and print it to the screen. This section
looks at how the user can enter data to be read by the program.
If we type in the command

vara = input()

the computer waits for the user to type in data.


So if you now enter r5, the computer stores r5 in the variable vara.
You can check this by printing the contents of vara by typing

print(vara)

6
Chapter 1 Python Programming

which prints

r5

We can make this more explicit by using

print("data typed in is:-", vara)


giving
data typed in is:-r5

You can also make the entry command clearer to the user by entering

varb=input(“enter some data to be stored in varb”)

Then, again we can explicitly print out the contents

print("data typed in is:-", varb)


giving
data typed in is:-r5

You have to use int(input) to enter an integer.


Otherwise, it is a string (one or more characters), for example:

n = int(input('Enter a number: '))


you enter 4
>>> print(type(n))
<class 'int'>

# Program to check input


# type in Python

num = input ("Enter number :")


print(num)
#You could enter 5 here and it would store 5 as a string and not as a
number
>>> print(num)
5
>>> print ("type of number", type(num))
type of number <class 'str'>
>>>

7
Chapter 1 Python Programming

#entering a float number (type 'float' before the 'input' command)


n = float(input('Enter a number: '))
Enter a number: 3.8
>>> print(type(n))
<class 'float'>
>>> print(n )
3.8

Now that we can enter data manually into the program, we will look at groups of data.

Arrays
An array is an area of store which contains a number of items. So from our previous
section on integers, we can have a number of integers defined together with the same
label. Python does not have a default type of array, although we have different types of
array.
So we can have an array of integers called “firstintarr” with the numbers 2, 3, 5, 7,
11, and 13 in it. Each of the entries is called an “element,” and the individual elements
of the array can be referenced using its position in the array. The position is called the
“index.” The elements in the array have to be of the same type. The type is shown at the
beginning of the array.
The array mechanism has to be imported into your program, as shown as follows:

from array import *


firstintarr = array('i', [2,3,5,7,11])

The ‘i’ in the definition of firstintarr means that the elements are integers.
And we can reference elements of the array using the index, for example:

v1 = firstintarr[3]
print(v1)

This outputs

We can also define floating point variables in an array by replacing the “i” by “f” in
the definition of the array.

8
Chapter 1 Python Programming

So we can define

firstfloatarr = array( 'f', [0.2,4.3,21.9,7.7])

And we can now write

varfloat1 = firstfloatarr[1]
print(varfloat1)

This will store 4.3 into varfloat1.


The array mechanism has to be imported into your program.
So at the start of each program, you need to include the code

from array import *

Once we have our array, we can insert, delete, search, or update elements into the array.
Array is a container which can hold a fix number of items, and these items should
be of the same type. Most of the data structures make use of arrays to implement their
algorithms. The following are the important terms to understand the concept of array:

• Insert

• Delete (remove)

• Search

• Update

• Append

Let’s review them now.

Inserting into an Array


The following code is in the file array3.py:

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.insert(1,13) # this inserts 13 into position 1 of the array (counting


from 0)

for x in myarr:
print(x)
9
Chapter 1 Python Programming

This outputs

2
13
3
5
7
11

Deleting (Removing) from an Array


The following code is in the source code file array4.py:
array4.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr.remove(2) # this removes the element containing 2 from the array

for x in myarr:
print(x)

This outputs

3
5
7
11

Searching
The following code is in the file array5.py:

from array import *

myarr = array('i', [2,3,5,7,11])

print (myarr.index(3))#this finds the index of the array which contains 3

10
Chapter 1 Python Programming

This outputs

Updating an Array
The following code is in the file array6.py:
array6.py

from array import *

myarr = array('i', [2,3,5,7,11])

myarr[2] = 17) #this updates element 2 with 17

for x in myarr:
print(x)

This outputs

2
3
17
7
11

Appending to an Array
The following code is in the file array9a.py:
array9a.py

from array import *

myarr = array('i', [2,3,5,7,11])

for x in myarr:
print(x)

new = int(input("Enter an integer: "))


myarr.append(new)
print(myarr)

11
Chapter 1 Python Programming

This outputs

2
3
5
7
11

Enter an integer: 19

array('i', [2, 3, 5, 7, 11, 19])

This section has shown the “array” use in Python.

Strings
Strings are similar to the character arrays we discussed in the previous section. They are
defined within quotation marks. These can be either single or double quotes. We can
specify parts of our defined string using the slice operator ([ ] and [:]). As with character
arrays, we can specify individual elements in the string using its position in the string
(index) where indexes start at 0.
We can concatenate two strings using “+” and repeat the string using “*”.
We cannot update elements of a string – they are immutable. This means that once
they are created, they cannot be amended.
The following code:

firststring = 'begin'
print(firststring)
gives
begin

The following code:

one = 1
two = 2
three = one + two
print(three)
#gives
3
12
Chapter 1 Python Programming

The following code:

first = " first "


second= "second"
concat = first + " " + second
print(concat)
#gives
first  second
print("concat: %s" % concat)
gives
concat:  first  second
The following code is in the file tst13a.py
secondstring = "second string"
print(secondstring.index("o")) #gives
3
print(secondstring.count("s")) # count the number of s characters in string
gives
2

print(secondstring[2:9]) # prints slice of string from 2 to 9 giving

cond st
print(secondstring[2:9:1]) #  The general form is [start:stop:step] giving

cond st
print(secondstring[::-1]) # Reverses the string giving

gnirts dnoces

splitup = secondstring.split(" ")


print(splitup) #gives
['second', 'string']

Strings are immutable, so if we tried

second= "second"
second[0]="q"

13
Chapter 1 Python Programming

we get

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment

indicating that we tried to update something (a string in this case) which is immutable.

Lists
Lists are similar to arrays and strings, in that you define a number of elements, which
can be specified individually using the index. With lists, however, the elements can be of
different types, for example, a character, an integer, and a float.
The following code is in the file alist7.py:

firstlist = ['k', 97 ,56.42, 64.08, 'bernard']

We specify the elements within square brackets.


We can then access individual elements in the list using the index (starting from 0),
for example:

print(firstlist[0])
gives
k
print(firstlist[1:3])
gives
[97, 56.42]

We can amend an element in a list.

firstlist[3] = 'plj'
print(firstlist)
giving
['k', 97, 56.42, 'plj', 'bernard']

14
Chapter 1 Python Programming

We can delete an element from a list.

del firstlist[3]
print(firstlist)
giving
['k', 97, 56.42, 'bernard']

We can append an element to the list.

firstlist.append(453.769)
print(firstlist)
giving
['k', 97, 56.42, 'bernard', 453.769]

Reading Entries in a List


The following code is held in the file alist1a.py:
alist1a.py

list1 = ['first', 'second', 'third']


list2 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)


print ("list1[0]: ", list1[0])
print ("list2: ", list2)
print ("list2[3]: ", list2[3])
print ("list2[:3]: ", list2[:3])
print ("list2[2:]: ", list2[2:])
print ("list2[1:3]: ", list2[1:3])

This outputs

list1:  ['first', 'second', 'third']


list1[0]:  first
list2:  [1, 2, 3, 4, 5]
list2[3]:  4
list2[:3]:  [1, 2, 3]
list2[2:]:  [3, 4, 5]
list2[1:3]:  [2, 3]

15
Chapter 1 Python Programming

Updating a List
The following code is held in the file alist2a.py:

alist2a.py

list1 = [1, 2, 3, 4, 5 ]

print ("list1: ", list1)

list1[1] = 26 #update the second item (counting from zero)

print ("updated list1: ", list1)

This outputs

list1:  [1, 2, 3, 4, 5]
updated list1:  [1, 26, 3, 4, 5]

Deleting an Element from List


The following code is held in the file alist3a.py:

alist3a.py
list1 = [1,2,3,4,5,6]
print (list1)
del list1[4]
print ("Updated list1 : ", list1)

This outputs

[1, 2, 3, 4, 5, 6]
Updated list1 :  [1, 2, 3, 4, 6]

Appending to a List
The following code is held in the file alist4aa.py:

alist4aa.py
list2 = [10,11,12,13,14,15]
print (list2)

16
Chapter 1 Python Programming

new = int(input("Enter an integer: "))


list2.append(new)
print(list2)

This outputs (if you enter 489)

[10, 11, 12, 13, 14, 15]

Enter an integer: 489

[10, 11, 12, 13, 14, 15, 489]

This has shown the use of lists.

Dictionaries
Dictionaries contain a list of items where one item acts as a key to the next. The list is
unordered and can be amended. The key-value relationships are unique. Dictionaries
are mutable.

Creating a Dictionary
In the first example, we create an empty dictionary. In the second, we have entries.

firstdict = {}

or

firstdict ={'1':'first','two':'second','my3':'3rd'}

Appending to a Dictionary
The following code is held in the file adict1a.py:

adict1a.py
#create the dictionary
adict1 = {'1':'first','two':'second','my3':'3rd'}

print (adict1)

17
Chapter 1 Python Programming

print (adict1['two'])   # in the dictionary 'two' is the key to 'second'

adict1[4] = 'four' # we want to add another value called 'four' whose key
is 4

print (adict1)

print (len(adict1)) #this will print the number of key-value pairs

This outputs

{'1': 'first', 'two': 'second', 'my3': '3rd'}


second
{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four'}
4

If we want to add value whose key is dinsdale, then we specify it as ‘dinsdale’.


So

adict1['dinsdale'] = 'doug'
print (adict1)

outputs

{'1': 'first', 'two': 'second', 'my3': '3rd', 4: 'four', 'dinsdale': 'doug'}

Amending a Dictionary
The following code is held in the file adict2a.py.
This amends the value whose key is ‘two’ to be '2nd'.

adict2a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}

adict1['two'] = '2nd'

print(adict1)

This outputs

{'1': 'first', 'two': '2nd', 'my3': '3rd'}

18
Chapter 1 Python Programming

Deleting from a Dictionary


The following code is held in the file adict3a.py:

adict3a.py
adict1 = {'1':'first','two':'second','my3':'3rd'}
print(adict1)
del adict1['two'] #this deletes the key-value pair whose key is 'two'
print(adict1)

This outputs

{'1': 'first', 'two': 'second', 'my3': '3rd'}


{'1': 'first', 'my3': '3rd'}

Searching Through a Dictionary


We want to search a dictionary to see if a specific key is contained in it. In this case, we
want to see if ‘a’ and ‘c’ are keys in the dictionary.
In Python

>>> my_dict = {'a' : 'one', 'b' : 'two'}

>>> 'a' in my_dict


TRUE
>>> 'c' in my_dict
FALSE

The following code is held in the file adict5aa.py:

adict5aa.py
print("Enter key to be tested: ")
testkey = input()
my_dict = {'a' : 'one', 'b' : 'two'}
print (my_dict.get(testkey, "none"))

This outputs (if you enter “a” when asked for a key)

Enter key to be tested:


a
one
19
Chapter 1 Python Programming

or outputs (if you enter “x” when asked for a key)

Enter key to be tested:


x
none

We have seen what dictionaries can do. We now look at tuples.

Tuples
A tuple contains items which are immutable. The elements of a tuple can be separated
by commas within brackets or individual quoted elements separated by commas. They
are accessed in a similar way to arrays, whereby the elements are numbered from 0. In
this section, we will look at creating, concatenating, reading, deleting, and searching
through tuples.
For example, define two tuples called firsttup and secondttup:

firsttup = ('a', 'b', 'c', 1, 2, 3)


secondtup = “a”, “b”, 10,  25

The following code refers to the third element of firsttup:

firsttup[2]
gives
c

The following code refers to the third element of firsttup:

firsttup[3]
gives
1
secondtup = "a", "b", 10,  25

The following code refers to the second element of secondtup:

secondtup[1]
gives
b

20
Chapter 1 Python Programming

The following code refers to the third element of secondtup:

secondtup[2]
gives
10

We can also use negative indices to select from the end and work backward, for
example,

secondtup[-1]

which gives

25
secondtup[-2]

which gives

10

Tuples cannot be amended.


So if we had

firsttup = ('a', 'b' 'c', 1, 2, 3)


firsttup[3] = 9

we would get

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

Creating a Tuple
# An empty tuple
empty_tuple = ()
print (empty_tuple)
()

# Creating non-empty tuples

# One way of creation


tup = 'first', 'second'
21
Chapter 1 Python Programming

print(tup)
('first', 'second')

# Another for doing the same


tup = ('first', 'second')
print(tup)
('first', 'second')

Concatenating Two Tuples


# Code for concatenating 2 tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')

# Concatenating above two


print(tuple1 + tuple2)
(0, 1, 2, 3, 'first', 'second')

Creating Nested Tuples


# Code for creating nested tuples

tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple3 = (tuple1, tuple2)
print(tuple3)
gives
((0, 1, 2, 3), ('first', 'second'))

Creating Repeated Tuples


# Code to create a tuple with repetition

tuple3 = ('first',)*3
print(tuple3)
gives
('first', 'first', 'first')

22
Chapter 1 Python Programming

Converting a List or a String into a Tuple


# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]
print(tuple(list1))
(0, 1, 2)
print(tuple('first')) # string 'first'
('f', 'i', 'r', 's', 't')

Creating Single-Element Tuple


# Creating tuple with single element (note that we still require the comma)
t=(1,)
print(t)
gives
(1,)

Reading Tuple
# Reading from start (index starts at zero)
tup1=(2,3,4,5,6,7)
tup[3]
gives
5

# Reading from  end (index starts at -1)


tup1[-1]
gives
7

Searching Within a Tuple


# Search
tup1=(2,3,4,5,6,7)
print (6 in tup1) # this tests if 6 is contained in tup1
gives

23
Chapter 1 Python Programming

True
print (9 in tup1)
gives
False

Deleting a Tuple
# Deleting a complete Tuple
del tup1
print(tup1)
gives

NameError: name 'tup1' is not defined

Using Tuple to Create Variables


# define our tuple as
aTuple = (10, 20, 30, 40)
# Now we can assign each of its elements to separate variables
a, b, c, d = aTuple
print(a)
gives
10
print(b)
gives
20
print(c)
gives
30
print(d)
gives
40

We have covered definitions and uses of different types of variables in this section.
We will now look at the use of “if” statements.

24
Chapter 1 Python Programming

If Then Else


When a decision has to be made in your program to either do one operation or the other,
we use if statements.
These are fairly straightforward. Basically, we say

if (something is true)
        Perform a task

This is the basic form of if.


We can extend this to say

if (a condition  is true)
      Perform a task
else if it does not satisfy the above condition
      Perform a different task

Here is some Python code to demonstrate this:

number = 5
if number > 3:
   print('greater than 3')

number = 5
if number > 3:
   print('greater than 3')
else:
   print('not greater than 3')

Type in this code into a program and run it. It should come as no surprise that the
output is

greater than 3

You could modify the program so that you input the number to be tested, but don’t
forget that for this code you need number = int(input (“Enter number :”)) to enter a
number.
This section has shown the importance of “if” statements in programming. Now we
will look at loops.

25
Chapter 1 Python Programming

Loops (For and While)


When we were doing many calculations in a program, it could be a bit of a chore to do
a similar thing with, say, ten numbers. We could have done it by repeating similar code
ten times. We can make this a bit simpler by writing one piece of code but then looping
round the same piece of code ten times. This is called a “for loop.” We will also look at
“while” loops.

For Loops
Here is an example of how a for loop can help us.
The statement is

'for x in variable
     Carry out some code'

So if we have a variable as the following


forloopvar1 = [20, 13, 56, 9]
we can say

for x in forloopvar1: # go through forloop1 and place each element  in x


    print(x)  #this is the only instruction within the loop

outputs

20
13
56
9

The “range” instruction in Python has the general format


range(start, stop, step)
where
“start” is the start value of the index. Default is 0.
“stop” is 1 less than the last index to be used.
“step” is by how much the index is incremented. Default is 1.
Here is an example using the “range” instruction.
The program goes round the for loop starting with variables number and total set to 1.

26
Chapter 1 Python Programming

Within the loop, it multiplies the current value of the number by the running total. Then
it adds 1 to the number. So it is working out 1*2*3*4*5*6*7*8*9*10 or “10 factorial” (10!).

number = 1
total = 1
for x in range(10): ): #so here start is 0 (default), stop is 10-1, and
step is 1
         total = total * number
        number = number + 1
print(total)

This outputs

3628800

which you can check with your scientific calculator is 10 factorial.

for x in range(3, 6): # starts with 3 and ends with 6-1


    print(x)

This outputs

3
4
5

We can also have a list of values instead of a range, as shown in the next program.
This goes through the values and finds the index position of the value 46. We can see
that 46 is in position 9 (counting from 0).

forloopvar1 = [20, 13, 56, 9, 32, 19, 87, 51, 70, 46, 56]
count = 0
for x in forloopvar1:
     if x == 46:
           break
          count = count + 1
print(count)

This outputs

27
Chapter 1 Python Programming

While Loops
The logic of “while” loops is similar to our for loops.
Here, we say

'while x is true
      Carry out some code'

So we could have the following code which keeps adding 1 to count until count is no
longer less than 10. Within the loop, the user is asked to enter integers. These are added
to a total which is printed out at the end of the loop.

total = 0;
number = 0
# while loop goes round 10 times
while number < 10 :

      # ask the user to enter the integer number


      n = int(input('Enter a number: '))

      total = total + n
      number = number + 1
print('Total Sum is = ', total)

So if the user enters the number shown in the following, we get the total:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
Total Sum is =  55

We have seen the importance of loops in this section. Our next section looks at
switches.

28
Chapter 1 Python Programming

Switches
In C programming, there is an instruction used widely called “switch.” However, because
there is no switch statement in Python, this section will demonstrate some code that can
be included into your programs to perform the same function.
A switch jumps to a piece of code depending on the value of the variable it receives.
For instance, if you had to perform different code for people in their 30s to that for
people in their 40s and different to people in their 50s, we could have the following code.
Here we have the value in “option” which determines which code we jump to.
The code for this function is in the file aswitch3.py:

aswitch3.py
def switch(option):
     if option == 30:
                print("Code for people in their 30s")
     elif option == 40:
                print("Code for people in their 40s")

     elif option == 50:

               print("Code for people in their 50s")

    else:
        print("Incorrect option")
#main code in the program where you enter 30,40 or 50 and the function
'switch' is called which uses the appropriate number as shown.
optionentered = int(input("enter your option (30, 40 or 50 : ) "))
switch(optionentered)
running this program and entering '50' gives
enter your option : 50
Code for people in their 50s

This section has shown how to perform a switch in Python. We now move onto an
important library of functions in Python. This is called “numpy.”

29
Chapter 1 Python Programming

Arithmetic Operations Using Numpy


Numpy is a library of mathematical functions that can be included into your Python
program. It is useful in manipulating arrays, reading text files, and working with
mathematical formulas. Numpy can be installed in various ways. One way is using “pip”
from the command line as shown as follows:

pip install numpy

It is particularly useful in manipulating matrices (or arrays with extra dimensions).


The arrays we have looked at so far are one-dimensional arrays. In this section, we will
look at arrays with more dimensions. A one-dimensional array can also be called a “rank
1 array.”

onedarray = array('i', [10,20,30,40,50])

We import numpy into our program using “import numpy”, and we assign a link for
our program. Here we define the link as “np” so the full line of code is

import numpy as np

The numpy function “shape” returns the dimensions of the array. So if your array
was defined as

b = np.array([[1,2,3],[4,5,6]])

then the array would be a 2x3 matrix (two rows and three columns) as shown as follows:

[[1 2 3]
[4 5 6]]

So if you now type

print(b.shape)

you would get

(2, 3)

as the shape.
The code for this function is in the file numpy1.py:

30
Chapter 1 Python Programming

import numpy as np

a = np.array([1, 2, 3])   # Create a rank 1 array


print(type(a))            # Prints "<class 'numpy.ndarray'>"
print(a.shape)            # Prints "(3,)"
print(a[0], a[1], a[2])   # Prints "1 2 3"
a[0] = 5                  # Change an element of the array
print(a)                  # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

#1 2 3
#4 5 6
# reference elements counting from 0
# so b[1, 2] is row 1 (2nd row) column 2 (3rd column)
#so if you print b[1, 2] you get 6
print("b[1, 2] follows")
print(b[1, 2])

print(b.shape)                     # Prints "(2, 3)" 2 rows 3 columns


print(b[0, 0], b[0, 1], b[0, 2])   # Prints "1 2 3"
print(b[1, 0], b[1, 1], b[1, 2])   # Prints "4 5 6"
print(b[0, 0], b[0, 1], b[1, 0])   # Prints "1 2 4"

The normal mathematical representation of a matrix is as shown as follows:

This is what we have defined in the preceding code using the following line of code:

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array

Matrix arithmetic can be understood by looking at real-life examples. The following


are tables of three people working for a computer company. The first table shows how
many laptops and how many printers each person sells in a month.

31
Chapter 1 Python Programming

In Store Sale

Person     Laptops     Printers
Joe         4          5
Mary        6         7
Jen         7          9

The next table shows how many laptops and printers each person has sold online.
Online Sale

Person     Laptops     Printers
Joe           6           22
Mary          21          24
Jen           41          17

These tables can be represented by matrices as shown in the following. We add each
term in the first matrix to the corresponding term in the second matrix to give the totals
shown in the third matrix.

The next table shows the total of laptops and printers sold by each person:
Total/Overall Sale

Person    Laptops     Printers
Joe         10          27
Mary        27         31
Jen         48          26

If each person doubles their total sales the following month, we can just multiply
their current sales total by 2 as shown as follows:

32
Chapter 1 Python Programming

We now look at their totals for the first month and have another table containing the
cost of a laptop and the cost of a printer.
Total Sales

Person      Laptops     Printers           Cost/Item list with cost


Joe          10          27                    Laptop          200
Mary         27          31                   Printer          25
Jen          48          26

We can work out how much money each person makes for the company my
multiplying their total number of sales of a laptop by its cost. Then we multiply their total
number of sales of printers by its cost and then add these two together. The table and the
corresponding matrix representations of this are shown as follows:

             Sales Cost
Joe         10x200 + 27x25 = 2975
Mary        27x200 + 31x25 = 3875
Jen         48x200 + 26x25 = 4775

There is a rule when multiplying matrices. The number of columns in the first matrix
has to be equal to the number of rows of the second matrix.
So if we say that a matrix is 2x3 (two rows and three columns), then it can multiply a
3x2 or a 3x3 or a 3.4, etc. matrix. It cannot multiply a 2x3 or 2x4 or 4x2 or 4x3, etc.

In the multiplication in the preceding diagram, we see it is (3x2) x (2x1) producing a


(3x1) matrix.

33
Another Random Scribd Document
with Unrelated Content
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 DAMAGES - Except


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 non-profit
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 of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many small
donations ($1 to $5,000) are particularly important to maintaining tax
exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.

Project Gutenberg™ eBooks are often created from several printed


editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

Вам также может понравиться