0% found this document useful (0 votes)
754 views128 pages

Value Added Course

Here are the key comparison operators in Python: Operator Name Example Result == Equal x == y True if x is equal to y != Not equal x != y True if x is not equal to y > Greater than x > y True if x is greater than y < Less than x < y True if x is less than y >= Greater than or x >= y True if x is greater than or equal to y equal <= Less than or x <= y True if x is less than or equal to y equal These operators usually return a boolean True or False value. Python Log

Uploaded by

Vignesh Waran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
754 views128 pages

Value Added Course

Here are the key comparison operators in Python: Operator Name Example Result == Equal x == y True if x is equal to y != Not equal x != y True if x is not equal to y > Greater than x > y True if x is greater than y < Less than x < y True if x is less than y >= Greater than or x >= y True if x is greater than or equal to y equal <= Less than or x <= y True if x is less than or equal to y equal These operators usually return a boolean True or False value. Python Log

Uploaded by

Vignesh Waran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 128

VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

VALUE ADDED CLASS

Machine programming with Python

V – Semester B.E

Organized by

Department of Electronics and Communication Engineering

1
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Department of ECE

VALUE ADDED COURSE


Batch: 2017-2021 Year:2018-19(EVEN SEM)
Date: 11.06.2019 to 13.06.2019 , 17.06.19,18.06.19 (5 Days ) FN: 09.00 am to 12.30pm
AN:02.00pm to 04.30pm
Course Name: Machine programming with Python
Resource Persons: Dr.A.Murugan, Mr.S.Meivel
Syllabus

Date & Session Course Contents


Day

11.06.2019 FN Introduction, first python program, variables

11.06.2019 AN operators, statements, loop, play with string, list and numbers
Variables, Python Operators, Arithmetic Operator, Comparison Operator, Assignment
12.06.2019 FN Operator, Bitwise Operator, Membership Operator, Identity Operator, If Statement, If
Else Statement,
Break & Continue Statement, For Loop, While, Loop, Home Assignment, String,
12.06.2019 AN Number, List, Dictionary, Function, Module, Exception File, Operation File, Reading
File, Writing file, Appending File.
13.06.2019 FN Testing and debugging

13.06.2019 AN Testing and debugging


Python Network Programming: Python Multithreaded Programming, Python CGI
17.06.2019 FN Programming, Python Database Connection, Python Meta programming.

Python Data Processing and Encoding, Python GUI Programming ,Create API
17.06.2019 AN
Documentation File in Python

18.06.2019 FN Projects : Hangman Game with Python and Working with Graphs in Python.

18.06.2019 AN Projects :Machine Learning using Python

2
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

11.06.2019
FORENOON

Syllabus: Introduction, first python program, variables

3
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
1. Introduction

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-orientated way or a functional way.

4
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Good to know

 The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is still
quite popular.
 In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated
Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly
useful when managing larger collections of Python files.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.

Online Debugger
https://www.onlinegdb.com/
https://www.w3schools.com/python/showpython.asp?filename=demo_helloworld

2. FIRST PYTHON PROGRAM


print ('Hello World')

3. VARIABLES
Example1:
n = 300
print(n)
300
n
300

5
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Example2:
n = 1000
print(n)
1000
n
1000

Example3:
a = b = c = 300
print(a, b, c)
300 300 300

Example4:
var = 23.5
print(var)
23.5

var = "Now I'm a string"


print(var)
Now I'm a string

Example5: n points to an integer object


print(n)
300
type(n)
<class 'int'>

Example6:
n = 300
m=n
id(n)
60127840
6
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
id(m)
60127840
m = 400
id(m)
60127872

Example7:
m = 300
n = 300
id(m)
60062304
id(n)
60062896

Example8:
name = "Bob"
>>> Age = 54
>>> has_W2 = True
>>> print(name, Age, has_W2)
Bob 54 True

Example9:
>>> age = 1
>>> Age = 2
>>> aGe = 3
>>> AGE = 4
>>> a_g_e = 5
>>> _age = 6
>>> age_ = 7
>>> _AGE_ = 8

>>> print(age, Age, aGe, AGE, a_g_e, _age, age_, _AGE_)


7
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
12345678

Example10:
>>> for = 3
SyntaxError: invalid syntax

Python Keywords

False def if raise


None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or

8
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

11.06.2019
AFTERNOON

Syllabus: Operators, statements, loop, play with string, list


and numbers

9
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

10
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

11
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

12
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

13
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:

Operator Description Example

is Returns true if both variables are the same object x is y

is not Returns true if both variables are not the same object x is not y

14
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

15
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits
fall off

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and
let the rightmost bits fall off

Python Statement

Instructions that a Python interpreter can execute are called statements. For example, a = 1is an assignment
statement. if statement, for statement, while statement etc. are other kinds of statements which will be
discussed later.

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a statement extend over
multiple lines with the line continuation character (\). For example:

a=1+2+3+\

4+5+6+\

7+8+9

16
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ] and
braces { }. For instance, we can implement the above multi-line statement as

a = (1 + 2 + 3 +

4+5+6+

7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For
example:

colors = ['red',

'blue',

'green']

We could also put multiple statements in a single line using semicolons, as follows

a = 1; b = 2; c = 3

LOOPS

Example1:

num = float(input("Enter a number: "))

if num >= 0:

17
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

if num == 0:

print("Zero")

else:

print("Positive number")

else:

print("Negative number")

Example2:
genre = ['pop', 'rock', 'jazz']

# iterate over the list using index


for i in range(len(genre)):
print("I like", genre[i])

I like pop

I like rock

I like jazz

Example3:
i=1
while i < 6:

18
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print(i)
i += 1

Example4:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

Example5:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Example6:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

Example7:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:

19
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
for y in fruits:
print(x, y)

STRINGS:

1. a = "Hello, World!"
print(a[1])
2. b = "Hello, World!"
print(b[2:5])
3. a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
4. a = "Hello, World!"
print(len(a))
5. a = "Hello, World!"
print(a.lower())
6. a = "Hello, World!"
print(a.upper())
7. a = "Hello, World!"
print(a.replace("H", "J"))
8. a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
9. print("Enter your name:")
x = input()
print("Hello, ", x)

LIST AND NUMBERS

Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

20
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type
for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or
security.

List

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

1. thislist = ["apple", "banana", "cherry"]


print(thislist)
2. thislist = ["apple", "banana", "cherry"]
print(thislist[1])
3. thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
4. thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
5. thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
6. thislist = ["apple", "banana", "cherry"]
print(len(thislist))
7. thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
8. thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

21
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
9. thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
10. thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
11. thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

List Methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

22
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

23
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

12.06.2019
FORENOON

Syllabus: Variables, Python Operators, Arithmetic Operator,


Comparison Operator, Assignment Operator, Bitwise Operator,
Membership Operator, Identity Operator, If Statement,
If Else Statement

24
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Add two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Find the Square Root

# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# uncomment to take the input from the user


#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Calculate the Area of a Triangle

# Python Program to find the area of triangle

a=5
b=6
c=7
25
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Solve Quadratic Equation

# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

a=1
b=5
c=6

# To take coefficient input from the users


# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


26
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

Enter a: 1

Enter b: 5

Enter c: 6

The solutions are (-3+0j) and (-2+0j)

Swap Two Variables

# Python program to swap two variables

# To take input from the user


# x = input('Enter value of x: ')
# y = input('Enter value of y: ')

x=5
y = 10

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))
27
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Generate a Random Number

# Program to generate a random number between 0 and 9

# import the random module


import random

print(random.randint(0,9))

28
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

12.06.2019
AFTERNOON

Syllabus: Break & Continue Statement, For Loop, While, Loop,


Home Assignment, String, Number, List, Dictionary, Function,
Module, Exception File, Operation File, Reading File, Writing
file, Appending File

29
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
1. Check if a Number is Odd or Even

num = int(input("Enter a number: "))

if (num % 2) == 0:

print("{0} is Even".format(num))

else:

print("{0} is Odd".format(num))

Enter a number: 43

43 is Odd

2. Check Leap Year

# Python program to check if the input year is a leap year or not

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))

30
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
else:
print("{0} is not a leap year".format(year))

2000 is a leap year

3. Find the Largest Among Three Numbers

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

31
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
4. Find the Factorial of a Number

# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# uncomment to take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

The factorial of 7 is 5040

5. Make a Simple Calculator

# Program make a simple calculator that can add, subtract, multiply and divide using functions

# This function adds two numbers

def add(x, y):

32
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

return x + y

# This function subtracts two numbers

def subtract(x, y):

return x - y

# This function multiplies two numbers

def multiply(x, y):

return x * y

# This function divides two numbers

def divide(x, y):

return x / y

print("Select operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

# Take input from the user

choice = input("Enter choice(1/2/3/4):")

33
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

if choice == '1':

print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':

print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':

print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':

print(num1,"/",num2,"=", divide(num1,num2))

else:

print("Invalid input")

Output

Select operation.

1.Add

2.Subtract

3.Multiply
34
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

4.Divide

Enter choice(1/2/3/4): 3

Enter first number: 15

Enter second number: 14

15 * 14 = 210

35
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

13.06.2019

Testing and debugging

1.
print ("Hello World!")
36
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

**************************************************************************************

2.
thetext = input("Enter some text ")
print ("This is what you entered:")
print (thetext)

**************************************************************************************
3.
# Note that \n within quote marks forces a new line to be printed
thetext = input("Enter some text\n")
print ("This is what you entered:")
print (thetext)

**************************************************************************************
4.
prompt = "Enter a some text "
thetext = input(prompt)
print ("This is what you entered:")
print (thetext)

**************************************************************************************
5.
total = 0.0
number1=float(input("Enter the first number: "))
total = total + number1
number2=float(input("Enter the second number: "))

37
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
total = total + number2
number3=float(input("Enter the third number: "))
total = total + number3
average = total / 3
print ("The average is " + str(average))

**************************************************************************************
6.
number1=float(input("Enter the first number: "))
number2=float(input("Enter the second number: "))
number3=float(input("Enter the third number: "))
total = number1 + number2 + number3
average = total / 3
print ("The average is: ")
print (average)

**************************************************************************************
7.
total = 0.0
count = 0
while count < 3:
number=float(input("Enter a number: "))
count = count + 1
total = total + number
average = total / 3
print ("The average is " + str(average))

**************************************************************************************
8.
total = 10
38
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

**************************************************************************************
9.
total = 10
print (total)

**************************************************************************************
10.
total = 10
print (total)
print (type (total))

**************************************************************************************
11.
print (2 + 4)
print (6 - 4)
print (6 * 3)
print (6 / 3)
print (6 % 3)
print (6 // 3) # floor division: always truncates fractional remainders
print (-5)
print (3**2) # three to the power of 2

**************************************************************************************
12.
print (2.0 + 4.0)
print (6.0 - 4.0)
print (6.0 * 3.0)
print (6.0 / 3.0)
print (6.0 % 3.0)
print (6.0 // 3.0) # floor division: always truncates fractional remainders
print (-5.0)
39
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print (3.0**2.0) # three to the power of 2

**************************************************************************************
13,
# mixing data types in expressions
# mixed type expressions are "converted up"
# converted up means to take the data type with the greater storage
# float has greater storage (8 bytes) than a regular int (4 bytes)
print (2 + 4.0)
print (6 - 4.0)
print (6 * 3.0)
print (6 / 3.0)
print (6 % 3.0)
print (6 // 3.0) # floor division: always truncates fractional remainders
print (-5.0)
print (3**2.0) # three to the power of 2

**************************************************************************************
14.

# these are Boolean expressions which result in a value of


# true or false
# Note that Python stores true as integer 1, and false as integer 0
# but outputs 'true' or 'false' from print statements
print (7 > 10)
print (4 < 16)
print (4 == 4)
print (4 <= 4)
print (4 >= 4)
print (4 != 4)

**************************************************************************************
40
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
15.

# these are string objects


print ("Hello out there")
print ('Hello')
print ("Where's the spam?")
print ('x')

**************************************************************************************
16.

# these are string assignments


a = "Hello out there"
print (a)
b = 'Hello'
print (b)
c = "Where's the spam?"
print (c)
d = 'x'
print (d)

**************************************************************************************
17.

a = 'Hello out there'


b = "Where's the spam?"
c=a+b
print (c)

**************************************************************************************
18.

41
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
a = 'Hello out there'
b = "Where's the spam?"
c=a+b
print (c)
#d = c + 10
# you cannot concatenate a string and an integer
# you must convert the integer to a string first:
d = c + str(10)
print (d)

**************************************************************************************
19.

a = "10"
b = '99'
c=a+b
print (c)
print (type(c))
c = int(c)
print (c)
print (type(c))

**************************************************************************************
20.

# How to round up a floating point number


# to the nearest integer

x = 1.6
print (x)
42
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
x = round(x)
print (x)
#compare the above with
x = 1.6
x = int(x)
print (x)

**************************************************************************************
21.

# Purpose: Example: outputting strings and numbers


# in a single print statement
# using string formatting.
firstname = "Anne"
lastname = 'Dawson'
print("My fullname is %s %s" % (firstname,lastname))
print()

# printing decimal or integer numbers in a string


x = 20
y = 75
print('The sum of %d and %d is %d' % (x, y, x + y))
print()

# printing decimal or integer numbers in a string


x = 20
y = 75
print('The sum of %i and %i is %i' % (x, y, x + y))
print()

# printing floating point numbers in a string


x = 20.5126
43
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
y = 15.2697
print('The sum of %f and %f is %f' % (x, y, x + y))
print()

# printing floating point numbers to 2 decimal places


x = 20.512
y = 15.269
print('The sum of %0.2f and %0.2f is %0.2f' % (x, y, x + y))
print()

# printing floating point numbers to 3 decimal places


x = 20.512
y = 15.269
print('The sum of %0.3f and %0.3f is %0.3f' % (x, y, x + y))
print()

for number in range(17):


print("The decimal number %d in hexadecimal is %x" % (number,number))

**************************************************************************************
22.
# Purpose: Example: how to repeat a program at the user's request
print ("This is the start of the program")
answer = 'y'
while (answer == 'y' or answer == 'Y'):
print ("This is a statement from within the while loop")
print ("This is another statement from within the while loop")
answer = input("Do you want to run this program again? y/n")
print ("Goodbye!")

**************************************************************************************
23.
44
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Purpose: Example: how to use a loop within a loop
# a nested while loop

print ("This is the start of the program")

x=1
while (x < 6):
print () # prints a new line
print ("x = " + str(x),) # the , forces printing of the next item
# to be on the same line
x=x+1
y=1
while (y < 6):
print ("y = " + str(y),) # the , forces printing on the same line
y=y+1

'''
Notice that with a loop repeating 5 times,
***within*** a loop that repeats 5 times
means that you can control 25 processes.
'''
**************************************************************************************
24.
# Purpose: Example: how to use a loop within a loop
# a nested while loop

print ("This is the start of the program")

x=1
while (x < 6):
print() # prints a new line
45
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print ("x = " + str(x)) # the , forces printing of the next item
# to be on the same line
x=x+1
y=1
while (y < 6):
print ("y = " + str(y),) # the , forces printing on the same line
y=y+1
z=1
while (z < 6):
print ("z = " + str(z),) # the , forces printing on the same line
z=z+1
print() # prints a new line

**************************************************************************************

25.
# Purpose: Example: how to use a loop within a loop
# a nested for loop

print ("This is the start of the program")

for i in range (1,6):


for j in range (1,6):
print ("i: " + str(i) + " j: " + str(j) )
print()
'''
Notice that with a loop repeating 5 times,
***within*** a loop that repeats 5 times
means that you can control 25 processes.
'''
**************************************************************************************
26.
46
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Purpose: Example: how to use a loop within a loop
# a nested for loop

print ("This is the start of the program")

for i in range (1,6):


for j in range (1,6):
for k in range (1,6):
print ("i: " + str(i) + " j: " + str(j) + " k: " + str(k))
print()
'''
Notice that with a loop repeating 5 times,
***within*** a loop that repeats 5 times
***within*** a loop that repeats 5 times
means that you can control 125 processes.
'''
**************************************************************************************
27.
# Purpose: Example: using the built-in square root function math.sqrt
# To use any math function, you have to include the statement:
# import math
# in your program - usually at the top, but can be anywhere.

import math
print (math.sqrt(16))
print (math.sqrt(16.5))
x = 144
print (math.sqrt(x))

**************************************************************************************
28.
# File: 06-02.py
47
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Purpose: Example: using the dir function to list out the names
# of available functions in the math module

import math
print (math)
print (dir(math))

**************************************************************************************
29.
# Purpose: Example: showing functions which have no return statement

def greeting():
print("Hello")

def many_greetings(n):
for i in range(n):
print("Hello Again!")

def many_greetings_with_name(n,the_name):
for i in range(n):
print("Hello Again" + the_name + "!")

greeting()
greeting()
greeting()

print() # prints a blank line

for i in range(2):
greeting()

print() # prints a blank line


48
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

many_greetings(4)

print() # prints a blank line

x = int(input("How many greetings do you want?: "))


many_greetings_with_name(x," Anne")

**************************************************************************************

30.
# Purpose: Example: using a programmer-defined function

# start of function definition


def cube( y ):
return y * y * y
# end of function definition

# prints the cube of numbers 1 to 5


for x in range(1,6):
print (cube(x))

# the last value of x is 5


print ("last value of x is:",x)

**************************************************************************************
31.
# Purpose: Example: using two programmer-defined functions

def cube( y ):
return y * y * y

49
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
def doubleIt ( z ):
return 2 * z

print ("1 to 5 cubed")


for x in range(1,6):
print (cube(x),)
print()
print()

print ("1 to 5 doubled")


for x in range(1,6):
print (doubleIt(x),)

**************************************************************************************
32.
# File: myFunctions.py
# Purpose: two programmer-defined functions
def cube( y ):
return y * y * y

def doubleIt ( z ):
return 2 * z

**************************************************************************************
33.
# Purpose: Example: importing programmer-defined functions
# from its own module file

# IMPORTANT: myFunctions.py should be in the same folder as this file

import myFunctions

50
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print ("1 to 5 cubed")
for x in range(1,6):
print (myFunctions.cube(x),)
print()
print()

print ("1 to 5 doubled" )


for x in range(1,6):
print (myFunctions.doubleIt(x),)
**************************************************************************************
34.
# Purpose: Example: function with no return statement
def times(x):
for i in range(1,11):
print ("%d x %d = %d" % (i, x, i * x))

print ("This is the 1 times tables:")


times(1)

print ("This is the 2 times tables:")


times(2)

**************************************************************************************
35.
# Purpose: Example: a function with two return statements

def division(x,y):
if (y == 0):
print ("division by zero not allowed")
return
else:
print (" returning %f divided by %f " % (x, y))
51
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
return x / y

print (" 5.0 / 2 returns:")


result = division( 5.0 , 2 )
print (result)

print (" 5.0 / 0 returns:")


result = division( 5.0 , 0 )
print (result)

**************************************************************************************
36.
# Purpose: Example: a function with no arguments

def greeting():
print ("Hello out there!")

greeting()
greeting()
greeting()

**************************************************************************************
37.
# Purpose: Example: a program with a Boolean function

def isPositive(x):
if (x >= 0):
return 1 # 1 is true
else:
return 0 # 0 is false

x = float(input("Enter a positive or negative number: "))


52
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
result = isPositive(x)
print (result)
print (isPositive(x))

**************************************************************************************
38.
# Purpose: Example: a polymorphic function

def doubleIt(x):
return (2 * x)

y=3
print (doubleIt(y))
z = "Spam "
print (doubleIt(z))

**************************************************************************************
39.
# Purpose: Example: the scope of a variable
# program demonstrating the scope of a variable
# (i.e. where it can be used)

def my_function(n):
print("n in function: ",n)
print("number in function: ",number)
number = 10
print("number in main program: ",number)
my_function(number)
#print(n)
**************************************************************************************
40.
# Purpose: Demonstrates the use of Python functions
53
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

def pause():
input("\n\nPress any key to continue...\n\n")

def quitMessage():
print ("Thank you for using this program")
print ("Goodbye")

def printThreeLines():
for i in range(1,4):
print ('this is line ' + str(i))

def printNineLines():
for i in range(1,4):
printThreeLines()

def startMessage():
print ("This program demonstrates the use of Python functions")
pause()

def blank_Line():
print()

def clearScreen():
for i in range(1,26):
blank_Line()

startMessage()
clearScreen()
print ("Testing this program")
printNineLines()
pause()
54
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
clearScreen()
printNineLines()
blank_Line()
printNineLines()
pause()
clearScreen()
quitMessage()

**************************************************************************************
41.
# Purpose: Example: creating and using a Python list

result = [0,0,0,0,0,0,0,0]
print (result)
result[0] = 75
result[1] = 90
result[4] = 72
print (result)
print (result[0])
print (result[1])
print (result[2])
print (result[3])
print (result[4])
print (result[5])
print (result[6])
print (result[7])
**************************************************************************************

42.
# Purpose: Example: creating and printing an empty list
55
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
list1 = []
print (list1)
# the following statement would generate an error
#print (list1[0])
**************************************************************************************
43.
# Purpose: Example: appending to an empty list

list1 = []
print (list1)
list1.append(67)
print (list1[0])
list1.append("spam")
print (list1)
print (list1[0])
print (list1[1])
# the following statement would generate an out-of-range error
#print (list1[2])
**************************************************************************************
44.
# Purpose: Example: a list of lists
list1 = [1,2,3]
print (list1)
list2 = [4,5,6]
print (list2)
list3=[list1,list2]
print (list3)
print (list3[0])
print (list3[1])
**************************************************************************************
45.
# Purpose: Example: accessing the last item in a list
56
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

list1 = [1,2,3,6,7,8,9,10]
print (list1)
print (list1[0])
print (list1[1])
print (list1[-1])
print (list1[-2])
**************************************************************************************
46.
# Purpose: Example: deleting items from a list

list1 = [1,2,3,4,5,6,7,8,9,10]
print (list1)
del list1[0]
del list1[-1]
print (list1)
**************************************************************************************
47.
# File: 07-07.py
# Purpose: Example: repeating lists
list1 = [1,2,3]
print (list1)
print (list1 * 3)
print (list1)
list1 = list1 * 2
print (list1)

**************************************************************************************

48.
# File: 07-08.py
57
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Purpose: Example: concatenating lists

list1 = [1,2,3]
print (list1)
list2 = [4,5,6]
print (list2)
list1 = list1 + list2
print (list1)
list1 = list1 + list1
print (list1)

**************************************************************************************
49.
# Purpose: Example: ist indexing
list1 = ["Anne", "Dawson", 666]
print (list1[0], list1[2])

**************************************************************************************
# File: 07-10.py
# Purpose: Example: list indexing

list1 = [2,4,6,8,10,12,14,16,18,20]
print (list1[0:1],list1[5:7])

**************************************************************************************
50.
# Purpose: Example: finding the length of a list

list1 = ["Anne","was",'here','testing',1,2,3]
list2 = [1,2,3,4]
list3 = []
58
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print (len(list1), len(list2), len(list3))
**************************************************************************************
51.
# Purpose: Example: list iteration

list2 = [1,2,3,"Spam",4,5]
for i in list2:
print (i, end=" ")

52.
# Purpose: Example: list membership

list2 = [1,2,3,"Spam",4,5]
print ("Spam" in list2)

**************************************************************************************
53.
# Purpose: Example: a selection of list methods

list2 = ["B","C","A"]
print (list2)
list2.extend(["X","Y"]) # extends the list
print (list2)
list2.pop() # removes last item from the list
print (list2)
list2.pop()
print (list2)
list2.reverse() # reverses the order of the items in the list
print (list2)
list2.append("S")
print (list2)
59
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
list2.sort() # sorts the list into ascending order
print (list2)
list2.reverse() # reverses the order of the items in the list
print (list2)

**************************************************************************************
54.
# Purpose: Example: a 2D list
tictactoe = [[1,2,3], [4,5,6], [7,8,9]]
print (tictactoe[0])
print (tictactoe[1])
print (tictactoe[2])
print()

row = 1
column = 0
print ("row " + str(row) + " column " + str(column) + " has value")
print (tictactoe[row][column])

row = 2
column = 2
print ("row " + str(row) + " column " + str(column) + " has value")
print (tictactoe[row][column])

print()
print()
tictactoe[2][2] = 0
print ("After changing the value at row 2 and column 2 to 0: ")
print()
print (tictactoe[0])
print (tictactoe[1])
print (tictactoe[2])
60
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

**************************************************************************************
55.
# Purpose: Differences in range() with Python 2 and Python 3

'''
>>>
range(0, 10)
<class 'range'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'>
>>>
'''

x = range(10)
print(x)
print(type(x))
x = list(range(10))
print(x)
print(type(x))
**************************************************************************************
56.
# Purpose: Example: strings
print ('Anne was here')
print ("9396633")
# Note that you can print a string over several lines
# if you contain it within triple quotes marks:
print ('''Anne was here on Saturday 30th October 2004''')

**************************************************************************************
57.
# Purpose: Example: using an apostrophe within a string
61
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# and using double quote marks within a string
print ("This is Anne's spam")
print ("This is Anne's spam and these are Jake's eggs" )

# You can also print a " within a string enclosed in single quotes:

print ('Here is a double quote ", and "more"')

**************************************************************************************
58.

# Purpose: Example: multiplying numbers and


# multiplying strings

print (3 * 4)
print (30 * 4)
print ("3" * 4)
print ("30" * 4)
**************************************************************************************
59.
# Purpose: Example: string concatenation
print ("Anne " + "was " + ("here " * 3))

**************************************************************************************
60.
# Purpose: Example: string indexing
s1 = "Anne Dawson"
print (s1[0],s1[5])

**************************************************************************************
61.
# Purpose: Example: string slicing
62
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

s1 = "Anne Dawson"
print (s1[0:1],s1[5:7])
print (s1[6:9])

**************************************************************************************
62.
# Purpose: Example: finding the length of a string
s1 = "Anne"
s2 = "Dawson"
s3 = ""
print (len(s1),end=" ")
print (len(s2),end=" ")
print (len(s3))

**************************************************************************************
63.
# Purpose: Example: the %s string formatting code

print ('Python is a %s language.' % 'great')

**************************************************************************************
64.
# Purpose: Example: finding a string within a string
s1 = 'spamandeggs'
x = s1.find('and')
print (x)

**************************************************************************************
65.
# Purpose: Example: finding a string within a string
63
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
s1 = 'spam and eggs'
s1.replace('and','without')
print (s1)
# the above shows that strings are immutable (cannot change)
s2 = s1.replace('and','without')
print (s2)

**************************************************************************************
66.
# Purpose: Example: escape sequences within a string

s = 'one\ntwo\tthree'
print (s)

**************************************************************************************
67.
# Purpose: Example: an escape sequence counts as one character

s = 'one\ntwo\tthree'
print (s)
print (len(s))

**************************************************************************************
68.
# Purpose: Example: iteration and membership with strings

s = 'Anne was here'


for c in s:
print (c, end=" ")
print ('w' in s, end=" ")
print (' ' in s, end=" ")
print ('x' in s)
64
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
**************************************************************************************
69.
# Demonstration of printing Unicode characters
# For explanation, see:
# \u2588 is a Full Block which can be used to build up a solid square
str1 = "Hello\u2588out there" # solid block within text
print (str1)
str1 = '\u2588\u2588' #two full block characters
print (str1)
print()
print()
print ("two lines of two full blocks")
print (str1)
print (str1)
print()
print()
# Note: a space is \u0020
print ('two lines of two full blocks, two spaces, two full blocks:')
str1 = '\u2588\u2588\u2588\u2588\u0020\u0020\u0020\u0020\u2588\u2588\u2588\u2588'
print (str1)
print (str1)
print()
print()
print ('two lines of two full blocks, the number 17 and two full blocks:')
str1 = '\u2588\u2588\u2588\u2588\u0020\u0020' + '17' + '\u2588\u2588\u2588\u2588'
print (str1)
str1 = '\u2588\u2588\u2588\u2588\u0020\u0020\u0020\u0020\u2588\u2588\u2588\u2588'
print (str1)

**************************************************************************************
70.
# Purpose: Example: a program which uses a file
65
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
file1 = open('C:\\temp\\file1.txt','r')
# the line above opens C:\temp\file1.txt for reading
string = file1.readline()
print (string)

**************************************************************************************
71.
# Purpose: Example: a program which uses a file

file1 = open("C:\\temp\\tester2.txt","w")
print (file1) # prints out details about the file
file1.write("Today is Monday\n")
file1.write("Tomorrow is Tuesday")
file1.close()

**************************************************************************************
72.

# Purpose: Example: a program which uses a file

file2 = open("C:\\temp\\tester2.txt","r")
print (file2) # prints out details about the file
string1 = file2.read()
print (string1)
file2.close()
file2 = open("C:\\temp\\tester2.txt","r")
string1 = file2.read(5)
print (string1)
string1 = file2.read(5)
print (string1)
string1 = file2.read(5)
66
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print (string1)
file2.close()

**************************************************************************************
73.
# Purpose: Example: a program which uses a file
def copyFile(oldFile, newFile):
f1 = open(oldFile, "r")
f2 = open(newFile, "w")
while 1:
text = f1.read(50)
if text == "":
break
f2.write(text)
f1.close()
f2.close()
return

filecopy = "C:\\temp\\tester2copy.txt" #this file will be created


fileold = "C:\\temp\\tester2.txt" # existing file
copyFile(fileold, filecopy)

**************************************************************************************
74.
# Purpose: Example: a program which uses a file

filename = input('Enter a file name: ')


try:
f = open (filename, "r")
except:
print ('There is no file named', filename )

67
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
**************************************************************************************
75.
# Purpose: Example: sequential search of a list

list1 = [11,27,36,44,51,22,65,1,78]
numbertofind = int(input("Enter a number\n"))
found = 0
for i in list1:
if numbertofind == i:
print (numbertofind, " at index: ",list1.index(numbertofind))
found = 1
if found == 0:
print ("Number not found")

**************************************************************************************
76.
# Purpose: Example: sequential search of a list

mylist = [10,11,3,4,55,12,23,14,16]
n = len(mylist)
print (n)
for i in range(n):
print (mylist[i], end=" ")
search = int(input("\nPlease enter a number to search for: "))
print (search)
found = False
for i in range(n):
if mylist[i] == search:
found = True
index = i
print()
if found == True:
68
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print (str(search) + " found at index " + str(index))
else:
print (str(search) + " not found")
**************************************************************************************
77.
# Purpose: Sequential (also known as linear) search
# Checking the number of steps to find the target

# Date: Wednesday 16th March 2016, 10:19 PT

list1 = [11,27,36,44,51,22,65,1,78]
numbertofind = int(input("Enter a number\n"))
found = 0
steps = 0
for i in list1:
steps = steps + 1
if numbertofind == i:
print (numbertofind, " at index: ",list1.index(numbertofind))
found = 1
if found == 1:
break
if found == 0:
print ("Number not found")
print("Steps taken to find the number: ",steps)

**************************************************************************************
78.
# File: binarysearch.py

def binarysearch(mylist,target):
left = 0
right = len(mylist)
69
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
while (left < right-1):
mid = int((right+left)/2)
number_at_mid = mylist[mid]
if (target == number_at_mid):
return True
if (target < number_at_mid):
right = mid
else:
left = mid
if (left >= right):
return False
if ( (left == (right-1)) and (mylist[left] == target) ):
return True
return False

n = int(input("Enter number of numbers to input: "))


count = 0
mylist = []
while (count < n):
count = count + 1
x = int(input("Enter value for number " + str(count) + ": "))
mylist.append(x)
print (mylist)
mylist.sort()
print (mylist)

repeat = "y"
while (repeat == "y" or repeat == "Y"):
mytarget = int(input("Enter number to find: "))
if binarysearch(mylist,mytarget):
print ("Found!")
else:
70
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print ("NOT Found!")
repeat = input("Another search? (y/n)")
print ("\n\nThank you for using this program")

**************************************************************************************
79.
# Purpose: Binary search -
# checking the number of steps to find the target

def binarysearch(mylist,target):
left = 0
right = len(mylist)
steps = 0
while (left < right-1):
steps = steps + 1
mid = int((right+left)/2)
number_at_mid = mylist[mid]
print("Steps taken to find the number: ",steps)
if (target == number_at_mid):
return True
if (target < number_at_mid):
right = mid
else:
left = mid
if (left >= right):
return False
if ( (left == (right-1)) and (mylist[left] == target) ):
return True

return False

mylist = [11,27,36,44,51,22,65,1,78]
71
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print (mylist)
mylist.sort()
print (mylist)

repeat = "y"
while (repeat == "y" or repeat == "Y"):
mytarget = int(input("Enter number to find: "))
if binarysearch(mylist,mytarget):
print ("Found!")
else:
print ("NOT Found!")
repeat = input("Another search? (y/n)")
print ("\n\nThank you for using this program")
**************************************************************************************
80.
# Purpose: to create a list of 10,000 unique random integers
# in the range 1 through 20,000
import random
numberslist = []
number = 0
while number < 10000:
value = random.randint(1,20000)
if not(value in numberslist):
numberslist.append(value)
number = number + 1
print(numberslist)

**************************************************************************************
81.
# Purpose: Example: a program which demonstrates a bubble sort on
72
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# a list of 10 random integers

import random

# define the bubble sort function


def sort(values):
length = len(values)
for time in range(0, length-1):
for position in range(0, (length-time-1)):
if values[position] > values[position+1]:
temp = values[position]
values[position] = values[position+1]
values[position+1] = temp

# generate a list of ten random numbers


numbers = []
number = 0
while number < 10:
value = random.randint(1,100)
if not(value in numbers):
numbers.append(value)
number = number + 1

# show unsorted list, sort the list, and show sorted list
print ("Before:", numbers)
sort(numbers)
print ("After :", numbers)

**************************************************************************************
82.
# Purpose: Example: a program which demonstrates a bubble sort on
73
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# a list of 10 random integers, counting the steps taken to sort the list
import random
# define the bubble sort function
def sort(values):
steps = 0
length = len(values)
for time in range(0, length-1):
for position in range(0, (length-time-1)):
if values[position] > values[position+1]:
temp = values[position]
values[position] = values[position+1]
values[position+1] = temp
steps = steps + 1
print("Steps taken to sort the list: ",steps)
# generate a list of ten random numbers
numbers = []
number = 0
while number < 10:
value = random.randint(1,100)
if not(value in numbers):
numbers.append(value)
number = number + 1
# show unsorted list, sort the list, and show sorted list
print ("Before:", numbers)
sort(numbers)
print ("After :", numbers)

**************************************************************************************
83.
# Purpose: Example: a recursive function
74
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

print (" 5! has a value of: ",)


result = factorial(5)
print (result)

print (" 4! has a value of:",)


result = factorial(4)
print (result)

**************************************************************************************
84.
# Purpose: OOP Example: How to create objects of the Person class and how to inspect the state of those
objects.
class Person():
'''Instantiates a Person object with given name. '''
def __init__(self, first_name, last_name):
'''Initializes private instance variables _firstname and _lastname. '''
self._firstname = first_name
self._lastname = last_name

def __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname

print(Person.__doc__) # prints the docstring for the class


person1 = Person("Anne","Dawson")
75
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
person2 = Person("Tom","Lee")
print(person1)
print(person2)

**************************************************************************************
85.
# Purpose: OOP Example: How to use accessor methods
class Person():
'''Instantiates a Person object with given name. '''
def __init__(self, first_name, last_name):
'''Initializes private instance variables _firstname and _lastname. '''
self._firstname = first_name
self._lastname = last_name

def __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname

def getFirstname(self): # accessor method


'''Returns the instance variable _firstname. '''
return self._firstname

def getLastname(self): # accessor method


'''Returns the instance variable _lastname. '''
return self._lastname

print(Person.__doc__) # prints the docstring for the class


person1 = Person("Anne","Dawson")
person2 = Person("Tom","Lee")
print(person1) # calls the __str__ method implicitly on person1 object
print(person2) # calls the __str__ method implicitly on person2 object
print(Person.getFirstname.__doc__) # prints the docstring for the getFirstname method
76
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print(person1.getFirstname())
print(person1.getLastname())
print(person2.getFirstname())
print(person2.getLastname())

**************************************************************************************
86.
# Purpose: OOP Example: How to use accessor and mutator methods

class Person():
'''Instantiates a Person object with given name. '''
def __init__(self, first_name, last_name):
'''Initializes private instance variables _firstname and _lastname. '''
self._firstname = first_name
self._lastname = last_name

def __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname

def getFirstname(self): # accessor method


'''Returns the instance variable _firstname. '''
return self._firstname

def getLastname(self): # accessor method


'''Returns the instance variable _lastname. '''
return self._lastname
def setFirstname(self,newFirstname): # mutator method
'''Assign a value to the instance variable _firstname. '''
self._firstname = newFirstname

def setLastname(self,newLastname): # mutator method


77
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
'''Assign a value to the instance variable _lastname. '''
self._lastname = newLastname
print(Person.__doc__) # prints the docstring for the class
person1 = Person("Anne","Dawson")
person2 = Person("Tom","Lee")
print(person1) # calls the __str__ method implicitly on person1 object
print(person2) # calls the __str__ method implicitly on person2 object
print(Person.getFirstname.__doc__) # prints the docstring for the getFirstname method
print(person1.getFirstname())
print(person1.getLastname())
print(person2.getFirstname())
print(person2.getLastname())
person1.setFirstname("Annie")
print(person1.getFirstname())
**************************************************************************************
87.
# Purpose: OOP Example: How to use accessor, mutator and regular methods

class Person():
'''Instantiates a Person object with given name. '''
def __init__(self, first_name, last_name):
'''Initializes private instance variables _firstname and _lastname. '''
self._firstname = first_name
self._lastname = last_name

def __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname

def getFirstname(self): # accessor method


'''Returns the instance variable _firstname. '''
return self._firstname
78
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

def getLastname(self): # accessor method


'''Returns the instance variable _lastname. '''
return self._lastname

def setFirstname(self,newFirstname): # mutator method


'''Assign a value to the instance variable _firstname. '''
self._firstname = newFirstname

def setLastname(self,newLastname): # mutator method


'''Assign a value to the instance variable _lastname. '''
self._lastname = newLastname

def reverseName(self): # method


'''Reverses the full name '''
return self._lastname + " " + self._firstname

print(Person.__doc__) # prints the docstring for the class


person1 = Person("Anne","Dawson")
person2 = Person("Tom","Lee")
print(person1) # calls the __str__ method implicitly on person1 object
print(person2) # calls the __str__ method implicitly on person2 object
print(Person.getFirstname.__doc__) # prints the docstring for the getFirstname method
print(person1.getFirstname())
print(person1.getLastname())
print(person2.getFirstname())
print(person2.getLastname())
person1.setFirstname("Annie")
print(person1.getFirstname())
print(person1.reverseName())
**************************************************************************************
88.
79
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
# Purpose: OOP Example: Student class inherits from Person class
class Person():
'''Instantiates a Person object with given name. '''
def __init__(self, first_name, last_name):
'''Initializes private instance variables _firstname and _lastname. '''
self._firstname = first_name
self._lastname = last_name

def __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname

def getFirstname(self): # accessor method


'''Returns the instance variable _firstname. '''
return self._firstname

def getLastname(self): # accessor method


'''Returns the instance variable _lastname. '''
return self._lastname

def setFirstname(self,newFirstname): # mutator method


'''Assign a value to the instance variable _firstname. '''
self._firstname = newFirstname

def setLastname(self,newLastname): # mutator method


'''Assign a value to the instance variable _lastname. '''
self._lastname = newLastname

def reverseName(self): # method


'''Reverses the full name '''
return self._lastname + " " + self._firstname

80
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
class Student(Person):
'''Instantiates a Student object with given name. '''
def __init__(self, first_name, last_name, student_number=0, G_P_A=0):
'''Initializes private instance variables _firstname, _lastname, _SN and _GPA. '''
super().__init__(first_name, last_name) # import base's parameters
'''Initializes private instance variables _firstname and _lastname. '''
self._SN = student_number
self._GPA = G_P_A

def __str__(self):
'''Returns the state of the Student object. '''
return self._firstname + " " + self._lastname + " " + str(self._SN) + " " + str(self._GPA)

def getSN(self): # accessor method


'''Returns the instance variable _SN. '''
return self._SN

def getGPA(self): # accessor method


'''Returns the instance variable _GPA. '''
return self._GPA

def setSN(self,newSN): # mutator method


'''Assign a value to the instance variable _SN. '''
self._SN = newSN

def setGPA(self,newGPA): # mutator method


'''Assign a value to the instance variable _GPA. '''
self._GPA = newGPA

def reverseName(self): # method


'''Reverses the full name '''
return self._lastname + " " + self._firstname + " " + str(self._GPA)
81
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print(Student.__doc__) # prints the docstring for the class
student1 = Student("Carol","Wong")
student2 = Student("Bill","Wang")
print(student1) # calls the __str__ method implicitly on person1 object
print(student2) # calls the __str__ method implicitly on person2 object
print(Student.getFirstname.__doc__) # prints the docstring for the getFirstname method
print(Student.getGPA.__doc__) # prints the docstring for the getGPA method
print(student1.getFirstname())
print(student1.getLastname())
print(student2.getFirstname())
print(student2.getLastname())
student1.setFirstname("Louisa")
print(student1.getFirstname())
print(student1.reverseName()) # The reverseName method of the Student class
# overrides the same method of the Parent class.
# This is an example of polymorphism

**************************************************************************************

82
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

17.06.2019
FORENOON

SYLLABUS: Python Network Programming: Python Multithreaded


Programming, Python CGI Programming, Python Database
Connection, Python Meta programming.

PYTHON MULTITHREADED PROGRAMMING

83
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
When programmers run a simple program of Python, execution starts at the first line and proceeds line-by-
line. Also, functions and loops may be the reason for program execution to jump but it is relatively easy to see
its working procedures and which line will be next executed. Programmers can put their fingers and can trace
the lines of codes that will be executed; this is called single-threaded programming.

However, in case of multi-threaded programming, it's like putting a second finger on your program. Both the
fingers move the same way and will be executed simultaneously.

What are Threads?

It is the execution of a tiny sequence of program instruction that can be managed independently and is a
distinctive part of operating system. Modern OS manage multiple programs using a time-sharing technique. In
Python, there are two different kinds of thread. These are:

 Kernel Threads

 User-space threads or User threads

Why Use Thread

Thread plays a significant role in application programming. All the GUI programs and web servers are
threaded together. The main reasons for using threads are:

 Parallel Computation: If any user has multiprocessor machine then the thread can allow doing parallel
processing with the goal of increase in processing speed.

 Standardization: It became a standard approach for all programming languages as it increases programming
speed.

 Parallel I/O (Input/Output): When we talk about the speed of input & output, it is comparatively slow in
CPU. By placing each i/o operations in multiple individual threads, programmers can make use of
operations done in parallel with each other & with the computation speed.

 Asynchronous Events: Multiple threaded applications can deal with asynchronous actions. For example in a
program, programmers may don't know whether the next action will be to use the mouse or to use the
keyboard. By planting a separate thread for each action, i.e., two threads both for mouse and keyboard,

84
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
programmers can be able to code a cleaner, efficient application which is to use non-blocking I/O
operations.

Thread Modules in Python

There are two ways of accessing Python threads. These are by using:

 py module

 py module

It is to be noted that 'tread' module has been considered as of lesser use, and hence users get to use the
'threading' module instead. Another thing has to keep in mind that the module 'thread' treats the thread as a
function whereas the 'threading' is implemented as an object.

Benefits of Threading

 For a single process, multiple threads can be used to process and share the same data-space and can
communicate with each other by sharing information.

 They use lesser memory overhead, and hence they are called lightweight processes.

 A program can remain responsive to input when threads are used.

 Threads can share and process the global variable's memory.

In a thread, there are three different parts. It has the beginning, an execution part, and a conclusion. It also has
an instruction pointer that points to where the thread or process is currently running, and hence the thread can
run several different program blocks concurrently.

Using a New Thread

It is achievable to execute functions in a separate thread using a module Thread. For doing this, programmers
can use the function - thread.start_new_thread().

Syntax:

85
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

thread.start_new_thread(function, args[, kwargs])

Here, the first part is a method as told before & this method is a faster and more efficient way to create new
threads. As the child thread starts the function passes a list of args. The thread gets terminated when the
function returns a value. The 'args' in the above syntax is a tuple of arguments.

Program of Threading Using Python

Example:

import threading

def coder(number):

print ('Coders: %s' , %number)

return

threads = []

for k in range(5):

t = threading.Thread(target=coder, args=(k,))

threads.append(t)

t.start()

Output:

Coders: 0

86
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Coders: 1

Coders: 2

Coders: 3

Coders: 4

Methods of Thread Class

The threading module, as described earlier has a Thread class that is used for implementing threads, and that
class also contains some predefined methods used by programmers in multi-threaded programming. These
are:

 run(): It acts as the entry of the thread

 start(): is used for starting the thread by calling the run()

 isAlive(): is used to verify whether the still executing or not

 getName(): is used for returning the name of a thread

 setName(): is used to set the name of the thread

PYTHON CGI PROGRAMMING


Until now we did a lot of stuff with programming that is not related to web or network. Now it's time for CGI.
As the name suggests, CGI means "Common" gateway interface for everything. CGI is one of the essential
parts of HTTP (Hyper-Text Transfer Protocol).

87
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
It is a set of standards that define a standard way of passing information or web-user request to an application
program & to get data back to forward it to users. This is the exchange of information between web-server
and a custom script. When the users requested the web-page, the server sends the requested web-page. The
web server usually passes the information to all application programs that process data and sends back an
acknowledged message; this technique of passing data back-and-forth between server and application is the
Common Gateway Interface. The current version of CGI is CGI/1.1 & CGI/1.2 is under process.

Browsing

What happens when a user clicks a hyperlink to browse a particular web-page or URL (Uniform Resource
Locator).

The steps are:

 Browser contacts the HTTP web server for demanding the URL

 Parsing the URL

 Look for the filename

 If it finds that file, a request is sent back

 Web browser takes a response from the web server

 As the server response, it either shows the received file or an error message.

It may become possible to set-up an HTTP server because when a certain directory is requested that file is not
sent back; instead it is executed as a program and that program's output is displayed back to your browser.

Configuring CGI

The steps are:

1. Find out which user is running the Web-server

2. Check for server configuration to see if you can run the scripts in a particular directory

3. Check for file's permission

4. Make a clear assurance that scripts you made are readable and executable by the web-server user

88
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
5. Make sure the Python-Script's first line refers to web-server that the interpreter can run

The architecture of CHI is shown below:

Python CGI Program Structure

The output of Python CGI script must consist of two sections separated by a blank line. The first part contains
the number of headers that describe the client what kind of data is following.

Python code header section looks something like this:

Example:

print ("Content-Type : text/html")

# then comes the rest hyper-text documents

print ("<html>")

print ("<head>")

89
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

print ("<title>My First CGI-Program </title>")

print ("<head>")

print ("<body>")

print ("<h3>This is HTML's Body section </h3>")

print ("</body>")

print ("</html>")

Save this file as CGI.py. When you open that saved file, the output becomes:

Output:

This is HTML's Body section

This is a simple Python script that writes its output to STDOUT file, i.e., on screen.

Use of CGI Module

If programmers write CGI scripts in Python, they can add these lines:

import cgitb

cgitb.enable()

The above code triggers special exception handler that will display a detailed report in the web-browser in
case of occurrence of any error.

HTTP Header

Few are the important lists of HTTP header frequently used in CGI programs. These are:

90
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

HTTP Header Value

Content-type text/html

Expires Date

Location URL

Set-Cookie String

Content-length N

CGI Environment Variables

Environment Variables Description

CONTENT_TYPE describes the data-type of the content

HTTP_COOKIE returns the visitor's cookie if one is set

CONTENT_LENGTH It is available for POST request to define the length of query information

HTTP_USER_AGENT defines the browser type of the visitor

PATH_INFO defines the path of a CGI script

91
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

REMOTE_HOST defines the host-name of the visitor

REMOTE_ADDR defines the IP Address of the visitor

REQUEST_METHOD used to make request & the most common methods are - GET and POST

PYTHON DATABASE CONNECTION


Programmers might expect that Python may make database programming more straightforward and painless
job, the Python database API supply with database-neutral programming interface for different databases.

These are:

 MySQL

 SQLite

 MS SQL

 PostgreSQL

 Informix

 Sybase

 Inter-base

 Oracle etc….

The DB-API is the standard for Python's database interface.

What is Database?

The database is a collection of organized information that can easily be used, managed, update, and they are
classified according to their organizational approach.

92
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
The Python Database interfaces are categorized into two. These are:

Generic Database Interface

Most Python's database interface remains to Python's DB-API standard and most of the databases have ODBC
support. Other than that Java database usually support JDBC and programmers can work with that from
Jython.

Relational Database System Interface

This employs a relational model with support of SQL. Lists of general-purpose database systems are:

1. Firebird

2. Informix

3. SAP DB

4. MS SQL server

5. Access

6. Ingres

7. MySQL etc….

Other than that, the lists of data warehouse database systems are:

1. Teradata

2. IBM Netezza

There are other non-relational categories of databases. These are:

 Record-based databases

 XML databases

 Graph databases

Native Python databases are:

 SnakeSQL
93
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 Buzhug

What Database API Includes

Using Python structure, DB-API provides standard and support for working with databases. The API consists
of:

 Bring in the API module

 Obtain database connection

 Issue SQL statements and then store procedures

 Close the connection

Benefits of Python Database Programming

 Programming in Python is considerably simple and efficient with compared to other languages, so as the
database programming

 Python database is portable, and the program is also portable so both can give an advantage in case of
portability

 Python supports SQL cursors

 It also supports Relational Database systems

 The API of Python for the database is compatible with other databases also

 It is platform independent

Defining MySQL Database

It is an interface for associating SQL database server from Python and uses the DB-API of Python to work.

How to Implement MySQL Database

To use MySQL database using Python, you need first to install it on your machine; then just type the script
given below to implement MySQL within your program.

94
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

import MySQLdb

If any error occurs then it means that the MySQL module is not installed and programmers can download it
from - https://sourceforge.net/projects/mysql-python/

Database Program Using Python

# importing the module

import MySQLdb

# opening a database connection

db = MySQLdb.connect ("localhost","testprog","stud","PYDB")

# define a cursor object

cursor = conn.cursor

# drop table if exists

Cursor.execute("IF STUDENT TABLE EXISTS DROP IT")

# query

sql = "CREATE TABLE STUDENT (NAME CHAR(30) NOT NULL, CLASS CHAR(5), AGE INT,
GENDER CHAR(8), MARKS INT"

# execute query

cursor.execute(sql)

# close object

cursor.close()

95
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

# close connection

conn.close()

Database Operations

There are various operations that programmers can perform within Python program. To deal with these
statements, you must have a good knowledge of Database programming and SQL.

Database Operations

Environment Variables Description

INSERT It is an SQL statement used to create a record into a table.

READ Fetches useful information from the database.

UPDATE It is used update those available or already existing record(s).

DELETE It is used to delete records from the database.

ROLLBACK It works like "undo", which reverts all the changes that you have made.

PYTHON META PROGRAMMING


One of the most important things that programmers should keep in mind is "do not repeat yourself". This
means that programmers should not repeat the same code - in fact, they must re-use the code. Programmers
must look for an elegant solution when they faced any problem of creating highly repetitive code. In Python,
this problem can be solved using the concept of meta-programming.
96
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Meta-programming is the concept of building functions and classes whose primary target is to manipulate
code by modifying, wrapping or generating existing code.

The major features of meta-programming are:

 Decorators

 Metaclasses

 Class-decorators

There is also a varied range of useful topics that costs a considerable demand when coming under the
umbrella of meta-programming such as signature objects, check for internal classes and functions, execution
of 'exec ()' codes, etc. The default/base metaclass is called "type"; in some cases, programmers can gain
control by manipulating or modifying the way classes are constructed - by adding extra accomplishment or
injecting additional codes along with it. So, in these types of cases, programmers can use metaclass-
programming some of the class-objects that already exist.

In other words, classes are just objects so programmers can introduce the concept of meta-classes into their
practice to customize their creation.

Putting Wrapper for a Function

Programmers can get the facility to add wrapper as a layer around a function to add extra processing
capabilities such as timing, logging, etc. The simple code to do this is:

Example:

import time

from functools import wraps

def karltime(func):

#Decorator for reporting the execution time.

@wraps(func)

97
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

def wrapper(*args, **kwargs):

start = time.time()

result = func(*args, **kwargs)

end = time.time()

print(func.__name__, end-start)

return result

return wrapper

Here is a program (connected with the previous program) segment that is using simple decorator

Example:

@karltime

def countdown(n):

while n > 0:

n -= 1

The decorator in Python's meta-programming is a special form of a function that takes functions as input and
returns a new function as output.

There are some built-in decorators viz:

 @classmethod

 @staticmethod

 @property

98
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Working of Metaclass

A metaclass can be any class that gets inherited from "type". It usually overrides either __new__ or __init__
to offer customized behavior. A custom-metaclass can be placed explicitly on a class like this:

Example:

class karlClass(object):

__metaclass__ = karlMeta

Another Meta Programming

Metaclass creates a class; normally when we build class by writing the word 'class', the default metaclass
"type" gets automatically invoked to build that class. Classes are often referred to as types and are fairly
sensible. Programmers can also add base-classes, fields, and methods. Program showing how they are used:

Example:

def karl(self, myName):

print("RAY, " + myName)

MyList = type('MyList', (list,), dict(x=62, karl=karl))

ml = MyList()

ml.append("Mango")

print(ml)

print(ml.x)

ml.karl("KARLOS")

print(ml.__class__.__class__)

99
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Output:

['Mango']

62

RAY, KARLOS

<class 'type'="">

Metaclass Hooking

Until now, we have used the "type" metaclass directly; it involves hooking won operation into a creation of
class objects and can be achieved by:

1. Writing a sub-class of the metaclass.

2. Inserting new metaclass using the 'metaclass hook'.

100
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

17.06.2019
AFTERNOON

SYLLABUS:
Python Data Processing and Encoding, Python GUI Programming ,
Create API Documentation File in Python

101
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

PYTHON DATA PROCESSING AND ENCODING

Data can be presented in different kinds of encoding such as CSV, XML, and JSON, etc. For each case the
processing format is different. Python can handle various encoding processes, and different types of modules
need to be imported to make these encoding techniques work.

Defining CSV Files

CSV (Common Separated Data) files to store data that are in tabular format into plain text & each line is
treated as a data record in the file. Each record holds one or more fields separated by commas. Here's a typical
format of tabular data along with its CSV data - record.

Figure - Separated Sample

And now let's see how it looks when a tabular form of data gets converted to Common Separated CSV file
format:

Output:

Name,Class,Dorm,Room

Emily Whittaker,2017,McCarren House,444

Belinda Jameson,2018,Cushing House,201

Jeff Smith,2019,Oliver House,11-A

102
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Kate Hudson,2018,Prescott House,205

CSV File Represented in Tuple

Example:

import csv

with open('school.csv') as g:

g_csv = csv.reader(g)

headers = next(g_csv)

for row in g:

# All the rows get rocessed

#........

This a typical example of a CSV file handled by Python.

Another alternative to read and put data in a sequence of dictionaries, the code will be:

Example:

import csv

with open('school.csv') as g:

g_csv = csv.DictReader(g)

for row in g_csv:

# process the data of the rows

103
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

#.......

Other modules can be used to deal with CSV files. Some of them are:

 writerow(headers)

 reader(args)

 split('.')

Defining JSON

It is a structure for passing around objects that contain value-pairs/names, arrays, and other objects. It is
abbreviated as JavaScript Object Notation. It is an open standard format that uses human-readable text to pass
on data-objects that consist of attributes/value - pairs.

Dealing with JSON Data

The JSON module of Python provides an easy way to encode and decode data in JSON. It has two major
functions. These are:

 dumps()

 loads()

Let's have a look at the Python data-structure into JSON:

Example:

import json

info = {

'name' : 'mango',

'number' : 10,

'price' : 500
104
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

json_sr = json.dumps(info)

This is how JSON encoded strings changed to Python data-structure:

info = json.loads(json_sr)

If the programmers are working with files instead of strings, they can use json.load() and json.dump().

JSON encoding sustains basic types of 'None', 'bool', 'int', 'float' and 'str' and also tuples, lists, and dictionaries
containing those types. In case of dictionaries, keys are assumed to be strings. For yielding the JSON
specification, programmers should encode Python lists and dictionaries.

The format of JSON encoding is almost similar to that of Python syntax, except for a few minor changes. For
example, True is mapped to 'true' and False is mapped to 'false'. Similarly, None is mapped to
'null.

PYTHON GUI PROGRAMMING

Python provides several different options for writing GUI based programs. These are listed below:

 Tkinter: It is the easiest among all to get started with. It is Python's standard GUI (Graphical User Interface)
package. It is the most commonly used toolkit for GUI Programming in Python.

 JPython: It is the Python platform for Java that is providing Python scripts seamless access o Java class
Libraries for the local machine.

 wxPython: It is open-source, cross-platform GUI toolkit written in C++. It one of the alternatives to Tkinter,
which is bundled with Python.

There are many other interfaces available for GUI. But these are the most commonly used ones. In this, we
will learn about the basic GUI programming using Tkinter.

105
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Using Tkinter

It is the standard GUI toolkit for Python. Fredrik Lundh wrote it. For modern Tk binding, Tkinter is
implemented as a Python wrapper for the Tcl Interpreter embedded within the interpreter of Python. Tk
provides the following widgets:

 button

 canvas

 combo-box

 frame

 level

 check-button

 entry

 level-frame

 menu

 list - box

 menu button

 message

 tk_optoinMenu

 progress-bar

 radio button

 scroll bar

 separator

 tree-view and many more...

Creating a GUI program using this Tkinter is simple. For this programmers need to follow the steps
mentioned below:

1. Import the module Tkinter


106
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
2. Build a GUI application (as a window)

3. Add those widgets that are mentioned above

4. Enter the primary, i.e., main event's loop for taking action when the user triggered the event.

A Sample Program Using Tkinter

In this program, it is shown how Tkinter is used via Python to built windows along with some buttons and the
events that are programmed using these buttons.

Example:

import tkinter as tk

from tkinter import *

from tkinter import ttk

class karl( Frame ):

def __init__( self ):

tk.Frame.__init__(self)

self.pack()

self.master.title("Karlos")

self.button1 = Button( self, text = "CLICK HERE", width = 25,

command = self.new_window )

self.button1.grid( row = 0, column = 1, columnspan = 2, sticky = W+E+N+S )

def new_window(self):
107
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

self.newWindow = karl2()

class karl2(Frame):

def __init__(self):

new =tk.Frame.__init__(self)

new = Toplevel(self)

new.title("karlos More Window")

new.button = tk.Button( text = "PRESS TO CLOSE", width = 25,

command = self.close_window )

new.button.pack()

def close_window(self):

self.destroy()

def main():

karl().mainloop()

if __name__ == '__main__':

main()

Standard Attributed for GUI

 Dimensions

 Fonts

 Colors
108
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 Cursors

 Anchors

 Bitmaps

Methods For Geometry Management

 The pack(): This method manages the geometry of widgets in blocks

 The grid(): This method organizes widgets in a tabular structure

 The place(): This method organizes the widgets to place them in a specific position

CREATE API DOCUMENTATION FILE IN PYTHON

An API document file is a text or HTML file that contains a description of all the features of the software,
language or product. It creates by a developer which helps other developers to understand the software and
use it correctly. This file also includes details about the classes, modules, functions, etc. used in the software.

In this tutorial, the way to create an API document file in Python is explained through an example.

Python Program to Multiply Two Numbers

The following Python program includes two functions. The first function is multiplication function that takes
two numbers in the form of input and displays their multiplication, and the second function is show function
that displays a welcome message to the screen.

You can reference the Python Function to learn more about functions in Python programming.

Example:

# Python program to multiply two numbers

def multiply(x, y):

'''
109
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

This function takes two numbers in the form of input and multiplies them.

It displays the multiplication as the result.

'''

print("Result= ",(x+y))

def show():

''' This function only displays a message.

It shows a welcome message to the user

'''

print("Welcome to Python tutorials.")

# functions calling

multiply(5, 2)

show()

Save the above program as the name multiply-two-numbers.py and execute it as:

F:\>py>python multiply-two-numbers.py

('Result= ', 10)

Welcome to Python tutorials.

110
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 In the above example program, it used multiply-two-numbers.py as a file name, but you can save as name
whatever you want.

 Triple double quote (""") and single quote (''') are called documentation string if these strings are written as
first statements in a module, function, class or a method.

This is a standard procedure to execute any Python program. To create an API document, we need to re-
execute the program with the Python pydoc module.

Example:

F:\>py>python -m pydoc -w multiply-two-numbers

In the above command:

 -m representing a module.

 pydoc is the name of the module.

 -w indicates that an HTML file to be created.

 multiply-to-numbers is a source file name.

The above program displays the output and creates an HTML file named multiply-two-numbers.html.

111
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

We can see that there is nothing other than the name and description of the two functions written in the
program as mentioned above in the HTML file. In this way, the API documentation represents help on all the
features including functions, classes, modules, etc.

112
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

18.06.2019
FORENNON

PROJECTS:
HANGMAN GAME WITH PYTHON AND
WORKING WITH GRAPHS IN PYTHON

113
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Beginner Python Project: Hangman Game with Python

The best beginner project we can consider is the game of Hangman. I am sure the majority of you reading this
Python Projects blog has played Hangman at one point of time in your life. To put it in just one single
statement, the main goal here is to create a “guess the word” game. As simple as it sounds, it has certain key
things you need to note.

 The user needs to be able to input letter guesses.


 A limit should also be set on how many guesses they can use.
 Keep notifying the user of the remaining turns.

This means you’ll need a way to grab a word to use for guessing. Let us keep it simple and use a text file for
the input. The text file consits of the words from which we have to guess.

You will also need functions to check if the user has actually inputted a single letter, to check if the inputted
letter is in the hidden word (and if it is, how many times it appears), to print letters, and a counter variable to
limit guesses.

Key Concepts to keep in mind for this Python Project:

 Random
 Variables
 Boolean
 Input and Output
 Integer
 Char
 String
 Length
 Print

114
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Code:

1. Hangman.py

https://trinket.io/python/99f458ee11

2. # This is a word game


3. import random
4.
5.
6. def print_scaffold(guesses, wd): # prints the scaffold
7. if (guesses == 0):
8. print "_________"
9. print "| |"
10. print "|"
11. print "|"
12. print "|"
13. print "|"
14. print "|________"
15. elif (guesses == 1):
16. print "_________"
17. print "| |"
18. print "| O"
19. print "|"
20. print "|"
21. print "|"
22. print "|________"
23. elif (guesses == 2):
24. print "_________"

115
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
25. print "| |"
26. print "| O"
27. print "| |"
28. print "| |"
29. print "|"
30. print "|________"
31. elif (guesses == 3):
32. print "_________"
33. print "| |"
34. print "| O"
35. print "| \|"
36. print "| |"
37. print "|"
38. print "|________"
39. elif (guesses == 4):
40. print "_________"
41. print "| |"
42. print "| O"
43. print "| \|/"
44. print "| |"
45. print "|"
46. print "|________"
47. elif (guesses == 5):
48. print "_________"
49. print "| |"
50. print "| O"
51. print "| \|/"
52. print "| |"
53. print "| / "
54. print "|________"
55. elif (guesses == 6):

116
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
56. print "_________"
57. print "| |"
58. print "| O"
59. print "| \|/"
60. print "| |"
61. print "| / \ "
62. print "|________"
63. print "\n"
64. print "The word was %s." %wd
65. print "\n"
66. print "\nYOU LOSE! TRY AGAIN!"
67. print "\nWould you like to play again, type 1 for yes or 2 for no?"
68. again = str(raw_input("> "))
69. again = again.lower()
70. if again == "1":
71. hangMan()
72. return
73.
74. def selectWord():
75. file = open('FREQ')
76. words = file.readlines()
77. myword = 'a'
78. while len(myword) < 4: # makes sure word is at least 4 letters long
79. myword = random.choice(words)
80. myword = str(myword).strip('[]')
81. myword = str(myword).strip("''")
82. myword = str(myword).strip("\n")
83. myword = str(myword).strip("\r")
84. myword = myword.lower()
85. return myword
86.

117
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
87.
88. def hangMan():
89. guesses = 0
90. word = selectWord()
91. word_list = list(word)
92. blanks = "_"*len(word)
93. blanks_list = list(blanks)
94. new_blanks_list = list(blanks)
95. guess_list = []
96.
97. print "Let's play hangman!\n"
98. print_scaffold(guesses, word)
99. print "\n"
100. print "" + ' '.join(blanks_list)
101. print "\n"
102. print "Guess a letter.\n"
103.
104. while guesses < 6:
105.
106. guess = str(raw_input("> "))
107. guess = guess.lower()
108.
109. if len(guess) > 1:
110. print "Stop cheating! Enter one letter at time."
111. elif guess == "":
112. print "Don't you want to play? Enter one letter at a time."
113. elif guess in guess_list:
114. print "You already guessed that letter! Here is what you've
guessed:"
115. print ' '.join(guess_list)
116. else:

118
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
117. guess_list.append(guess)
118. i=0
119. while i < len(word):
120. if guess == word[i]:
121. new_blanks_list[i] =
word_list[i]
122. i = i+1
123.
124. if new_blanks_list == blanks_list:
125. print "Your letter isn't here."
126. guesses = guesses + 1
127. print_scaffold(guesses, word)
128.
129. if guesses < 6:
130. print "Guess again."
131. print ' '.join(blanks_list)
132.
133. elif word_list != blanks_list:
134.
135. blanks_list = new_blanks_list[:]
136. print ' '.join(blanks_list)
137.
138. if word_list == blanks_list:
139. print "\nYOU WIN! Here is your prize:"
140. print "\n"
141. print "Would you like to play again?"
142. print "Type 1 for yes or 2 for no."
143. again = str(raw_input("> "))
144. if again == "1":
145. hangMan()
146. quit()

119
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
147.
148. else:
149. print "Great guess! Guess another!"
150.
151. hangMan()
152.

https://www.techbeamers.com/best-python-interpreter-execute-python-online/
https://repl.it/repls/WittyForcefulDatabases

INTERMEDIATE PYTHON PROJECT: WORKING WITH GRAPHS IN PYTHON

Package requirements:

 Python 3

 Scipy (0.19.1 or later)

 Numpy (1.13.1 or later)

 Matplotlib (2.0.2 or later)

 Pandas (0.20.3 or later)

 Sklearn (0.19.0 or later)

 Jupyter (optional)

The best way to get started with learning intermediate stages of programming in Python is to definitely start
working with the libraries that Python supports.

There is literally ‘n’ number of libraries that you can make use of while coding in Python. Some are very easy
and straightforward while some might take some time to grasp and master.

Here are some of the top libraries you can consider starting out with:

120
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 NumPy
 SciPy
 Pandas
 Matplotlib

NumPy is for scientific computing on a whole.

Scipy uses arrays like basic data structure used for linear algebra, calculus, and other similar concepts.

Pandas are used for dataframes and Matplotlib is to visualize data in the form of graphs and notations.

The best possible usage of Python is for data visualization. As helpful as numeric data output is, there are
many requirements of a visual representation of the data.

By visual representation, it is just a generalization. Anything ranging from creating your front-end or a
Graphical User Interface (GUI) to plotting numeric data as points on a graph.

Matplotlib is used to plot data points on a graph. And Matplotlib is a plotting library for the Python
programming language and its numerical mathematics extension NumPy. It provides an object-oriented API
for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or
GTK+.

There are many options for doing 3D plots in Python, but here are some common and easy ways using

Matplotlib.

In general, the first step is to create a 3D axes, and then plot any of the 3D graphs that best illustrates the data
for a particular need. In order to use Matplotlib, the mplot3d toolkit that is included with the Matplotlib
installation has to be imported:

1from mpl_toolkits import mplot3d


Then, to create a 3D axes you can execute this code:

1<pre id="3346" class="graf graf--pre graf-after--p">%matplotlib inline


2import numpy as np

121
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
3import matplotlib.pyplot as plt
4fig = plt.figure()
5ax = plt.axes(projection=’3d’)</pre>

It is inside this 3D axes that a plot can be drawn, it is important to know what type of plot (or combination of
plots) will be better to describe the data.

At this point in time, you need to note that this comprises our base for further plotting.

Points and Lines:

The following image combines 2 plots, one with a line that goes through every point of the data, and others
that draw a point on each of the particular 1000 values on this example.

The code is actually very simple when you try to analyze it. We have made use of standard trigonometric
functions to plot a set of random values to obtain our projection in 3 dimensions.

Code:

1ax = plt.axes(projection=’3d’)# Data for a three-dimensional line

2zline = np.linspace(0, 15, 1000)

3xline = np.sin(zline)

4yline = np.cos(zline)

122
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
5ax.plot3D(xline, yline, zline, ‘gray’)# Data for three-dimensional scattered points

6zdata = 15 * np.random.random(100)

7xdata = np.sin(zdata) + 0.1 * np.random.randn(100)

8ydata = np.cos(zdata) + 0.1 * np.random.randn(100)

9ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap=’Greens’);

3D Contour Plots:

The input for the contour plot is a bit different than for the previous plot, as it needs the data on a two-
dimensional grid.

Note that on the following example that after assigning values for x and y, they are combined on a grid by
executing “np.meshgrid(x, y)” and then the Z values are created from executing the function f(X,Y) with the
values of the grid (Z=f(X,Y)).

Again, basic 3d plot simplified in the following code:

1 def f(x, y):


2 return np.sin(np.sqrt(x ** 2 + y ** 2))
3
4 x = np.linspace(-6, 6, 30)
5 y = np.linspace(-6, 6, 30)

123
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
6
7 X, Y = np.meshgrid(x, y)
8 Z = f(X, Y)fig = plt.figure()
9 ax = plt.axes(projection='3d')
10ax.contour3D(X, Y, Z, 50, cmap='binary')
11ax.set_xlabel('x')
12ax.set_ylabel('y')
13ax.set_zlabel('z');

On the previous graphs, the data was generated in order, but in real life sometimes the data is not ordered, for
those cases, the surface triangulation is very useful as it creates surfaces by finding sets of triangles formed
between adjacent points.

Surface Triangulation:

1theta = 2 * np.pi * np.random.random(1000)


2r = 6 * np.random.random(1000)
3x = np.ravel(r * np.sin(theta))
4y = np.ravel(r * np.cos(theta))
5z = f(x, y)
6ax = plt.axes(projection=’3d’)
7ax.plot_trisurf(x, y, z,cmap=’viridis’, edgecolor=’none’);

124
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON

Now that we are familiar with how we can expand our reach on learning Python by looking at external
libraries, we can go ahead and check out the next level of Python Projects which is the Advanced Level.

PROJECTS : MACHINE LEARNING USING PYTHON

1. Machine Learning Gladiator

A small project to get hands-on experience with Python, sklearn and Machine Learning.

Package requirements:

 Python 3

 Scipy (0.19.1 or later)

 Numpy (1.13.1 or later)

 Matplotlib (2.0.2 or later)

 Pandas (0.20.3 or later)

 Sklearn (0.19.0 or later)

 Jupyter (optional)

We’re affectionately calling this “machine learning gladiator,” but it’s not new. This is one of the fastest ways
to build practical intuition around machine learning.

125
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
The goal is to take out-of-the-box models and apply them to different datasets. This project is awesome for 3
main reasons:

First, you’ll build intuition for model-to-problem fit. Which models are robust to missing data? Which models
handle categorical features well? Yes, you can dig through textbooks to find the answers, but you’ll learn
better by seeing it in action.

Second, this project will teach you the invaluable skill of prototyping models quickly. In the real world, it’s
often difficult to know which model will perform best without simply trying them.

Finally, this exercise helps you master the workflow of model building. For example, you’ll get to practice…

 Importing data
 Cleaning data
 Splitting it into train/test or cross-validation sets
 Pre-processing
 Transformations
 Feature engineering

Because you’ll use out-of-the-box models, you’ll have the chance to focus on honing these critical steps.

Check out the sklearn (Python) or caret (R) documentation pages for instructions. You should
practice regression, classification, and clustering algorithms.
Tutorials
 Python: sklearn – Official tutorial for the sklearn package
 Predicting wine quality with Scikit-Learn – Step-by-step tutorial for training a machine learning model
 R: caret – Webinar given by the author of the caret package
Data Sources
 UCI Machine Learning Repository – 350+ searchable datasets spanning almost every subject matter. You’ll
definitely find datasets that interest you.
 Kaggle Datasets – 100+ datasets uploaded by the Kaggle community. There are some really fun datasets here,
including PokemonGo spawn locations and Burritos in San Diego.

126
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 data.gov – Open datasets released by the U.S. government. Great place to look if you’re interested in social
sciences.

2. Predict Stock Prices

The stock market is like candy-land for any data scientists who are even remotely interested in finance.

First, you have many types of data that you can choose from. You can find prices, fundamentals, global
macroeconomic indicators, volatility indices, etc… the list goes on and on.

Second, the data can be very granular. You can easily get time series data by day (or even minute) for each
company, which allows you think creatively about trading strategies.

Finally, the financial markets generally have short feedback cycles. Therefore, you can quickly validate your
predictions on new data.

Some examples of beginner-friendly machine learning projects you could try include…

 Quantitative value investing… Predict 6-month price movements based fundamental indicators from
companies’ quarterly reports.
 Forecasting… Build time series models, or even recurrent neural networks, on the delta between implied and
actual volatility.
 Statistical arbitrage… Find similar stocks based on their price movements and other factors and look for
periods when their prices diverge.
Obvious disclaimer: Building trading models to practice machine learning is simple. Making them profitable
is extremely difficult. Nothing here is financial advice, and we do not recommend trading real money.
Tutorials
 Python: sklearn for Investing – YouTube video series on applying machine learning to investing.
 R: Quantitative Trading with R – Detailed class notes for quantitative finance with R.
Data Sources
 Quandl – Data market that provides free (and premium) financial and economic data. For example, you can
bulk download end-of-day stock prices for over 3000 US companies or economic data from the Federal
Reserve.
127
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
 Quantopian – Quantitative finance community that offers a free platform for developing trading algorithm.
Includes datasets.
 US Fundamentals Archive – 5 years of fundamentals data for 5000+ U.S. companies.
https://www.hackerearth.com/practice/machine-learning/machine-learning-projects/python-project/tutorial/

3 . Improve Health Care

Another industry that’s undergoing rapid changes thanks to machine learning is global health and health care.

In most countries, becoming a doctor requires many years of education. It’s a demanding field with long
hours, high stakes, and an even higher barrier to entry.

As a result, there has recently been significant effort to alleviate doctors’ workload and improve the overall
efficiency of the health care system with the help of machine learning.

Uses cases include:

 Preventative care… Predicting disease outbreaks on both the individual and the community level.
 Diagnostic care… Automatically classifying image data, such as scans, x-rays, etc.
 Insurance… Adjusting insurance premiums based on publicly available risk factors.

As hospitals continue to modernize patient records and as we collect more granular health data, there will be
an influx of low-hanging fruit opportunities for data scientists to make a difference.

Tutorials
 R: Building meaningful machine learning models for disease prediction
 Machine Learning in Health Care – Excellent presentation by Microsoft Research

Data Sources
 Large Health Data Sets – Collection of large health-related datasets
 data.gov/health – Datasets related to health and health care provided by the U.S. government.
 Health Nutrition and Population Statistics – Global health, nutrition, and population statistics provided by the
World Bank.

128

You might also like