Python Programming Overview and History
Python Programming Overview and History
Dr Perugu Shyam
[Link], PGDBI, [Link], Ph.D
Assistant Professor
Department of Biotechnology
National Institute of Technology Warangal
1
16-09-2024
python
• Simple
• Python is a simple and minimalistic language in nature
• Reading a good python program should be like reading English
• Its Pseudo-code nature allows one to concentrate on the problem rather
than the language
• Easy to Learn
python
• Interpreted
• You run the program straight from the source code.
• Python program → Bytecode → a platforms native language
• You can just copy over your code to another system and it will automatically
work with python platform
• Object-Oriented
• Simple and additionally supports procedural programming
• Extensible – easily import other code
• Embeddable –easily place your code in non-python programs
• Extensive libraries
• (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV,
cryptography, etc...) (wxPython, Twisted, Python Imaging library)
2
16-09-2024
python Timeline/History
• Python was conceived in the late 1980s.
• Guido van Rossum, Benevolent Dictator For Life
• Rossum is Dutch, born in Netherlands
• Descendant of ABC, he wrote glob( ) func in UNIX
• He worked @ Univ of Amsterdam, worked for CWI, NIST, CNRI,
Google
• Also, helped develop the ABC programming language
python Timeline/History
• In 1995, python 1.2 was released.
• By version 1.4 python had several new features
• Keyword arguments (similar to those of common lisp)
• Built-in support for complex numbers
• Basic form of data-hiding through name mangling (easily
bypassed however)
3
16-09-2024
python Timeline/History
• In 2000, Python 2.0 was released.
• Introduced list comprehensions similar to Haskells
• Introduced garbage collection
• In 2001, Python 2.2 was released.
• Included unification of types and classes into one hierarchy,
making pythons object model purely Object-oriented
• Generators were added(function-like iterator behavior)
• Standards
• [Link]
4
16-09-2024
High-level data types: Computers store everything in 1s and 0s, but humans need to
work with data in more complex forms, such as text. A language that supports such
complex data is said to have high-level data types. A high-level data type is easy to
manipulate. For example, Python strings can be searched, sliced, joined, split, set to
upper- or lowercase, or have white space removed.
Interpreted: Interpreted languages run directly from source code that humans
generate. Interpreted languages run more slowly because the translation takes place
on the fly, but development and debugging is faster because you don't have to wait for
the compiler. Interpreted languages are easier to run on multiple operating systems.
In the case of Python, it's easy to write code that works on multiple operating
systems—with no need to make modifications.
5
16-09-2024
TECHNICAL
STUFF
Programs written in interpreted languages can be tested as
soon as they're written, without waiting for the code to compile.
6
16-09-2024
7
16-09-2024
Versatility
Python modules (collections of features for performing
tasks)
8
16-09-2024
Languages
• Some influential ones:
• FORTRAN
• science / engineering
• COBOL
• business data
• LISP
• logic and AI
• BASIC
• a simple language
18
9
16-09-2024
Python types
• Str, unicode – ‘MyString’, u‘MyString’
• List – [ 69, 6.9, ‘mystring’, True]
• Tuple – (69, 6.9, ‘mystring’, True) immutable
• Dictionary or hash – {‘key 1’: 6.9, ‘key2’: False} - group of key and
value pairs
Python types
• Int – 42- may be transparently expanded to long
through 438324932L
• Float – 2.171892
• Complex – 4 + 3j
• Bool – True or False
10
16-09-2024
11
16-09-2024
Python semantics
• Each statement has its own semantics, the def
statement doesn’t get executed immediately like other
statements
24
12
16-09-2024
Expressions
• expression: A data value or set of operations to compute
a value.
Examples: 1 + 4 * 3
25
Brackets
Orders (exponentiation, **)
Division and Multiplication (/, *, //, %)
Addition and Subtraction (+, -)
13
16-09-2024
Real numbers
• When integers and reals are mixed, the result is a real number.
• Example: 1 / 2.0 is 0.5
• The conversion occurs on a per-operator basis.
• 7 / 3 * 1.2 + 3 / 2
• 2 * 1.2 + 3 / 2
• 2.4 + 3 / 2
• 2.4 + 1
• 3.4
28
14
16-09-2024
Math commands
• Python has useful commands for performing calculations.
• To use many of these commands, you must write the following at the top of your Python program:
from math import *
29
Variables
• variable: A named piece of memory that can store a value.
• Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.
x 5 gpa 3.14
30
15
16-09-2024
Representing data
>>> 3.2 # canonical
3.2000000000000002
>>> str(3.2) # nice
'3. 2'
>>> repr(3.2) # canonical
'3.2000000000000002'
>>> print 3.2 # nice
3.2
The canonical representation usually tries to be a chunk of text that, when pasted
into the interpreter, re-creates the object
16
16-09-2024
print
• print : Produces text output on the console.
• Syntax:
print "Message"
print Expression
• Prints the given text message or expression value on the console, and moves
the cursor down to the next line.
print Item1, Item2, ..., ItemN
• Prints several messages and/or expressions on the same line.
• Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
34
You have 20 years until retirement
17
16-09-2024
input
• input : Reads a number from user input.
• You can assign (store) the result of input into a variable.
• Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until
retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
• Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
36
18
16-09-2024
range
• The range function specifies a range of integers:
• range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
• It can also accept a third value specifying the change between values.
• range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
• Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff!
37
Cumulative loops
• Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
38
19
16-09-2024
if
• if statement: Executes a group of statements only if
a certain condition is true. Otherwise, the statements
are skipped.
• Syntax:
if condition:
statements
• Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."
39
1 >>> x = 6
2 >>> if x >4:
3 print ( 'Yes ' )
4
5 Yes
1 >>> if x >4:
2 print ( 'Yes ' )
3 print ( 'More yes ' )
4
5 Yes
6 More yes
1 >>> if x >4:
2 print ( 'Yes ' )
3 print ( 'More yes ' )
4 else :
5 print ( 'No ' )
20
16-09-2024
if/else
• if/else statement: Executes one block of statements if a certain condition is True, and
a second block of statements if it is False.
• Syntax:
if condition:
statements
else:
statements
• Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to University of Texas!"
else:
print "Your application is denied."
41
1 >>> if a <3:
2 print ( 'Yes ' )
3 elif b >0:
4 print ( 'No ' )
5 else :
6 print ( 'Maybe ' )
7
8 Yes
21
16-09-2024
while
• while loop: Executes a group of statements as long as a condition is True.
• good for indefinite loops (repeat an unknown number of times)
• Syntax:
while condition:
statements
• Example:
number = 1
while number < 200:
print number,
number = number * 2
• Output:
1 2 4 8 16 32 64 128
43
1 >>> anum = 0
2 >>> while anum < 4:
3 print ( anum )
4 anum = anum + 1
5
60
71
82
93
22
16-09-2024
Range
1 >>> range ( 10 )
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 >>> range (2, 10)
4 [2, 3, 4, 5, 6, 7, 8, 9]
5 >>> range ( 2, 10, 2 )
6 [2, 4, 6, 8]
7 >>> for i in range ( 5 ):
8 print ( i, end='') # py 3.4
9 print i, # py 2.7
10
11 0 1 2 3 4
12 >>> list ( range ( 10 ) ) # py 3.4
23
16-09-2024
Enumerate Function
• Python eases the programmers’ task by providing a
built-in function enumerate( ) for this task.
• The enumerate ( ) function adds a counter to an
iterable and returns it in the form of an enumerating
object.
• This enumerated object can then be used directly for
loops or converted into a list of tuples using the list( )
function.
• enumerate( ) function is an essential skill for efficient
iteration and data manipulation in Python.
Enumerate Function
• Parameters:
24
16-09-2024
Enumerate Function
1 >>> adata = ('Monday ', 'Tuesday ', ' Wednesday ', 'Thursday ', ‘ Friday ' )
2 >>> for a,b in enumerate ( adata ):
3 print ( a, b )
4
5 0 Monday
6 1 Tuesday
7 2 Wednesday
8 3 Thursday
9 4 Friday
Strings
A string is an ordered sequence of characters.
● A string has a length. Get the length with the len( ) builtin function.
● A string is indexable. Get a single character at a position in a string
with the square bracket operator, for example mystring[5].
● You can retrieve a slice (substring) of a string with a slice
operation, for example mystring[5:8].
Create strings with single quotes or double quotes. You can also
escape characters with a backslash.
25
16-09-2024
• string: Strings start and end with quotation mark " or apostrophe ' characters.
• Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
• A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
• A string can represent characters by preceding them with a backslash.
• \t tab character
• \n new line character
• \" quotation mark character
• \\ backslash character
51
1 >>> answ = [ ]
2 >>> for i in range ( 0, len (dna ), 10 ):
3 count = dna[i:i +10]. count ('t')
4 pct = count /10.0
5 answ . append ( pct )
6 >>> len ( answ )
7 440384
26
16-09-2024
String Concatenation
27
16-09-2024
Complement String.
1 >>> st4 = st2 . replace ( 't', 'a' )
2 >>> st5 = st4 . replace ( 'A', 't' )
3 >>> st5
4 ' tagtcatgctcatcgtcggtcatcgtcgtcatcgtcgtcatctgctactaaataatcgtcatctg '
5 >>> st6 = st5 . replace ('c', 'C' )
6 >>> st7 = st6 . replace ('g', 'c' )
7 >>> st8 = st7 . replace ('C', 'g' )
8 >>> st9 = st8 [::-1]
9 >>> st9
10 ' ctgtagtcgtaataaatgatgctgtagtcgtcgtagtcgtcgtagtccgtcgtagtgctagtcat '
28
16-09-2024
>>> s1 = 'flower'
>>> s1 += 's'
>>> s1
'flowers'
String properties
• len(string) - number of characters in a
string
(including spaces)
• [Link](string) - lowercase version of a string
• [Link](string) - uppercase version of a string
• Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = [Link](name)
print big_name, "has", length,
"characters"
Output:
58
MARTIN DOUGLAS STEPP has 20 characters
29
16-09-2024
30
16-09-2024
str3 = [Link]("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)
join(): [Link](sequence)
• Python join() method is used to concat a string with
iterable object. It returns a new string which is the
concatenation of the strings in iterable. It allows
various iterables like: List, Tuple, String etc.
OUTPUT:
B:I:O:T:E:C:H
31
16-09-2024
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index()
isalnum( ): [Link]( )
• In python isalnum( ) method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.
str1 = "python"
str2 = "python123"
str3 = "12345"
str4 = "python@123"
str5 = "python 123"
print(str1. isalnum())
print(str2. isalnum())
print(str3. isalnum())
print(str4. isalnum())
print(str5. isalnum())
Output:
True
True
True
False
False
32
16-09-2024
isdigit(): [Link]()
• In python isdigit() method returns True if all the
characters in the string are digits. It returns False
if no character is digit in the string.
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23 OUTPUT:
str6 = “/u00BD” # 1/2 True
False
print([Link]()) False
print([Link]()) False
print([Link]()) True
print([Link]()) False
print([Link]())
print([Link]())
isnumeric(): [Link]()
• In python isnumeric() method checks whether all the characters of the
string are numeric characters or not.
• It returns True if all the characters are numeric, otherwise returns False.
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23
str6 = “/u00BD” # 1/2 True
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) True
print([Link]()) True
print([Link]())
33
16-09-2024
raw_input
• raw_input : Reads a string of text from user input.
• Example:
name = raw_input("Howdy, pardner. What's her
name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's her name? Paris Hilton
Paris Hilton ... what a silly name!
67
Text processing
• text processing: Examining, editing, formatting text.
• often uses loops that examine the characters of a string one by one
for c in “biocomputing":
print c
Output:
b
i
o
c
o
m
p
u
t
i
n
68 g
34
16-09-2024
Indexes
• The Python index( ) method helps you find the index position of
an element or an item in a string of characters or a list of items.
Indexes
•Element: This is the list element or the string character whose lowest
index/position will be returned.
•Start_pos: This specifies the position of the list item or the character of the
string from where the search begins.
•End_pos: This specifies the position of the list element or the character of the
string from where the search begins.
For example:
• if we have a list [1, 2, 3, 4, 5], we can find the index of the value 3 by calling
[Link](3), which will return the value 2 (since 3 is the third element in the list, and
indexing starts at 0).
35
16-09-2024
Indexes
• Characters in a string are numbered with indexes starting at 0:
• Example:
name = "P. SHYAM"
index 0 1 2 3 4 5 6 7
character P . S H Y A M
71
Files:
• Primary memory
• Secondary memory
• 1. Open a file,
• 2. Read the data,
• 3. Close the le.
36
16-09-2024
37
16-09-2024
38
16-09-2024
Mode Description
r Read Mode (default value)
w Write Mode (file is opened in write-only mode)
Append Mode (Opens a file for appending at the
a
end of the file without truncating)
Create Mode (Creates a new file but will return
x
an error if the file already exists.
t Open the file in text mode.
Opens the file in binary [Link] mode
b returns bytes. It is mainly used while dealing with
the non-text file such as images.
+ Opens the file for updating (reading and writing)
Parameter Description
This parameter value gives the pathname (absolute or relative to the current
file working directory) of the file to be opened.
This is the optional string that specifies the mode in which a file will be opened.
mode The default value is 'r' for reading a text file. We can discuss the other modes in the
later section.
This is an optional integer used to set the buffering policy. Pass 0 to switch
buffering off (only allowed in binary mode), 1 to select line buffering (only usable
buffering in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk
buffer.
This is the name of the encoding used to decode or encode the file. The default one
encoding is platform dependant.
These are optional string denotes how the standard encoding and decoding errors
errors have to be handled.
This is the parameter that indicates how the newline mode works (it only applies to
newline text mode). It can be None, '', '\n', '\r', and '\r\n'.
This parameter indicates whether to close a file descriptor or not. The default value
closefd is True. If closefd is False and a file descriptor rather than a filename was given, the
underlying file descriptor will be kept open when the file is closed.
39
16-09-2024
40
16-09-2024
# 3. Open the file in append mode, and add a line to the end of the file.
outfile = open(infilename, 'a')
[Link]('line 4\n')
[Link]( )
print ‘ -‘ * 40
File processing
• Many programs handle data, which often comes from files.
Example:
file_text = open("[Link]").read()
82
41
16-09-2024
Line-by-line processing
• Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("[Link]").readlines():
count = count + 1
print "The file contains", count, "lines."
83
Function:
• Functions are a nearly universal program-structuring
device. You may have come across them before in other
languages, where they may have been called subroutines or
procedures.
42
16-09-2024
Example:
• >>> type(32)
• <class int>
Function
• Function is a named sequence of statements that performs a
computation.
• When you define a function, you specify the name and the
sequence of statements. Later, you can “call” the function by
name.
43
16-09-2024
Declaration of function
44
16-09-2024
45
16-09-2024
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:', square)
46
16-09-2024
• Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output: 120
• Example:
lambda arguments: expression
add = lambda x, y: x + y
result = add(3, 5)
print(result)
Output: 8
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)
Output: [1, 4, 9, 16, 25]
47
16-09-2024
• Example:
def apply_function(func, arg):
return func(arg)
def square(x):
return x**2
result = apply_function(square, 3)
print(result)
Output: 9
def make_adder(n):
def adder(x):
return x + n
return adder
add_3 = make_adder(3)
result = add_3(5)
print(result)
Output: 8
48
16-09-2024
• import math
# sqrt computes the square root
square_root = [Link](4)
print("Square Root of 4 is",square_root)
Output:
Square Root of 4 is 2.0
2 to the power 3 is 8
49
16-09-2024
Functions
• def print_hello( ):# returns nothing
print “hello”
Lists
• LIST is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in
lists are called elements or sometimes items.
50
16-09-2024
51
16-09-2024
Traversing a list
• The most common way to traverse the elements of a list is with a for loop. The syntax
is the same as for strings:
loop traverses the list and updates each element. len returns the number of
elements in the list. range returns a list of indices from 0 to n − 1, where n is the
length of the list.
Each time through the loop, i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign the
new value.
52
16-09-2024
List operations:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
List slices:
>>> t = [a, b, c, d, e, f]
>>> t[1:3]
[b, c]
>>> t[:4]
[a, b, c, d]
>>> t[3:]
[d, e, f]
>>> t[:]
[a, b, c, d, e, f]
>>> t = [a, b, c, d, e, f]
>>> t[1:3] = [x, y]
>>> print(t)
[a, x, y, d, e, f]
53
16-09-2024
List methods:
append adds a new element to the end of a list:
>>> t = [a, b, c]
>>> [Link](d)
>>> print(t)
[a, b, c, d]
Deleting elements
>>> t = [a, b, c]
>>> x = [Link](1)
>>> print(t)
[a, c]
>>> print(x)
B
54
16-09-2024
55
16-09-2024
Dictionaries
• A dictionary is like a list. In a list, the index positions have to be integers; in
a dictionary, the indices can be (almost) any type.
• Python has several tools that can manipulate long strings of data and the
fastest is the dictionary. For example; it may be desired to know the location
of every word in the text. Each word is used as a key and the data for each
key is a list of the locations of that word.
• 1. You could create 26 variables, one for each letter of the alphabet. Then
you could traverse the string and, for each character, increment the
corresponding counter, probably using a chained conditional.
• 2. You could create a list with 26 elements. Then you could convert each
character to a number (using the built-in function ord), use the number
as an index into the list, and increment the appropriate counter.
56
16-09-2024
word = bioinformatics
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
57
16-09-2024
We can use get to write our histogram loop more concisely. get method automatically
handles the case where a key is not in a dictionary, we can reduce four lines down to one
and eliminate the if statement.
word = brontosaurus
d = dict()
for c in word:
d[c] = [Link](c,0) + 1
print(d)
The use of the get method to simplify this counting loop ends up
being a very commonly used “idiom” in Python and we will use it
many times in the rest of the book.
58
16-09-2024
• The outer loop is reading the lines of the file and the
inner loop is iterating through each of the words on that
particular line. This is an example of a pattern called
nested loops because one of the loops is the outer loop and
the other loop is the inner loop.
• Inner loop executes all of its iterations each time the outer
loop makes a single iteration, we think of the inner loop as
iterating “more quickly” and the outer loop as iterating
more slowly.
In our else statement, we use the more compact alternative for incrementing a variable. counts[word] += 1 is equivalent
to counts[word] = counts[word] + 1. Either method can be used to change the value of a variable by any desired amount.
Similar alternatives exist for-=, *=, and /=.
59
16-09-2024
Output:
chuck 1
annie 42
jan 100
60
16-09-2024
For example : if we wanted to find all the entries in a dictionary with a value
above ten, we could write the following code:
The for loop iterates through the keys of the dictionary, so we must use the index
operator to retrieve the corresponding value for each key.
Output:
annie 42
jan 100
61
16-09-2024
>>> [Link](reverse=True)
>>> l [(22, c), (10, a), (1, b)]
>>>
62
16-09-2024
INPUT:
glucose_level = 120 # Example glucose level in mg/dL
insulin_level = 5 # Example insulin level in uU/mL
threshold_glucose = 100 # Example threshold for glucose level in mg/dL
if glucose_level > threshold_glucose and insulin_level > 0:
print("Metabolic parameters indicate normal insulin response")
print("Metabolic condition check complete")
Output:
Metabolic parameters indicate normal insulin response
Metabolic condition check complete
Output:
Blood group A detected.
Blood grouping analysis complete
63
16-09-2024
64
16-09-2024
Exception Handling
• Error in Python can be of two types i.e. Syntax errors and Exceptions.
• Errors are problems in a program due to which the program will stop
the execution.
• Exceptions are raised when some internal events occur which change
the normal flow of the program.
65
16-09-2024
try:
code-you-want-to-run
except exception1 [as variable1]:
exception1 block
...
except exceptionN [as variableN]:
exceptionN block
⚫ The optional [as variable] will not work with older Python
66
16-09-2024
Output:
if (s != o:
^
SyntaxError: invalid syntax
67
16-09-2024
Output:
2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )
NameError: name 'o' is not defined
# Python code to catch an exception and handle it using try and except code blocks
OUTPUT:
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
68
16-09-2024
69
16-09-2024
70
16-09-2024
Exception example
⚫ [Link]
try:
i = int("snakes")
print "the integer is", i
except ValueError:
print "oops! invalid value"
Exception handling
• try: print "Unexpected:"
f = open("[Link]")
except IOError: print sys.exc_info()[0]
print "Could not open“ raise # re-throw caught exception
else:
[Link]() try:
a[7] = 0
finally:
• a = [1,2,3] print "Will run regardless"
try:
a[7] = 0
except (IndexError, TypeError): • Easily make your own exceptions:
print "IndexError caught” class myException(except)
except Exception, e: def __init__(self,msg):
print "Exception: ", e [Link] = msg
except: # catch everything
def __str__(self):
return repr([Link])
71
16-09-2024
Classes
class MyVector: """A simple vector class."""
num_created = 0
#USAGE OF CLASS MyVector
def __init__(self, x=0, y=0):
print MyVector.num_created
self.__x = x v = MyVector()
self.__y = y w = MyVector(0.23, 0.98)
MyVector.num_created += 1 print w.get_size()
def get_size(self): bool = isinstance(v, MyVector)
return self.__x+self.__y
@staticmethod Output:
def get_num_created 0
1.21
return MyVector.num_created
Expression
72
16-09-2024
>>> x = 1; y = 2
>>> x, y
(1, 2)
>>> x = 5
>>> y = 1.5
>>> x * y
7.5
73
16-09-2024
Threading in Python
import threading
theVar = 1
class MyThread ( [Link] ):
def run ( self ):
global theVar
print 'This is thread ' + \
str ( theVar ) + ' speaking.‘
print 'Hello and good bye.’
theVar = theVar + 1
for x in xrange ( 10 ):
MyThread().start()
• Jython and IronPython are different python implementations, both of which run
on different virtual machines. Jython runs on the JVM (Java virtual machine) and
IronPython runs on the CLR (common language runtime).
For example, using Jython, we can write a plugin for a Java application, and using
IronPython we can use the .NET standard library. The downside to using a
different implementation to CPython is that CPython is the most used python, and
therefore has the best support from libraries and developers.
• Libraries – ftplib, snmplib, uuidlib, smtpd, urlparse, SimpleHTTPServer, cgi,
telnetlib, cookielib, xmlrpclib, SimpleXMLRPCServer, DocXMLRPCServer
74
16-09-2024
Python Interpreters
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• Many more…
75
16-09-2024
76