Value Added Course
Value Added Course
V – Semester B.E
Organized by
1
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Department of ECE
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
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.
2
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
11.06.2019
FORENOON
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:
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 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
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
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
Example10:
>>> for = 3
SyntaxError: invalid syntax
Python Keywords
8
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
11.06.2019
AFTERNOON
9
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Operators
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ 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
= 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
12
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Comparison Operators
== Equal x == y
!= Not equal x != y
13
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Python Logical Operators
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true
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:
is not Returns true if both variables are not the same object x is not y
14
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
15
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
<< 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:
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']
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)
There are four collection data types in the Python programming language:
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.
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
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
23
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
12.06.2019
FORENOON
24
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
num1 = 1.5
num2 = 6.3
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: '))
a=1
b=5
c=6
Enter a: 1
Enter b: 5
Enter c: 6
x=5
y = 10
print(random.randint(0,9))
28
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
12.06.2019
AFTERNOON
29
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
1. Check if a Number is Odd or Even
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Enter a number: 43
43 is Odd
year = 2000
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))
# Python program to find the largest number among the three input numbers
31
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
4. Find the Factorial of a Number
factorial = 1
# Program make a simple calculator that can add, subtract, multiply and divide using functions
32
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
return x + y
return x - y
return x * y
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
33
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
print(num1,"-",num2,"=", subtract(num1,num2))
print(num1,"*",num2,"=", multiply(num1,num2))
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
15 * 14 = 210
35
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
13.06.2019
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.
**************************************************************************************
40
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
15.
**************************************************************************************
16.
**************************************************************************************
17.
**************************************************************************************
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.
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.
**************************************************************************************
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
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
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
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()
for i in range(2):
greeting()
many_greetings(4)
**************************************************************************************
30.
# Purpose: Example: using a programmer-defined function
**************************************************************************************
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
**************************************************************************************
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
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()
**************************************************************************************
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
**************************************************************************************
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
**************************************************************************************
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:
**************************************************************************************
58.
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
**************************************************************************************
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
**************************************************************************************
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.
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
**************************************************************************************
74.
# Purpose: Example: a program which uses a file
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
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
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
# 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)
**************************************************************************************
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
**************************************************************************************
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
**************************************************************************************
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
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 __str__(self):
'''Returns the state of the Person object. '''
return self._firstname + " " + self._lastname
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)
**************************************************************************************
82
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
17.06.2019
FORENOON
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.
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
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.
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.
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.
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
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.
Example:
import threading
def coder(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
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:
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).
Browser contacts the HTTP web server for demanding the URL
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
2. Check for server configuration to see if you can run the scripts in a particular directory
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 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.
Example:
print ("<html>")
print ("<head>")
89
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
print ("<head>")
print ("<body>")
print ("</body>")
print ("</html>")
Save this file as CGI.py. When you open that saved file, the output becomes:
Output:
This is a simple Python script that writes its output to STDOUT file, i.e., on screen.
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
Content-type text/html
Expires Date
Location URL
Set-Cookie String
Content-length N
CONTENT_LENGTH It is available for POST request to define the length of query information
91
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
REQUEST_METHOD used to make request & the most common methods are - GET and POST
These are:
MySQL
SQLite
MS SQL
PostgreSQL
Informix
Sybase
Inter-base
Oracle etc….
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:
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.
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
Record-based databases
XML databases
Graph databases
SnakeSQL
93
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Buzhug
Using Python structure, DB-API provides standard and support for working with databases. The API consists
of:
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
The API of Python for the database is compatible with other databases also
It is platform independent
It is an interface for associating SQL database server from Python and uses the DB-API of Python to work.
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/
import MySQLdb
db = MySQLdb.connect ("localhost","testprog","stud","PYDB")
cursor = conn.cursor
# 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
ROLLBACK It works like "undo", which reverts all the changes that you have made.
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.
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
def karltime(func):
@wraps(func)
97
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
start = time.time()
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.
@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
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:
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:
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
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.
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.
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
102
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Example:
import csv
with open('school.csv') as g:
g_csv = csv.reader(g)
headers = next(g_csv)
for row in g:
#........
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)
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.
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()
Example:
import json
info = {
'name' : 'mango',
'number' : 10,
'price' : 500
104
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
json_sr = json.dumps(info)
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 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
Creating a GUI program using this Tkinter is simple. For this programmers need to follow the steps
mentioned below:
4. Enter the primary, i.e., main event's loop for taking action when the user triggered the event.
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
tk.Frame.__init__(self)
self.pack()
self.master.title("Karlos")
command = self.new_window )
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)
command = self.close_window )
new.button.pack()
def close_window(self):
self.destroy()
def main():
karl().mainloop()
if __name__ == '__main__':
main()
Dimensions
Fonts
Colors
108
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
Cursors
Anchors
Bitmaps
The place(): This method organizes the widgets to place them in a specific position
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.
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:
'''
109
VAC MATERIALS - MACHINE PROGRAMMING WITH PYTHON
This function takes two numbers in the form of input and multiplies them.
'''
print("Result= ",(x+y))
def show():
'''
# 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
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:
-m representing a module.
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
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.
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.
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
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
Package requirements:
Python 3
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
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:
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.
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:
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)
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)).
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:
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.
A small project to get hands-on experience with Python, sklearn and Machine Learning.
Package requirements:
Python 3
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.
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/
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.
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