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
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
com
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
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
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
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
Introduction�������������������������������������������������������������������������������������������������������������xv
iii
Table of Contents
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
v
Table of Contents
vi
Table of Contents
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))
<class 'int'>
a1=51
print(type(a1))
a1=51.6
print(type(a1))
2
Chapter 1 Python Programming
a1='51'
print(type(a1))
<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))
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.
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
v5 = v1 + v2
print(v5)
The result is
print(v1+v2)
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
4
Chapter 1 Python Programming
v11 = v2 ** 2
print(v11)
gives
16
v11 = v2 ** v1
print(v11)
gives
16
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'>
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()
print(vara)
6
Chapter 1 Python Programming
which prints
r5
You can also make the entry command clearer to the user by entering
7
Chapter 1 Python Programming
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:
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
varfloat1 = firstfloatarr[1]
print(varfloat1)
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
for x in myarr:
print(x)
9
Chapter 1 Python Programming
This outputs
2
13
3
5
7
11
for x in myarr:
print(x)
This outputs
3
5
7
11
Searching
The following code is in the file array5.py:
10
Chapter 1 Python Programming
This outputs
Updating an Array
The following code is in the file array6.py:
array6.py
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
for x in myarr:
print(x)
11
Chapter 1 Python Programming
This outputs
2
3
5
7
11
Enter an integer: 19
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
one = 1
two = 2
three = one + two
print(three)
#gives
3
12
Chapter 1 Python Programming
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
second= "second"
second[0]="q"
13
Chapter 1 Python Programming
we get
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:
print(firstlist[0])
gives
k
print(firstlist[1:3])
gives
[97, 56.42]
firstlist[3] = 'plj'
print(firstlist)
giving
['k', 97, 56.42, 'plj', 'bernard']
14
Chapter 1 Python Programming
del firstlist[3]
print(firstlist)
giving
['k', 97, 56.42, 'bernard']
firstlist.append(453.769)
print(firstlist)
giving
['k', 97, 56.42, 'bernard', 453.769]
This outputs
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 ]
This outputs
list1: [1, 2, 3, 4, 5]
updated list1: [1, 26, 3, 4, 5]
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
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
adict1[4] = 'four' # we want to add another value called 'four' whose key
is 4
print (adict1)
This outputs
adict1['dinsdale'] = 'doug'
print (adict1)
outputs
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
18
Chapter 1 Python Programming
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
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)
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[2]
gives
c
firsttup[3]
gives
1
secondtup = "a", "b", 10, 25
secondtup[1]
gives
b
20
Chapter 1 Python Programming
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
we would get
Creating a Tuple
# An empty tuple
empty_tuple = ()
print (empty_tuple)
()
print(tup)
('first', 'second')
tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple1 = (0, 1, 2, 3)
tuple2 = ('first', 'second')
tuple3 = (tuple1, tuple2)
print(tuple3)
gives
((0, 1, 2, 3), ('first', 'second'))
tuple3 = ('first',)*3
print(tuple3)
gives
('first', 'first', 'first')
22
Chapter 1 Python Programming
list1 = [0, 1, 2]
print(tuple(list1))
(0, 1, 2)
print(tuple('first')) # string 'first'
('f', 'i', 'r', 's', 't')
Reading Tuple
# Reading from start (index starts at zero)
tup1=(2,3,4,5,6,7)
tup[3]
gives
5
23
Chapter 1 Python Programming
True
print (9 in tup1)
gives
False
Deleting a Tuple
# Deleting a complete Tuple
del tup1
print(tup1)
gives
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 (something is true)
Perform a task
if (a condition is true)
Perform a task
else if it does not satisfy the above condition
Perform a different task
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
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'
outputs
20
13
56
9
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
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 :
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")
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
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]]
print(b.shape)
(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
#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])
This is what we have defined in the preceding code using the following line of code:
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
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.
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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
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.
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.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
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.
ebooknice.com