[go: up one dir, main page]

0% found this document useful (0 votes)
20 views221 pages

Python Full Notes

Uploaded by

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

Python Full Notes

Uploaded by

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

PYTHON PROGRAMMING

UNIT I
Python Introduction

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

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?


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

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

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

Python Syntax compared to other programming


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

Python Install
Many PCs and Macs will have python already installed.

To check if you have python installed on a Windows PC, search in the start bar
for Python or run the following on the Command Line (cmd.exe):

C:\Users\Your Name>python --version

To check if you have python installed on a Linux or Mac, then on linux open the
command line or on Mac open the Terminal and type:

python --version

If you find that you do not have python installed on your computer, then you can
download it for free from the following website: https://www.python.org/

Let's write our first Python file, called helloworld.py, which can be done in any
text editor.

helloworld.py

print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:

C:\Users\Your Name>python helloworld.py

The output should read:

Hello, World!

Whenever you are done in the python command line, you can simply type
the following to quit the python command line interface:

exit()

Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for


readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, but it has to be at least


one.
Example
if 5 > 2:
print("Five is greater than
two!") if 5 > 2:
print("Five is greater than two!")

You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Python Variables
In Python, variables are created when you assign a value to it:

Example
Variables in Python:

x = 5
y = "Hello, World!"

Python has no command for declaring a variable.

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a
comment:

Example
Comments in Python:

#This is a comment.
print("Hello,
World!")

Comments can be used to explain Python code.

Comments can be used to make the code more

readable.

Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello,
World!")

Comments can be placed at the end of a line, and Python will ignore the rest
of the line:

Example
print("Hello, World!") #This is a comment

Comments does not have to be text to explain the code, it can also be
used to prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")

Multi Line Comments


Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your
comment inside it:

Example
"""
This is a comment
written in
more than just one
line """
print("Hello, World!")

Creating Variables
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for declaring
a variable.

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type and can even
change type after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same
as x = 'John'

Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three
different variables)

Example
#Legal variable
names: myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable
names: 2myvar = "John"
my-var =
"John" my var =
"John"
Remember that variable names are case-sensitive

Assign Value to Multiple Variables


Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

And you can assign the Same value to multiple variables in one line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output Variables
The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example
x = "awesome"
print("Python is " +
x)
You can also use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome"
z = x + y
print(z)

For numbers, the + character works as a mathematical operator:

Example
x = 5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give you an error:

Example
x = 5
y = "John"
print(x + y)

Global Variables
Variables that are created outside of a function (as in all of the examples
above) are known as global variables.

Global variables can be used by everyone, both inside of functions and


outside.

Example
Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " +
x)
myfunc()

If you create a variable with the same name inside a function, this variable
will be local, and can only be used inside the function. The global variable
with the same name will remain as it was, global and with the original value.

Example
Create a variable inside a function, with the same name as the global
variable

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " +
x)

myfunc()

print("Python is " + x)
The global Keyword
Normally, when you create a variable inside a function, that variable is local,
and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example
If you use the global keyword, the variable belongs to the global scope:

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
Also, use the global keyword if you want to change a global variable inside
a function.

Example
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:

x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python Data Types


Built-in Data Types
Variables can store data of different types, and different types can do
different things.

Python has the following data types built-in by default, in these categories:

Text Type: Str

Numeric Types: int, float,

complex Sequence Types: list,

tuple, range Mapping Type: Dict

Set Types: set, frozenset


Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

Getting the Data Type


You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5
print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:

Example
x = ["apple", "banana", "cherry"]
Example
x = bool(5)
print(type(b))
print(type(c))

Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make
random numbers:

Exampl0065
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


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

Operator Name Example


+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3
-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

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

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

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

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

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


Python Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
in Returns True if a sequence with the specified value x in
y
is present in the object

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


is not present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description

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

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

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

~ NOT Inverts all the bits

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

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off
UNIT 2
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so
we print to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
Other programming languages often use curly-brackets for this purpose.

Example
If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Downloaded by sri yoga sankar


Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33

Downloaded by sri yoga sankar


if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.

Example
One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional statements:

Downloaded by sri yoga sankar


Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Nested If
You can have if statements inside if statements, this is called nested if statements.

Example
x = 41

if x > 10:
print("Above
ten,") if x > 20:
print("and also above
20!") else:
print("but not above 20.")

The pass Statement

Downloaded by sri yoga sankar


if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

Example
a = 33
b = 200

if b > a:
pass

Python Loops
Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition
is true.

Example
Print i as long as i is less than 6:

i = 1
while i <
6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we
need to define an indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is
true:

Downloaded by sri yoga sankar


Example
Exit the loop when i is 3:

i = 1
while i <
6:
print(i)
if i ==
3:
brea
The continue Statement
With the continue statement we can stop the current iteration, and continue
with the next:

Example
Continue to the next iteration if i is 3:

i = 0
while i <
6: i += 1
if i == 3:
continu
e
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no
longer is true:

Example
Print a message once the condition is false:

i = 1
while i <
6:
print(i)
i += 1
else:

Downloaded by sri yoga sankar


print("i is no longer less than 6")

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.

With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana",


"cherry"] for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterableobjects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

Downloaded by sri yoga sankar


The break Statement
With the break statement we can stop the loop before it has looped through all
the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana",


"cherry"] for x in fruits:
print(x)
if x == "banana":
break

Example
Exit the loop when x is "banana", but this time the break comes before the
print:

fruits = ["apple", "banana",


"cherry"] for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Example
Do not print banana:

fruits = ["apple", "banana",


"cherry"] for x in fruits:

Downloaded by sri yoga sankar


if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):

Example
Using the start parameter:

for x in range(2,
6): print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example

Downloaded by sri yoga sankar


Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when
the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The pass Statement

Downloaded by sri yoga sankar


for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.

Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:

Example
a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

Downloaded by sri yoga sankar


a = """Loremipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Loremipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the
code.

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello,
World!"
print(a[1])

Slicing
You can return a range of characters by using the slice syntax.

Downloaded by sri yoga sankar


Specify the start index and the end index, separated by a colon, to return a part
of the string.

Example
Get the characters from position 2 to position 5 (not included):

b = "Hello,
World!"
print(b[2:5])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters from position 5 to position 1 (not included), starting the
count from the end of the string:

b = "Hello,
World!" print(b[-
5:-2])

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello,
World!"
print(len(a))

String Methods
Python has a set of built-in methods that you can use on strings.

Example

Downloaded by sri yoga sankar


The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Example
The lower() method returns the string in lower case:

a = "Hello,
World!"
print(a.lower())

Example
The upper() method returns the string in upper case:

a = "Hello,
World!"
print(a.upper())

Example
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Example
The split() method splits the string into substrings if it finds instances of the
separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.

Example

Downloaded by sri yoga sankar


Check if the phrase "ain" is present in the following text:

txt = "The rain in Spain stays mainly in the


plain" x = "ain" in txt
print(x)

Example
Check if the phrase "ain" is NOT present in the following text:

txt = "The rain in Spain stays mainly in the


plain" x = "ain" not in txt
print(x)

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Example
To add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)

String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:

Downloaded by sri yoga sankar


Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:

Example
Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Downloaded by sri yoga sankar


Escape Character
To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to


insert.

An example of an illegal character is a double quote inside a string that is


surrounded by double quotes:

Example
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example
The escape character allows you to use double quotes when you normally would
not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Other escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

Downloaded by sri yoga sankar


\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

String Methods
Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original
string.

Method Description

Downloaded by sri yoga sankar


capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a


string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the
position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

Downloaded by sri yoga sankar


index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

Downloaded by sri yoga sankar


istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with


a specified value

rfind() Searches the string for a specified value and returns the last
position of where it was found

Downloaded by sri yoga sankar


rindex() Searches the string for a specified value and returns the last
position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

Downloaded by sri yoga sankar


title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

Python Collections (Arrays)


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

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


members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 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.

Example

Downloaded by sri yoga sankar


Create a List:

thislist = ["apple", "banana",


"cherry"] print(thislist)

Access Items
You access the list items by referring to the index number:

Example
Print the second item of the list:

thislist = ["apple", "banana",


"cherry"] print(thislist[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item,
- 2 refers to the second last item etc.

Example
Print the last item of the list:

thislist = ["apple", "banana",


"cherry"] print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.

When specifying a range, the return value will be a new list with the specified
items.

Example
Return the third, fourth, and fifth item:

Downloaded by sri yoga sankar


thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not
included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example
This example returns the items from the beginning to "orange":

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:

Example
This example returns the items from "cherry" and to the end:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:

Example
This example returns the items from index -4 (included) to index -1 (excluded)

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"] print(thislist[-4:-1])

Downloaded by sri yoga sankar


Change Item Value
To change the value of a specific item, refer to the index number:

Example
Change the second item:

thislist = ["apple", "banana",


"cherry"] thislist[1] =
"blackcurrant" print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:

Example
Print all items in the list, one by one:

thislist = ["apple", "banana",


"cherry"] for x in thislist:
print(x)

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:

Example
Check if "apple" is present in the list:

thislist = ["apple", "banana",


"cherry"] if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

List Length
To determine how many items a list has, use the len() function:

Downloaded by sri yoga sankar


Example
Print the number of items in the list:

thislist = ["apple", "banana",


"cherry"] print(len(thislist))

Add Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana",


"cherry"] thislist.append("orange")
print(thislist)

To add an item at the specified index, use the insert() method:

Example
Insert an item as the second position:

thislist = ["apple", "banana",


"cherry"] thislist.insert(1,
"orange") print(thislist)

Remove Item
There are several methods to remove items from a list:

Example
The remove() method removes the specified item:

thislist = ["apple", "banana",


"cherry"] thislist.remove("banana")
print(thislist)

Downloaded by sri yoga sankar


Example
The pop() method removes the specified index, (or the last item if index is not
specified):

thislist = ["apple", "banana",


"cherry"] thislist.pop()
print(thislist)

Example
The del keyword removes the specified index:

thislist = ["apple", "banana",


"cherry"] del thislist[0]
print(thislist)

Example
The del keyword can also delete the list completely:

thislist = ["apple", "banana",


"cherry"] del thislist

Example
The clear() method empties the list:

thislist = ["apple", "banana",


"cherry"] thislist.clear()
print(thislist)

Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only
be a reference to list1, and changes made in list1 will automatically also be
made in list2.

There are ways to make a copy, one way is to use the built-in List
method copy().

Example

Downloaded by sri yoga sankar


Make a copy of a list with the copy() method:

thislist = ["apple", "banana",


"cherry"] mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().

Example
Make a copy of a list with the list() method:

thislist = ["apple", "banana",


"cherry"] mylist = list(thislist)
print(mylist)

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

Example
Join two list:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Another way to join two lists are by appending all the items from list2 into list1,
one by one:

Example
Append list2 into list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

Downloaded by sri yoga sankar


for x in list2:
list1.append(x)

print(list1)

Or you can use the extend() method, which purpose is to add elements from one
list to another list:

Example
Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

The list() Constructor


It is also possible to use the list() constructor to make a new list.

Example
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double


round- brackets
print(thislist)

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

Downloaded by sri yoga sankar


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

clear() Removes all the elements from the list

copy() Returns a copy of the list

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

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

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Downloaded by sri yoga sankar


Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.

Example
Create a Tuple:

thistuple = ("apple", "banana",


"cherry") print(thistuple)

Access Tuple Items


You can access tuple items by referring to the index number, inside square
brackets:

Example
Print the second item in the tuple:

thistuple = ("apple", "banana",


"cherry") print(thistuple[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.

Example
Print the last item of the tuple:

thistuple = ("apple", "banana",


"cherry") print(thistuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.

Downloaded by sri yoga sankar


When specifying a range, the return value will be a new tuple with the specified
items.

Example
Return the third, fourth, and fifth item:

thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not
included).

Remember that the first item has index 0.

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the
tuple:

Example
This example returns the items from index -4 (included) to index -1 (excluded)

thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango") print(thistuple[-4:-1])

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.

Example
Convert the tuple into a list to be able to change it:

Downloaded by sri yoga sankar


x = ("apple", "banana",
"cherry") y = list(x)
y[1] =
"kiwi" x =
tuple(y)

print(x)
Loop Through a Tuple
You can loop through the tuple items by using a for loop.

Example
Iterate through the items and print the values:

thistuple = ("apple", "banana",


"cherry") for x in thistuple:
print(x)

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:

Example
Check if "apple" is present in the tuple:

thistuple = ("apple", "banana",


"cherry") if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Tuple Length
To determine how many items a tuple has, use the len() method:

Example
Print the number of items in the tuple:

Downloaded by sri yoga sankar


thistuple = ("apple", "banana",
"cherry") print(len(thistuple))

Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

Example
You cannot add items to a tuple:

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an
error print(thistuple)

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.

Example
One item tuple, remember the commma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple =
("apple")
print(type(thistuple
Remove Items
Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:

Example

Downloaded by sri yoga sankar


The del keyword can delete the tuple completely:

thistuple = ("apple", "banana",


"cherry") del thistuple
print(thistuple) #this will raise an error because the tuple no
longer exists

Join Two Tuples


To join two or more tuples you can use the + operator:

Example
Join two tuples:

tuple1 = ("a", "b" ,


"c") tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.

Example
Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double


round- brackets
print(thistuple)

Tuple Methods
Python has two built-in methods that you can use on tuples.

Downloaded by sri yoga sankar


Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where
found

Python Set
A set is a collection which is unordered and unindexed. In Python sets are
written with curly brackets.

Example
Create a Set:

thisset = {"apple", "banana",


"cherry"} print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will
appear.

Access Items
You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.

But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.

Example
Loop through the set, and print the values:

Downloaded by sri yoga sankar


thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example
Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Change Items
Once a set is created, you cannot change its items, but you can add new items.

Add Items
To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana",

"cherry"} thisset.add("orange")

Example
Add multiple items to a set, using the update() method:

thisset = {"apple", "banana", "cherry"}


thisset.update(["orange", "mango", "grapes"])
print(thisset)

Downloaded by sri yoga sankar


Get the Length of a Set
To determine how many items a set has, use the len() method.

Example
Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana",

"cherry"} thisset.remove("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example
Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.

Downloaded by sri yoga sankar


You can also use the pop(), method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.

The return value of the pop() method is the removed item.

Example
Remove the last item by using the pop() method:

thisset = {"apple", "banana",

"cherry"} x = thisset.pop()

print(x)

print(thisset)

Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.

Example
The clear() method empties the set:

thisset = {"apple", "banana",

"cherry"} thisset.clear()

print(thisset)

Example
The del keyword will delete the set completely:

thisset = {"apple", "banana",

"cherry"} del thisset

print(thisset)

Join Two Sets

Downloaded by sri yoga sankar


There are several ways to join two or more sets in Python.

You can use the


union( method that returns a new set containing all items from
both sets, or the )update( method that inserts all the items from one set into
another: )

Example
The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Example
The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set1.update(set2)
print(set1)

Note: Both union( and update( will exclude any duplicate items.
) )
There are other methods that joins two sets and keeps ONLY the duplicates, or
NEVER the duplicates, check the full list of set methods in the bottom of this
page.

The set() Constructor


It is also possible to use the set() constructor to make a set.

Example
Using the set() constructor to make a set:

Downloaded by sri yoga sankar


thisset = set(("apple", "banana", "cherry")) # note the double round-
brackets
print(thisset)

Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or


mor

difference_update() Removes the items in this set that are also included in
anot
specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

Downloaded by sri yoga sankar


intersection_update() Removes the items in this set that are not present in other,
specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and


another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Downloaded by sri yoga sankar


Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.

Example
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

Example
Get the value of the "model" key:

x = thisdict["model"]

There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:

x = thisdict.get("model")

Downloaded by sri yoga sankar


Change Values
You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict["year"] = 2018

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.

Example
Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Example
Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])

Example
You can also use the values() method to return values of a dictionary:

Downloaded by sri yoga sankar


for x in thisdict.values():
print(x)

Example
Loop through both keys and values, by using the items() method:

for x, y in thisdict.items():
print(x, y)

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

Example
Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() function.

Example
Print the number of items in the dictionary:

print(len(thisdict))

Adding Items

Downloaded by sri yoga sankar


Adding an item to the dictionary is done by using a new index key and
assigning a value to it:

Example
thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict["color"] = "red"
print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict.popitem()
print(thisdict)

Downloaded by sri yoga sankar


Example
The del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

Example
The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict.clear()
print(thisdict)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2
will only be a reference to dict1, and changes made in dict1 will automatically
also be made in dict2.

Downloaded by sri yoga sankar


There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Example
Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in function dict().

Example
Make a copy of a dictionary with the dict() function:

thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested
dictionaries.

Example
Create a dictionary that contain three dictionaries:

myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004

Downloaded by sri yoga sankar


},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" :
"Linus", "year"
: 2011
}
}
Or, if you want to nest three dictionaries that already exists as dictionaries:

Example
Create three dictionaries, then create one dictionary that will contain the other
three dictionaries:

child1 =
{
"name" : "Emil",
"year" : 2004
}
child2 =
{
"name" : "Tobias",
"year" : 2007
}
child3 =
{
"name" : "Linus",
"year" : 2011
}

myfamily {
=
"child1" : child1,
"child2" : child2,
"child3" : child3
}

The dict() Constructor


It is also possible to use the dict() constructor to make a new dictionary:

Downloaded by sri yoga sankar


Example
thisdict = dict(brand="Ford", model="Mustang",
year=1964) # note that keywords are not string
literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

Downloaded by sri yoga sankar


pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

Downloaded by sri yoga sankar


These exceptions can be handled using the try statement:

Downloaded by sri yoga sankar


Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
This statement will raise an error, because x is not defined:

print(x)

Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special block of
code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other errors:

try:
print(x)
except
NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else
You can use the else keyword to define a block of code to be executed if no errors were raised:

Downloaded by sri yoga sankar


Example
In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went
wrong") else:
print("Nothing went wrong")

Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example
try:
print(x)
except:
print("Something went
wrong") finally:
print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example
Try to open and write to a file that is not writable:

try:
f = open("demofile.txt")
f.write("LorumIpsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()

The program can continue, without leaving the file object open.

Raise an exception

Downloaded by sri yoga sankar


As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example
Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example
Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Downloaded by sri yoga sankar


UNIT-3

Downloaded by sri yoga sankar


UNIT III
 File Handling

 Modules

 Regular Expressions

 Text handling

 Object Oriented Programming

 Classes

 Objects

 Inheritance

 Overloading

 Polymorphism

 Interacting with Databases

 Introduction to MySQL

 interacting with MySQL

 Building a address book with add/edit/delete/search features


Downloaded by sri yoga sankar
FILE HANDLING

 File handling is an important part of any web


application.

 Python has several functions for


creating, reading, updating, and deleting
files.

Downloaded by sri yoga sankar


PYTHON FILE OPEN

 The key function for working with files in Python is the open() function.

 The open() function takes two parameters; filename, and mode.

 There are four different methods (modes) for opening a file:

 "r" - Read - Default value. Opens a file for reading, error if the file does not
exist

 "a" - Append - Opens a file for appending, creates the file if it does not exist

 "w" - Write - Opens a file for writing, creates the file if it does not exist

 "x" - Create - Creates the specified file, returns an error if the file exists

 In addition you can specify if the file should be handled as binary or text
mode

 "t" - Text - Default value. Text mode

 "b" - Binary - Binary mode (e.g. images)

Downloaded by sri yoga sankar


SYNTAX

To open a file for reading it is enough to specify the


name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default
values, you do not need to specify them.

Note: Make sure the file exists, or else you will get
an error.

Downloaded by sri yoga sankar


OPEN A FILE ON THE SERVER
Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing
purposes. Good Luck!

To open the file, use the built-in open() function.


The open() function returns a file object, which has a read() method for reading the content of the file:

Example
f = open("demofile.txt", "r")
print(f.read())

If the file is located in a different location, you will have to specify the file path, like this:

Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

Downloaded by sri yoga sankar


READ ONLY PARTS OF THE FILE

By default the read() method returns the whole


text, but you can also specify how many
characters you want to return:

Example

Return the 5 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))

Downloaded by sri yoga sankar


READ LINES
You can return one line by using the readline() method:

Example:Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Example:Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by line:

Example:Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)

Downloaded by sri yoga sankar


CLOSE FILES

It is a good practice to always close the file when you


are done with it.

Example:Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases,


due to buffering, changes made to a file may not show
until you close the file.

Downloaded by sri yoga sankar


PYTHON FILE WRITE

Write to an Existing File


To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Example:Open the file "demofile2.txt" and append content to the


file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Example:open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Downloaded by sri yoga sankar


Example:Open the file "demofile3.txt" and overwrite the
content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.

Downloaded by sri yoga sankar


CREATE A NEW FILE

To create a new file in Python, use the open() method, with one of the
following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example:Create a file called "myfile.txt”

f = open("myfile.txt", "x")

Result: a new empty file is created!

Example:Create a new file if it does not exist:

f = open("myfile.txt", "w")

Downloaded by sri yoga sankar


PYTHON DELETE FILE

Delete a File

To delete a file, you must import the OS


module, and run its os.remove() function:

Example:Remove the file "demofile.txt“

import os
os.remove("demofile.txt")

Downloaded by sri yoga sankar


CHECK IF FILE EXIST:
To avoid getting an error, you might want to check if the
file exists before you try to delete it:

Example:Check if file exists, then delete it

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Downloaded by sri yoga sankar


DELETE FOLDER

To delete an entire folder, use the os.rmdir() method:

Example:Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

Downloaded by sri yoga sankar


PYTHON MODULES
A file containing a set of functions you want to
include in your application.

Downloaded by sri yoga sankar


CREATE A MODULE
To create a module just save the code you want in a file
with the file extension .py:
Example:Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using
the import statement:
Example:Import the module named mymodule, and call
the greeting function:

import mymodule
mymodule.greeting("Jonathan")

Downloaded by sri yoga sankar


VARIABLES IN MODULE
Variables in Module

The module can contain functions, as already described, but also


variables of all types (arrays, dictionaries, objects etc):

Example:Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example:Import the module named mymodule, and access the person1


dictionary:

import mymodule
a = mymodule.person1["age"]
print(a)

Downloaded by sri yoga sankar


NAMING A MODULE
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module

You can create an alias when you import a module, by


using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx
a = mx.person1["age"]
print(a)

Downloaded by sri yoga sankar


BUILT-IN MODULES
There are several built-in modules in Python, which you
can import whenever you like.

Example:Import and use the platform module:

import platform
x = platform.system()
print(x)

Downloaded by sri yoga sankar


USING THE DIR() FUNCTION
There is a built-in function to list all the function names (or
variable names) in a module.

The dir() function

Example:List all the defined names belonging to the


platform module:

import platform
x = dir(platform)
print(x)

Downloaded by sri yoga sankar


IMPORT FROM MODULE
You can choose to import only parts from a module, by using the from keyword.

Example:The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 =
{ "name": "John",
"age": 36,
"country": "Norway"
}

Example:Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to elements in
the module. Example: person1["age"], not mymodule.person1["age"]

Downloaded by sri yoga sankar


PYTHON REGEX

A RegEx, or Regular Expression, is a sequence


of characters that forms a search pattern.

RegEx can be used to check if a string contains the


specified search pattern.

Downloaded by sri yoga sankar


REGEX MODULE
Python has a built-in package called re, which can be
used to work with Regular Expressions.

Import the re module:

import re

Downloaded by sri yoga sankar


REGEX IN PYTHON

When you have imported the re module, you can start


using regular expressions:

Example

Search the string to see if it starts with "The" and ends


with "Spain":

import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)

Downloaded by sri yoga sankar


REGEX FUNCTIONS

The re module offers a set of functions that allows us to


search a string for a match:

Function and its Description

Findall Returns a list containing all matches

searchReturns a Match object if there is a match


anywhere in the string

splitReturns a list where the string has been split at


each match

subReplaces one or many matches with a string

Downloaded by sri yoga sankar


METACHARACTERS
Metacharacters are characters with a special
meaning:
Character and Description and Example
[] A set of characters "[a-m]”
\ Signals a special sequence (can also be used
to escape special characters) "\d”
. Any character (except newline character)
"he..o”
^ Starts with "^hello”

Downloaded by sri yoga sankar


SPECIAL SEQUENCES

A special sequence is a \ followed by one of the


characters in the list below, and has a special meaning:
\A Returns a match if the specified
characters are at the beginning of the string "\
Athe”
\b Returns a match where the specified
characters are at the beginning or at the end of a
word

Downloaded by sri yoga sankar


SETS
A set is a set of characters inside a pair of square
brackets [] with a special meaning
[arn]
Returns a match where one of the specified characters (a, r, or n) are present
[a-n]
Returns a match for any lower case character, alphabetically between a and n
[^arn]
Returns a match for any character EXCEPT a, r, and n
[0123]
Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9]
Returns a match for any digit between 0 and 9
[0-5][0-9]
Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z]
Returns a match for any character alphabetically between a and z, lower case
OR upper case
[+]
In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for
any + character in the string

Downloaded by sri yoga sankar


THE FINDALL() FUNCTION

The findall() function returns a list containing all


matches.
Example:Print a list of all matches:

import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)

Downloaded by sri yoga sankar


EXAMPLE
Return an empty list if no match was found:

import re
txt = "The rain in Spain"
x = re.findall("Portugal", txt)
print(x)

Downloaded by sri yoga sankar


THE SEARCH() FUNCTION

The search() function searches the string for a match, and


returns a Match object if there is a match.

If there is more than one match, only the first occurrence of


the match will be returned:

Example:Search for the first white-space character in the


string:

import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in
position:", x.start())

Downloaded by sri yoga sankar


EXAMPLE

Make a search that returns no match:

import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)

Downloaded by sri yoga sankar


THE SPLIT() FUNCTION

The split() function returns a list where the string has


been split at each match:

Example:Split at each white-space character:

import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)

Downloaded by sri yoga sankar


EXAMPLE
Split the string only at the first occurrence:

import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)

Downloaded by sri yoga sankar


THE SUB() FUNCTION

The sub() function replaces the matches with the text of


your choice:

Example:Replace every white-space character with the


number 9:

import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)

Downloaded by sri yoga sankar


You can control the number of replacements by
specifying the count parameter:

Example:Replace the first 2 occurrences:

import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt,
2) print(x)

Downloaded by sri yoga sankar


MATCH OBJECT

A Match Object is an object containing information


about the search and the result.

Note: If there is no match, the value None will be


returned, instead of the Match Object.

Example-Do a search that will return a Match Object:

import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object

Downloaded by sri yoga sankar


The Match object has properties and methods used to
retrieve information about the search, and the result:

.span() returns a tuple containing the start-, and end


positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a
match
Example

Print the position (start- and end-position) of the first


match occurrence.

The regular expression looks for any words that starts with
an upper case "S":

import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())

Downloaded by sri yoga sankar


EXAMPLE

Print the string passed into the function:

import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)

Downloaded by sri yoga sankar


Example

Print the part of the string where there was a match.

The regular expression looks for any words that starts


with an upper case "S":

import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())

Downloaded by sri yoga sankar


PYTHON CLASSES/OBJECTS
Python is also an object oriented programming language.

Almost everything in Python is an object, with its properties


and methods.

A Class is like an object constructor, or a "blueprint" for


creating objects.

Downloaded by sri yoga sankar


CREATE A CLASS

To create a class, use the keyword class:

Example:Create a class named MyClass, with a


property named x:

class MyClass:
x=5

Downloaded by sri yoga sankar


CREATE OBJECT

Now we can use the class named MyClass to create


objects:

Example

Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)

Downloaded by sri yoga sankar


THE INIT () FUNCTION

The examples above are classes and objects in their simplest form, and are not really
useful in real life applications.

To understand the meaning of classes we have to understand the built-in init () function.

All classes have a function called init (), which is always executed when the class is
being initiated.

Use the init () function to assign values to object properties, or other operations that are
necessary to do when the object is being created:

Example:Create a class named Person, use the init () function to assign values for name
and age:

class Person:
def init (self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)

Downloaded by sri yoga sankar


OBJECT METHODS
Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def init (self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.

Downloaded by sri yoga sankar


THE SELF PARAMETER

The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:

Example

Use the words mysillyobject and abc instead of

self: class Person:


def init (mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Downloaded by sri yoga sankar


MODIFY OBJECT PROPERTIES
You can modify properties on objects like this:
Example
Set the age of p1 to 40:

p1.age = 40

Downloaded by sri yoga sankar


DELETE OBJECT PROPERTIES

You can delete properties on objects by using


the del keyword:

Example
Delete the age property from the p1 object:

del p1.age

Downloaded by sri yoga sankar


DELETE OBJECTS
You can delete objects by using the del keyword:
Example:Delete the p1 object:

del p1

Downloaded by sri yoga sankar


THE PASS STATEMENT

class definitions cannot be empty, but if you for some


reason have a class definition with no content, put in
the pass statement to avoid getting an error.

Example

class Person:
pass

Downloaded by sri yoga sankar


PYTHON INHERITANCE
Inheritance allows us to define a class that inherits all
the methods and properties from another class.

Parent class is the class being inherited from, also


called base class.

Child class is the class that inherits from another


class, also called derived class.

Downloaded by sri yoga sankar


CREATE A PARENT CLASS

Any class can be a parent class, so the syntax is the same as creating any
other class:

Example:Create a class named Person,


with firstname and lastname properties, and a printname method:

class Person:
def init (self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname
method:

x = Person("John", "Doe")
x.printname()

Downloaded by sri yoga sankar


CREATE A CHILD CLASS
To create a class that inherits the functionality from another class, send the parent class
as a parameter when creating the child class:

Example:Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods
to the class.

Now the Student class has the same properties and methods as the Person class.

Example:Use the Student class to create an object, and then execute the printname

method:

x = Student("Mike", "Olsen")
x.printname()

Downloaded by sri yoga sankar


Add the init () Function

So far we have created a child class that inherits the


properties and methods from its parent.

We want to add the init () function to the child class


(instead of the pass keyword).

Note: The init () function is called automatically


every time the class is being used to create a new
object.

Downloaded by sri yoga sankar


EXAMPLE

Add the init () function to the Student class:

class Student(Person):
def init (self, fname, lname):
#add properties etc.

When you add the init () function, the child class will
no longer inherit the parent's init () function.

Note: The child's init () function overrides the


inheritance of the parent's init () function.

Downloaded by sri yoga sankar


To keep the inheritance of the
parent's init () function, add a call to the
parent's init () function:

Example

class Student(Person):
def init (self, fname, lname):
Person. init (self, fname, lname)

Now we have successfully added the init () function,


and kept the inheritance of the parent class, and we
are ready to add functionality in the init () function.

Downloaded by sri yoga sankar


USE THE SUPER() FUNCTION

Python also has a super() function that will make the


child class inherit all the methods and properties from
its parent:

Example

class Student(Person):
def init (self, fname, lname):
super(). init (fname, lname)

By using the super() function, you do not have to use


the name of the parent element, it will automatically
inherit the methods and properties from its parent.

Downloaded by sri yoga sankar


ADD PROPERTIES

Example:Add a property called graduationyear to


the Student class:

class Student(Person):
def init (self, fname, lname):
super(). init (fname, lname)
self.graduationyear = 2019

Downloaded by sri yoga sankar


In the example below, the year 2019 should be a variable,
and passed into the Student class when creating student
objects. To do so, add another parameter in the init ()
function:

Example

Add a year parameter, and pass the correct year when


creating objects:

class Student(Person):
def init (self, fname, lname,
year): super(). init (fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

Downloaded by sri yoga sankar


ADD METHODS
Example:Add a method called welcome to
the Student class:

class Student(Person):
def init (self, fname, lname, year):
super(). init (fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the
class of", self.graduationyear)
If you add a method in the child class with the same
name as a function in the parent class, the inheritance
of the parent method will be overridden.

Downloaded by sri yoga sankar


OPERATOR OVERLOADING IN PYTHON
Operators are used in Python to perform specific
operations on the given operands.

Each operator can be used in a different way for


different types of operands.

For example, + operator is used for adding two


integers to give an integer as a result but when we
use it with float operands, then the result is a float
value and when + is used with string operands then
it concatenates the two operands provided.

This different behaviour of a single operator for


different types of operands is called Operator
Overloading.

Downloaded by sri yoga sankar


EXAMPLE

>>> x=10
>>> y=20
>>> x+y
30

>>> z=10.4
>>> x+z
20.4

>>> s1 = 'hello '


>>> s2 = 'world'
>>> s1+s2
'hello world'

Downloaded by sri yoga sankar


METHOD OVERLOADING

In oops we have different types of elements like


Object, Class and etc. in these elements we
implement the reusability in tow elements are
Inheritance and Polymorphism. In this topic,
Method overloading is in the Polymorphism.
Polymorphism is a technique of producing
different functionality with a single format.

Here we have two types of polymorphism.

Method Overloading

Method Overriding

Downloaded by sri yoga sankar


Method Overloading:

Method Overloading is the class having methods


that are the same name with different arguments.

Arguments different will be based on a number of


arguments and types of arguments.

It is used in a single class.

It is also used to write the code clarity as well as


reduce complexity.

Method Overriding:

Method Overriding is the method having the same


name with the same arguments.

It is implemented with inheritance also.

It mostly used for memory reducing processes.

Downloaded by sri yoga sankar


METHOD OVERLOADING:

Method Overloading is the class having methods


that are the same name with different arguments.

Arguments different will be based on a number of


arguments and types of arguments.

It is used in a single class.

It is also used to write the code clarity as well as


reduce complexity.

Method Overriding:

Method Overriding is the method having the same


name with the same arguments.

It is implemented with inheritance also.

It mostly used for memory reducing processes.

Downloaded by sri yoga sankar


EXAMPLE

class Employee:
def Hello_Emp(self,eame=None):
if ename is not None:
print("Hello "+e_name)
else:
print("Hello ")
emp1=Employee()
emp1.Hello_Emp()
emp1.Hello_Emp("Besant")

Downloaded by sri yoga sankar


INTERACTING WITH DATABASES
Frontend
Backend
Interface

Downloaded by sri yoga sankar


INTRODUCTION TO MYSQL

Installing mysql
Python can be used in database applications.

One of the most popular databases is MySQL.

MySQL Database

To be able to experiment with the code examples in this


tutorial, you should have MySQL installed on your
computer.

You can download a free MySQL database


at https://www.mysql.com/downloads/.

Downloaded by sri yoga sankar


VIDEO ON INSTALLING MYSQL

https://www.youtube.com/watch?reload=9&v=GIRcpjg
-3Eg

Downloaded by sri yoga sankar


INSTALL MYSQL DRIVER

Python needs a MySQL driver to access the MySQL database.

In this tutorial we will use the driver "MySQL Connector".

We recommend that you use PIP to install "MySQL Connector".

PIP is most likely already installed in your Python environment.

Navigate your command line to the location of PIP, and type the
following:

Download and install "MySQL Connector":

C:\Users\Your Name\AppData\Local\Programs\
Python\Python36- 32\Scripts>python -m pip install
mysql-connector-python

Downloaded by sri yoga sankar


TEST MYSQL CONNECTOR

To test if the installation was successful, or if you


already have "MySQL Connector" installed, create a
Python page with the following content:

demo_mysql_test.py:

import mysql.connector

Downloaded by sri yoga sankar


CREATE CONNECTION

Start by creating a connection to the database.

Use the username and password from your MySQL


database:

demo_mysql_connection.py:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

Downloaded by sri yoga sankar


Unit-4

Downloaded by sri yoga sankar


Introduction to pygame
Last Updated: 08-10-2020
Game programming is very rewarding nowadays and it can also be used in advertising and as
a teaching tool too. Game development includes mathematics, logic, physics, AI, and much
more and it can be amazingly fun. In python, game programming is done in pygame and it is
one of the best modules for doing so.

Installing pygame:
Pygame requires Python; if you don’t already have it, you can download it from
python.org. Use python 3.6.1 or greater, because it is much friendlier to newbies, and
additionally runs faster.
The best way to install pygame is with the pip tool (which python uses to install
packages). Note, this comes with python in recent versions. We use the –user flag to tell it
to install into the home directory, rather than globally.

python3 -m pip install -U pygame --user

To see if it works, run one of the included examples:

python3 -m pygame.examples.aliens

Once you have installed pygame, you’re ready to create your very first pygame instance.

# import the pygame module


import pygame

# import pygame.locals for easier


# access to key coordinates
from pygame.locals import *

# Define our square object and call super to


# give it all the properties and methods of pygame.sprite.Sprite
# Define the class for our square objects
class Square(pygame.sprite.Sprite):
def init (self):
super(Square, self). init ()

# Define the dimension of the surface


# Here we are making squares of side 25px
self.surf = pygame.Surface((25, 25))

Downloaded by sri yoga sankar


# Define the color of the surface using RGB color coding.
self.surf.fill((O, 2OO, 255))
self.rect = self.surf.get_rect()

# initialize pygame
pygame.init()

# Define the dimensions of screen object


screen = pygame.display.set_mode((8OO, 6OO))

# instantiate all square objects


square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()

# Variable to keep our game loop running


gameOn = True

# Our game loop


while gameOn:
# for loop through the event queue
for event in pygame.event.get():

# Check for KEYDOWN event


if event.type == KEYDOWN:

# If the Backspace key has been pressed set


# running to false to exit the main loop
if event.key == K_BACKSPACE:
gameOn = False

# Check for QUIT event


elif event.type == QUIT:
gameOn = False

# Define where the squares will appear on the screen


# Use blit to draw them on the screen surface
screen.blit(square1.surf, (4O, 4O))
screen.blit(square2.surf, (4O, 53O))
screen.blit(square3.surf, (73O, 4O))
screen.blit(square4.surf, (73O, 53O))

# Update the display using flip


pygame.display.flip()
The above Python code is a simple pygame script to draw four cyan color squares.

Blit and Flip –

Blit: Blit keyword is used to draw a surface on another surface. In simple words when we
draw a surface we just blit it onto some other surface.
Flip: It is used to update the entire screen after everything is drawn. Remember that the
flip only works after drawing all the necessary surfaces otherwise, it will update nothing.

Downloaded by sri yoga sankar


What is NumPy?
NumPy is a python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier


transform, and matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project


and you can use it freely.

NumPy stands for Numerical Python.

Why Use NumPy ?


In Python we have lists that serve the purpose of arrays, but they are slow to
process.

NumPy aims to provide an array object that is up to 50x faster that


traditional Python lists.

The array object in NumPy is called ndarray, it provides a lot of supporting


functions that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources
are very important.

Data Science: is a branch of computer science where we study how


to store, use and analyze data for deriving information from it.

Why is NumPy Faster Than Lists?


NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.

Downloaded by sri yoga sankar


Which Language is NumPy written in?
NumPy is a Python library and is written partially in Python, but most of the
parts that require fast computation are written in C or C++.

Where is the NumPy Codebase?


The source code for NumPy is located at this github
repository https://github.com/numpy/numpy

github: enables many people to work on the same codebase.

Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.

Install it using this command:

C:\Users\Your Name>pip install numpy

If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.

Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:

import numpy

Now Numpy is imported and ready to use.

Downloaded by sri yoga sankar


Example
import numpy

arr = numpy.array([1, 2, 3, 4,

5]) print(arr)

Try it Yourself »

NumPy as np
NumPy is usually imported under the np alias.

alias: In Python alias are an alternate name for referring to the same thing.

Create an alias with the as keyword while importing:

import numpy as np

Now the NumPy package can be referred to as np instead of numpy.

Example
import numpy as np

arr = np.array([1, 2, 3, 4,

5]) print(arr)

Try it Yourself »

Checking NumPy Version


The version string is stored under version attribute.

Downloaded by sri yoga sankar


Example
import numpy as np

print(np. version )

Downloaded by sri yoga sankar


PyGTK
PyGTK is a set of wrappers written in Python and C for GTK + GUI library.
It is part of the GNOME project. It offers comprehensive tools for building
desktop applications in Python. This tutorial discusses the basic
functionalities of the different widgets found in the toolkit.
PyGTK is a set of wrappers written in Python and C for GTK + GUI library.
It is part of the GNOME project. It offers comprehensive tools for building
desktop applications in Python. Python bindings for other popular GUI
libraries are also available.
PyQt is a Python port of QT library. Our PyQt tutorial can be found here.
Similarly, wxPython toolkit is Python binding for wxWidgets, another
popular cross-platform GUI library. Our wxPython tutorial is available
here.
GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating
graphical user interfaces. Offering a complete set of widgets, GTK+ is
suitable for projects ranging from small one-off tools to complete
application suites.
GTK+ has been designed from the ground up to support a wide range of
languages. PyGTK is a Python wrapper for GTK+.
GTK+ is built around the following four libraries −
 Glib − A low-level core library that forms the basis of GTK+. It
provides data structure handling for C.
 Pango − A library for layout and rendering of text with an
emphasis on internationalization.
 Cairo − A library for 2D graphics with support for multiple output
devices
(including the X Window System, Win32)
 ATK − A library for a set of interfaces providing accessibility tools such
as
screen readers, magnifiers, and alternative input devices.

PyGTK eases the process and helps you create programs with a graphical
user interface using the Python programming language. The underlying
GTK+ library provides all kinds of visual elements and utilities for it to
develop full-featured applications for the GNOME Desktop. PyGTK is a
cross-platform library. It is a free software distributed under the LGPL
Downloaded by sri yoga sankar
license.

Downloaded by sri yoga sankar


PyGTK is built around GTK + 2.x. In order to build applications for GTK
+3, PyGObject bindings are also available.

PyGTK for Microsoft Windows


The installation of PyGTK for Microsoft Windows involves the following steps −
 Step 1 − Install a 32-bit Python interpreter (latest Python 2.7 distribution)
 Step 2 − Download and install GTK+ runtime.
 Step 3 − Download and install GTK+ runtime −https://ftp.gnome.org
 Step 4 − It is also recommended that you download PyCairo and PyGobject
modules from the following URLs
– https://ftp.gnome.org https://ftp.gnome.org/pub
 Step 5 − For convenience, all-in-one installer which handles all of
the PyGTK dependencies is also available. Download and install the
latest all-in-one installer for Windows from the
following URL
– https://ftp.gnome.org/pub/GNOME

PyGTK - Hello World

Creating a window using PyGTK is very simple. To proceed, we first need


to import the gtk module in our code.
import gtk
The gtk module contains the gtk.Window class. Its object constructs a
toplevel window. We derive a class from gtk.Window.
class PyApp(gtk.Window):
Define the constructor and call the show_all() method of the gtk.window class.
def init (self):
super(PyApp, self). init ()
self.show_all()
We now have to declare the object of this class and start an event loop by
calling its main() method.
PyApp()
gtk.main()
It is recommended we add a label “Hello World” in the parent window.
label = gtk.Label("Hello World")
self.add(label)
The following is a complete code to display “Hello World”−
import gtk

Downloaded by sri yoga sankar


class PyApp(gtk.Window):
def init (self):
super(PyApp, self). init ()
self.set_default_size(300,200)
self.set_title("Hello World in PyGTK")
label = gtk.Label("Hello World")
self.add(label)
self.show_all()
PyApp()
gtk.main()
The implementation of the above code will yield the following output −

PyGTK - Important Classes

The PyGTK module contains various widgets. gtk.Object class acts as the base class for
most of the widgets as well as for some non-widget classes. The toplevel window for
desktop applications using PyGTK is provided by gtk.Window class. The following table
lists the important widgets and their functions −

S.NO Classes and Description

1
gtk.Widget
This is a gtk.base class for all PyGTK widgets. gtk.Widget provides a common set of
methods and signals for the widgets.

2
gtk.Window
This is a toplevel window that holds one child widget. gtk.Window is a display area
decorated with a title bar, and items to allow the user to close, resize and move the window.

3
gtk.Button

Downloaded by sri yoga sankar


This is a pushbutton widget that issues a signal when clicked. gtk.Button is usually
displayed as a pushbutton with a text label and is generally used to attach a callback
function.

4
gtk.Entry
This is a single line text entry widget.

5
gtk.Label
This widget displays a limited amount of read-only text.

6
gtk.ButtonBox
This is a base class for widgets that contains multiple buttons.

7
gtk.HBox
This is a container that organizes its child widgets into a single horizontal row.

8
gtk.VBox
This is a container that organizes its child widgets into a single column.

9
gtk.Fixed
This is a container that can place child widgets at fixed positions and with fixed sizes, given
in pixels.

10
gtk.Layout
This provides infinite scrollable area containing child widgets and custom drawing.

11
gtk.MenuItem
This widget implements the appearance and behavior of menu items. The derived widget
subclasses of the gtk.MenuItem are the only valid children of menus. When selected by a
user, they can display a popup menu or invoke an associated function or method

12
gtk.Menu
This is a dropdown menu consisting of a list of MenuItem objects which can be navigated
and activated by the user to perform application functions.

Downloaded by sri yoga sankar


13
gtk.MenuBar
This displays the menu items horizontally in an application window or dialog.

14
gtk.ComboBox
This widget is used to choose from a list of items.

15
gtk.Scale
This is a horizontal or vertical slider control to select a numeric value.

16
gtk.Scrollbar
This displays a horizontal or vertical scrollbar.

17
gtk.ProgressBar
This is used to display the progress of a long running operation.

18
gtk.Dialog
This displays a popup window for user information and action.

19
gtk.Notebook
This widget is a container whose children are overlapping pages that can be switched
between using tab labels.

20
gtk.Paned
This is a base class for widgets with two panes, arranged either horizontally or vertically.
Child widgets are added to the panes of the widget. The division between the two children
can be adjusted by the user.

21
gtk.TextView
This widget displays the contents of a TextBuffer object.

22
gtk.Toolbar
This container holds and manages a set of buttons and widgets in a horizontal or vertical
bar.

Downloaded by sri yoga sankar


23
gtk.TreeView
This widget displays the contents of standard TreeModel (ListStore, TreeStore,
TreeModelSort)

24
gtk.DrawingArea
This widget helps in creating custom user interface elements. gtk.DrawingArea is
essentially a blank widget containing a window that you can draw on.

25
gtk.Calendar
This widget displays a calendar and allows the user to select a date.

26
gtk.Viewport
This widget displays a portion of a larger widget.

PyGTK - Window Class


An object of the gtk.Window class provides a widget that users commonly
think of as a Wwindow. This widget is a container hence, it can hold one
child widget. It provides a displayable area decorated with title bar and
resizing controls.
gtk.Window class has the following constructor −
gtk.Window(type)
Type paramter takes one of the following values −

gtk.WINDOW_TOPLEVEL This window has no parent. The Toplevel windows


(default) are the main application window and dialogs.

gtk.WINDOW_POPUP This window has no frame or decorations. A


popup window is used for menus and tooltips.

Some of the important methods of the gtk.Window class are listed below −

S.NO Methods and Description

1 set_title(string)
This sets the "title" property of the gtk.window to the value specified by
the title. The title of a window will be displayed in its title bar.

Downloaded by sri yoga sankar


2 get_title()
This returns the title of a window if set.

3 set_position()
This sets the position of window. The predefined position constants are −
 gtk.WIN_POS_NONE
 gtk.WIN_POS_CENTER
 gtk.WIN_POS_MOUSE
 gtk.WIN_POS_CENTER_ALWAYS
 gtk.WIN_POS_CENTER_ON_PARENT

3 set_focus()
This sets the widget specified to be the focus widget for the window.

4 set_resizable()
This is true by default. set_resizable() helps the user to set the size of a
window.
5 set_decorated()
This is true by default. If false, the title bar and the resizing controls of
window will be disabled.

6 set_modal()
If true, window becomes modal and the interaction with other
windows is prevented. This is used for the Dialog widgets.

7 set_default_size()
This sets the default size of the window to the specified width and height
in pixels.
The gtk.Window widget emits the following signals −

activate-default This is emitted when the default child widget of window is


activated usually by the user pressing the Return or Enter
key.

activate-focus This is emitted when the child widget with the focus is
activated usually by the user pressing the Space key.

Downloaded by sri yoga sankar


move-focus This is emitted when the focus is changed within the
window's child widgets when the user presses the Tab, the
Shift+Tab or the Up, Down, Left or Right arrow keys.

set-focus This is emitted when the focus changes to widget in window.

PyGTK - Button Class


The gtk.Button widget is usually displayed as a pushbutton with a text
label. It is generally used to attach a callback function or method that is
called when the button is clicked.
The gtk.Button class has the following constructor −
gtk.Button(label = None, stock = None, use_underline = True)
Wherein,
 Label − The text to be displayed by the button label
 Stock − The stock id identifying the stock image and text to be
used in the button. Default is None.
 Underline − If True, an underscore in the text indicates the next
character
should be underlined and used for the mnemonic accelerator.
Some of the predefined constants for stock parameter are −

 STOCK_OK
 STOCK_STOP
 STOCK_YES
 STOCK_NO
 STOCK_QUIT
 STOCK_CANCEL
 STOCK_CLOSE
The Button class has the following important methods −

S.NO Methods and Description

1
set_label()
This sets the text of the button label to label. This string is also used to
select the stock item if the "use_stock" property is True.

2
get_label()

Downloaded by sri yoga sankar


This retrieves the text from the label of the button

3
set_focus_on_click()
If True, the button grabs focus when clicked with the mouse.

4
set_alignment()
This is the horizontal and vertical alignment of the child widget. The value
ranges from 0.0 to 1.0.

5
set_image()
This sets the image property to the value of image. The
"gtkbutton-images" property should be set to True.

The following signals are emitted by the Button widget −

activat This is emitted when the gtk.Widget's activate() method is called. For a button
e it causes the "clicked" signal to be emitted.

clicked This is emitted when the mouse button is pressed and released while the
pointer is over the button or when the button is triggered with the keyboard.

PyGTK - Label Class


A Label widget is useful to display non-editable text. Label is used by
many other widgets internally. For example, Button has a label to show
text on the face. Similarly, MenuItem objects have a label. A label is a
windowless object, so it cannot receive events directly.
Label class has a simple constructor −
gtk.Label(str = None)
The following useful methods can be used with Label object −

S.NO Methods and Description

1
set_text()
This sets new text as label

2
get_text()

Downloaded by sri yoga sankar


This returns text from label

3
set_use_underline()
If true, an underscore in the text indicates the next character should be
used for the mnemonic accelerator key.

4
set_justify
This sets the alignment of the lines in the text of the label relative to each
other.
Possible values are – gtk.JUSTIFY_LEFT, gtk.JUSTIFY_RIGHT,
gtk.JUSTIFY_CENTER, and gtk.JUSTIFY_FILL.
5
Set_line_wrap()
If true, the line will be wrapped

6
set_selectable()
If true, the text in the label can be selected for copy-paste

7
set_width_chars()
This sets the width of a label

The following signals are emitted by label widget −

activate-current-link This gets emitted when the user activates a link in the label.

activate-link This gets emitted to activate a URI.

copy-clipboard This gets emitted when text is copied from the label to the
clipboard.

PyGTK - Entry Class


Entry widget is a single-line text entry widget. If the entered text is
longer than the allocation of the widget, the widget will scroll so that the
cursor position is visible.
Entry field can be converted in password mode using set_visibility()
method of this class. Entered text is substituted by character chosen by
invisible_char() method, default being '*'.
The Entry class has the following constructor −
gtk.Entry(max = 0)

Downloaded by sri yoga sankar


Here, max stands for maximum length of entry field in characters. The
parameter takes a numeric value (0-65536).
The following table shows the important methods of an Entry class −

S.NO Methods and Description

1
set_visibility(visible)
If false, the contents are obscured by replacing the characters with
the default invisible character — '*'

2
set_invisible_char(char)
The default '*' characters in the entry field are replaced by char

3
set_max_length(x)
This sets the "max-length" property to the value of x. (0-65536)

4
set_text(str)
This sets the "text" property to the value of str. The string in str
replaces the current contents of the entry.

5
get_text()
This returns the value of the "text" property which is a string
containing the contents of the entry.

6
set_alignment()
This sets the "xalign" property to the value of xalign. set_alignment()
controls the horizontal positioning of the contents in the Entry field.

The following signals are emitted by entry widget −

activate This is emitted when the entry is activated either by user action or
programmatically with the gtk.Widget.activate() method.

backspace This is emitted when the Backspace key is entered from the
keyboard.

copy-clipboard This is emitted when the selection text in the entry is copied to the
clipboard.

Downloaded by sri yoga sankar


cut-clipboard This is emitted when the selection in the entry is cut and placed in
the clipboard.

paste-clipboard This is emitted when the contents of the clipboard are pasted into
the entry.

Downloaded by sri yoga sankar


PyMedia

PyMedia is a Python module available on Linux, Windows and cygwin and features the
following:

 Encode/decode audio compressed streams. The following formats are available:


o MP3,MP2
o WMA( v1 and v2 )
o AC3
o OGG( optional with vorbis library )
o AAC( optional with faad library )
 Encode/decode video compressed streams. The following formats supported:
o AVI( divx, xvid ), generic file format, carrying many possible streams
o ASF( wmv1/2 ), generic file format, carrying many possible streams
o MPEG1,2( VCD, SVCD, DVD compatible )
 Sound output through the OSS / Waveout. Mutlichannel for digital output.
 Sound input through the OSS / Wavein.
 Sound mixer manipulation, list all lines, set/get values of every line.
 Sound manipulation classes such as SpectrAnalyzer, Resampler.
 Video manipulation to convert video frames between YUV and RGB formats
 Direct CD/DVD ROM access to read audio/video tracks in a raw format.
This way you can play Audio, DVD and Video CDs using the same interface.

Downloaded by sri yoga sankar


PYTHON IMAGE PROCESSING

Python provides lots of libraries for image processing, including −

 OpenCV − Image processing library mainly focused on real-time computer vision


with application in wide-range of areas like 2D and 3D feature toolkits, facial &
gesture recognition, Human-computer interaction, Mobile robotics, Object
identification and others.
 Numpy and Scipy libraries − For image manipuation and processing.
 Sckikit − Provides lots of alogrithms for image processing.
 Python Imaging Library (PIL) − To perform basic operations on images like create
thumnails, resize, rotation, convert between different file formats etc.

In this section we are going to see some basics of image processing in python.

Install required library


Our first step will be to install the required library, like openCV, pillow or other which we
wants to use for image processing. We can use pip to install the required library, like −

$pip install pillow

That's it: now we can play with our image.

Image: Open() and show()


First, open the file/image and show. You can rotate the image while showing like below −

#Import required library from


PIL import Image

#Open Image
im = Image.open("TajMahal.jpg")

#Image rotate & show


im.rotate(45).show()

Output

Downloaded by sri yoga sankar


As the above variable im, is a pillow object. We can retreive some information about the
opened image −

>>> im
<PIL.JpegImagePlugin.JpegImageFile image mode = RGB size = 1000x667 at
0x65AB990<
>>> im.size
(1000, 667)
>>> im.format
'JPEG'
>>>

Convert and Save() Image


We can change the format of image from one form to another, like below −

>>> im.save('TajMahal.png')

Now if we see the folder, we have same image in two different formats.

Resize-thumbnails()
We can change the size of image using thumbnail() method of pillow −

>>> im.thumbnail ((300, 300))


>>> im.show()

The image will change as follows:

Downloaded by sri yoga sankar


Converting to grayscale image − convert()
We can make the grayscale image from our original colored image.

>>> TajMahal_gray = Image.open('TajMahal.jpg').convert('L')


>>> TajMahal_gray.show()

Where "L" stands for 'luminous'.

Above example is from the PIL library of python. We can use other library like open-cv,
matplotlib & numpy for image processing. Below are some of the example program to
demonstrate the use of much powerful library for image processing.

Downloaded by sri yoga sankar


Showing image in grayscale

#Import required library


import cv2
import numpy as np
from matplotlib import pyplot as plt

im = cv2.imread('TajMahal.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',im)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Another way to write above program with a tick/line to mark the image.

import cv2
import numpy as np
from matplotlib import pyplot as plt

im = cv2.imread('TajMahal.jpg',cv2.IMREAD_GRAYSCALE)

plt.imshow(im, cmap = 'gray', interpolation = 'bicubic')


# to hide tick values on X and Y axis
plt.xticks([]), plt.yticks([]) plt.plot([200,300,400],
[100,200,300],'c', linewidth = 5) plt.show()

Output

Downloaded by sri yoga sankar


Downloaded by sri yoga sankar
PYTHON NETWORK PROGRAMMING

Python provides two levels of access to network services. At a low level, you can access the
basic socket support in the underlying operating system, which allows you to implement
clients and servers for both connection-oriented and connectionless protocols.

Python also has libraries that provide higher-level access to specific application-level
network protocols, such as FTP, HTTP, and so on.

This chapter gives you understanding on most famous concept in Networking - Socket
Programming.

What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may
communicate within a process, between processes on the same machine, or between
processes on different continents.

Sockets may be implemented over a number of different channel types: Unix domain sockets,
TCP, UDP, and so on. The socket library provides specific classes for handling the common
transports as well as a generic interface for handling the rest.

Sockets have their own vocabulary −

Sr.No. Term & Description


Domain
1 The
family of protocols that is used as the transport mechanism. These values are
constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
Type

2 The type of communications between the two endpoints, typically


SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for
connectionless protocols.
Protocol
3 Typically
zero, this may be used to identify a variant of a protocol within a
domain and type.
hostname

The identifier of a network interface −



4 A string, which can be a host name, a dotted-quad address, or an
IPV6 address in colon (and possibly dot) notation
 A string "<broadcast>", which specifies an
INADDR_BROADCAST address.

Downloaded by sri yoga sankar


 A zero-length string, which specifies INADDR_ANY, or
 An Integer, interpreted as a binary address in host byte order.

Port
5 Each
server listens for clients calling on one or more ports. A port may be a Fixnum
port number, a string containing a port number, or the name of a service.

The socket Module


To create a socket, you must use the socket.socket() function available in socket module,
which has the general syntax −

s = socket.socket (socket_family, socket_type, protocol=O)

Here is the description of the parameters −

 socket_family − This is either AF_UNIX or AF_INET, as explained earlier.


 socket_type − This is either SOCK_STREAM or SOCK_DGRAM.
 protocol − This is usually left out, defaulting to 0.

Once you have socket object, then you can use required functions to create your client or
server program. Following is the list of functions required −

Server Socket Methods


Sr.No. Method & Description
s.bind()
1
This method binds address (hostname, port number pair) to socket.
s.listen()
2
This method sets up and start TCP listener.
s.accept()
3
This passively accept TCP client connection, waiting until connection
arrives (blocking).

Client Socket Methods


Sr.No. Method & Description
s.connect()
1
This method actively initiates TCP server connection.

General Socket Methods

Downloaded by sri yoga sankar


Sr.No. Method & Description
s.recv()
1
This method receives TCP message
s.send()
2
This method transmits TCP message
s.recvfrom()
3
This method receives UDP message
s.sendto()
4
This method transmits UDP message
s.close()
5
This method closes socket
socket.gethostname()
6
Returns the hostname.

A Simple Server
To write Internet servers, we use the socket function available in socket module to create a
socket object. A socket object is then used to call other functions to setup a socket server.

Now call bind(hostname, port) function to specify a port for your service on the given host.

Next, call the accept method of the returned object. This method waits until a client connects
to the port you specified, and then returns a connection object that represents the connection
to that client.

#!/usr/bin/python # This is server.py file

import socket # Import socket module

s = socket.socket() # Create a socket object


host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port

s.listen(5) # Now wait for client connection.


while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection

A Simple Client

Downloaded by sri yoga sankar


Let us write a very simple client program which opens a connection to a given port
12345 and given host. This is very simple to create a socket client using Python's socket
module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once
you have a socket open, you can read from it like any IO object. When done, remember to
close it, as you would close a file.

The following code is a very simple client that connects to a given host and port, reads any
available data from the socket, and then exits −

#!/usr/bin/python # This is client.py file

import socket # Import socket module

s = socket.socket() # Create a socket object


host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1O24)
s.close() # Close the socket when done

Now run this server.py in background and then run above client.py to see the result.

# Following would start a server in background.


$ python server.py &

# Once server is started run client as follows:


$ python client.py

This would produce following result −

Got connection from ('127.O.O.1', 48437)


Thank you for connecting

Python Internet modules


A list of some important modules in Python Network/Internet programming.

Protocol Common function Port No Python module


HTTP Web pages 80 httplib, urllib, xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 telnetlib
Gopher Document transfers 70 gopherlib, urllib

Downloaded by sri yoga sankar


Please check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP
protocols.

Downloaded by sri yoga sankar


PYTHON GUI PROGRAMMING TKINTER
http://www.tutorialspoint.com/python/python_gui_programming.htm Copyright ©
tutorialspoint.com

Python provides various options for developing graphical user interfaces GUIs.
Most important are listed below.

Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. We would look this option in this chapter.

wxPython: This is an open-source Python interface for wxWindows


http://wxpython.org.

JPython: JPython is a Python port for Java which gives Python scripts seamless
access to Java class libraries on the local machine http://www.jython.org.

There are many other interfaces available, which you can find them on the net.

Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter provides
a powerful object-oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps −

Import the Tkinter module.

Create the GUI application main window.

Add one or more of the above-mentioned widgets to the GUI application.

Enter the main event loop to take action against each event triggered by the
user.

Example

#!/usr/bin/python

import Tkinter
top =
Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window −

Tkinter Widgets

Downloaded by sri yoga sankar


Tkinter provides various controls, such as buttons, labels and text boxes used in a
GUI application. These controls are commonly called widgets.

Downloaded by sri yoga sankar


There are currently 15 types of widgets in Tkinter. We present these widgets as well
as a brief description in the following table −

Operator Description

Butto The Button widget is used to display buttons in your application.


n

The Canvas widget is used to draw shapes, such as lines, ovals,


Canva polygons and rectangles, in your application.
s

The Checkbutton widget is used to display a number of options as


Checkbutt checkboxes. The user can select multiple options at a time.
on

The Entry widget is used to display a single-line text field for


Entr accepting values from a user.
y

The Frame widget is used as a container widget to organize other


Fram widgets.
e

The Label widget is used to provide a single-line caption for other


Labe widgets. It can also contain images.
l

The Listbox widget is used to provide a list of options to a user.


Listbo
x

The Menubutton widget is used to display menus in your application.


Menubutt
on

The Menu widget is used to provide various commands to a user.


Men These commands are contained inside Menubutton.
u

The Message widget is used to display multiline text fields for


Messa accepting values from a user.
ge

The Radiobutton widget is used to display a number of options as


Radiobutt radio buttons. The user can select only one option at a time.
on

The Scale widget is used to provide a slider widget.


Scal
e

The Scrollbar widget is used to add scrolling capability to various


Scrollba widgets, such as list boxes.
r

Downloaded by sri yoga sankar


The Text widget is used to display text in multiple lines.
Tex
t

The Toplevel widget is used to provide a separate window container.


Toplev
el

The Spinbox widget is a variant of the standard Tkinter Entry


Spinbo widget, which can be used to select from a fixed number of
x values.

Downloaded by sri yoga sankar


A PanedWindow is a container widget that may contain any number
PanedWind of panes, arranged horizontally or vertically.
ow

A labelframe is a simple container widget. Its primary purpose is


LabelFram to act as a spacer or container for complex window layouts.
e

This module is used to display message boxes in your applications.


tkMessage
Box

Let us study these widgets in detail −

Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and
fonts are specified.

Dimension

s Colors

Fonts

Anchors

Relief

styles

Bitmaps

Cursors

Let us study them briefly −

Geometry Management
All Tkinter widgets have access to specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area.
Tkinter exposes the following geometry manager classes: pack, grid, and place.

The pack Method - This geometry manager organizes widgets in blocks


before placing them in the parent widget.

The grid Method - This geometry manager organizes widgets in a table-like


structure in the parent widget.

The place Method -This geometry manager organizes widgets by placing them
in a specific position in the parent widget.

Let us study the geometry management methods briefly −


Loading [MathJax]/jax/output/HTML-
CSS/jax.js

Downloaded by sri yoga sankar


What is SciPy?
SciPy is a scientific computation library that uses NumPy underneath.

SciPy stands for Scientific Python.

It provides more utility functions for optimization, stats and signal


processing.

Like NumPy, SciPy is open source so we can use it freely.

SciPy was created by NumPy's creator Travis Olliphant.

Scipy
Why Use SciPy?
If SciPy uses NumPy underneath, why can we not just use NumPy?

SciPy has optimized and added functions that are frequently used in NumPy
and Data Science.

Which Language is SciPy Written in?


SciPy is predominantly written in Python, but a few segments are written in
C.

Where is the SciPy Codebase?


The source code for SciPy is located at this github
repository https://github.com/scipy/scipy

github: enables many people to work on the same codebase.

Installation of SciPy
If you have Python and PIP already installed on a system, then installation of
SciPy is very easy.

Downloaded by sri yoga sankar


Install it using this command:

C:\Users\Your Name>pip install scipy

If this command fails, then use a Python distribution that already has SciPy
installed like, Anaconda, Spyder etc.

Import SciPy
Once SciPy is installed, import the SciPy module(s) you want to use in your
applications by adding the from scipy import module statement:

from scipy import constants

Now we have imported the constants module from SciPy, and the
application is ready to use it:

Example
How many cubic meters are in one liter:

from scipy import constants

print(constants.liter)

constants: SciPy offers a set of mathematical constants, one of them


is liter which returns 1 liter as cubic meters.

You will learn more about constants in the next chapter.

Checking SciPy Version


The version string is stored under the version attribute.

Example
import scipy

print(scipy. version

Downloaded by sri yoga sankar


Note: two underscore characters are used in version .

Constants in SciPy
As SciPy is more focused on scientific implementations, it provides many
built-in scientific constants.

These constants can be helpful when you are working with Data Science.

PI is an example of a scientific constant.

Example
Print the constant value of PI:

from scipy import constants

print(constants.pi)

Constant Units
A list of all units under the constants module can be seen using
the dir() function.

Example
List all constants:

from scipy import constants

print(dir(constants))

Unit Categories
The units are placed under these categories:

 Metric
 Binary
 Mass
 Angle
 Time
 Length

Downloaded by sri yoga sankar


 Pressure
 Volume
 Speed
 Temperature
 Energy
 Power
 Force

Metric (SI) Prefixes:


Return the specified unit in meter (e.g. centi returns 0.01)

Example
from scipy import constants

print(constants.yotta) #1e+24
print(constants.zetta) #1e+21
print(constants.exa) #1e+18
print(constants.peta) #1000000000000000.0
print(constants.tera) #1000000000000.0
print(constants.giga) #1000000000.0
print(constants.mega) #1000000.0
print(constants.kilo) #1000.0
print(constants.hecto) #100.0
print(constants.deka) #10.0
print(constants.deci) #0.1
print(constants.centi) #0.01
print(constants.milli) #0.001
print(constants.micro) #1e-06
print(constants.nano) #1e-09
print(constants.pico) #1e-12
print(constants.femto) #1e-15
print(constants.atto) #1e-18
print(constants.zepto) #1e-21

Binary Prefixes:
Return the specified unit in bytes (e.g. kibi returns 1024)

Downloaded by sri yoga sankar


Example
from scipy import constants

print(constants.kibi) #1024
print(constants.mebi) #1048576
print(constants.gibi) #1073741824
print(constants.tebi) #1099511627776
print(constants.pebi) #1125899906842624
print(constants.exbi) #1152921504606846976
print(constants.zebi) #1180591620717411303424
print(constants.yobi) #12089258196146291747061
76

Mass:
Return the specified unit in kg (e.g. gram returns 0.001)

Example
from scipy import constants

print(constants.gram) #0.001
print(constants.metric_ton) #1000.0
print(constants.grain) #6.479891e-05
print(constants.lb)

#0.45359236999999997
print(constants.pound) #0.45359236999999997
print(constants.oz) #0.028349523124999998
print(constants.ounce) #0.028349523124999998
print(constants.stone) #6.3502931799999995
print(constants.long_ton) #1016.0469088
print(constants.short_ton) #907.1847399999999
print(constants.troy_ounce) #0.031103476799999998
print(constants.troy_pound) #0.37324172159999996
print(constants.carat) #0.0002
print(constants.atomic_mass)
#1.66053904e-27 print(constants.m_u)
#1.66053904e-
27
print(constants.u) #1.66053904e-27

Angle:
Return the specified unit
in radians (e.g. degree returns 0.017453292519943295)
Downloaded by sri yoga sankar
Example
from scipy import constants

print(constants.degree) #0.017453292519943295
print(constants.arcmin) #0.0002908882086657216
print(constants.arcminute)

#0.0002908882086657216 print(constants.arcsec)
#4.84813681109536e-
06 print(constants.arcsecond)
#4.84813681109536e-
06

Time:
Return the specified unit in seconds (e.g. hour returns 3600.0)

Example
from scipy import constants

print(constants.minute) #60.0
print(constants.hour) #3600.0
print(constants.day) #86400.0
print(constants.week) #604800.0
print(constants.year) #31536000.0
print(constants.Julian_year) #31557600.0

Length:
Return the specified unit in meters (e.g. nautical_mile returns 1852.0)

Example
from scipy import constants

print(constants.inch) #0.0254
print(constants.foot) #0.30479999999999996
print(constants.yard) #0.9143999999999999
print(constants.mile) #1609.3439999999998
print(constants.mil) #2.5399999999999997e-
05
print(constants.pt) #0.000352777777777777
76
print(constants.point) #0.000352777777777777
76
print(constants.survey_foot) #0.3048006096012192

Downloaded by sri yoga sankar


print(constants.survey_mile) #1609.3472186944373
print(constants.nautical_mile) #1852.0

Downloaded by sri yoga sankar


print(constants.fermi) #1e-15
print(constants.angstrom) #1e-10
print(constants.micron) #1e-06
print(constants.au) #149597870691.0
print(constants.astronomical_unit) #149597870691.0
print(constants.light_year) #9460730472580800.0
print(constants.parsec)

#3.0856775813057292e+16

Pressure:
Return the specified unit in pascals (e.g. psi returns 6894.757293168361)

Example
from scipy import constants

print(constants.atm) #101325.0
print(constants.atmospher #101325.0
e)
print(constants.bar) #100000.0
print(constants.torr) #133.322368421052
63
print(constants.mmHg) #133.322368421052
63
print(constants.psi) #6894.75729316836
1

Area:
Return the specified unit in square meters(e.g. hectare returns 10000.0)

Example
from scipy import constants

print(constants.hectare) #10000.0
print(constants.acre) #4046.8564223999992

Volume:
Return the specified unit in cubic meters (e.g. liter returns 0.001)

Example
from scipy import constants

Downloaded by sri yoga sankar


print(constants.liter) #0.001
print(constants.litre) #0.001
print(constants.gallon) #0.003785411783999999
7
print(constants.gallon_US) #0.003785411783999999
7
print(constants.gallon_imp) #0.00454609
print(constants.fluid_ounce) #2.9573529562499998e-
05
print(constants.fluid_ounce_US #2.9573529562499998e-
) 05
print(constants.fluid_ounce_im #2.84130625e-05
p)
print(constants.barrel) #0.15898729492799998
print(constants.bbl) #0.15898729492799998

Speed:
Return the specified unit in meters per
second (e.g. speed_of_sound returns 340.5)

Example
from scipy import constants

print(constants.kmh) #0.2777777777777778
print(constants.mph) #0.44703999999999994
print(constants.mach) #340.5
print(constants.speed_of_sound) #340.5
print(constants.knot) #0.5144444444444445

Temperature:
Return the specified unit in Kelvin (e.g. zero_Celsius returns 273.15)

Example
from scipy import constants

print(constants.zero_Celsius) #273.15
print(constants.degree_Fahrenheit) #0.5555555555555556

Energy:
Return the specified unit in joules (e.g. calorie returns 4.184)

Downloaded by sri yoga sankar


Example
from scipy import constants

print(constants.eV) #1.6021766208e-
19 print(constants.electron_volt)
#1.6021766208e-19 print(constants.calorie)
#4.184
print(constants.calorie_th) #4.184
print(constants.calorie_IT)

#4.1868 print(constants.erg) #1e-07


print(constants.Btu) #1055.05585262
print(constants.Btu_IT) #1055.05585262
print(constants.Btu_th) #1054.3502644888888
print(constants.ton_TNT) #4184000000.0

Power:
Return the specified unit
in watts (e.g. horsepower returns 745.6998715822701)

Example
from scipy import constants

print(constants.hp) #745.6998715822701
print(constants.horsepower) #745.6998715822701

Force:
Return the specified unit in newton (e.g. kilogram_force returns 9.80665)

Example
from scipy import constants

print(constants.dyn) #1e-05
print(constants.dyne) #1e-05
print(constants.lbf) #4.448221615260
5
print(constants.pound_force) #4.448221615260
5
print(constants.kgf) #9.80665
print(constants.kilogram_forc #9.80665
e)

Downloaded by sri yoga sankar


Working with SOAP based
Web Service using Python
Web services is a standardized way or medium to
propagate communication between the client and
server applications on the World Wide Web. Web
services provide a common platform that allows
multiple applications built on various programming
languages to have the ability to communicate with each
other

What is SOAP?

SOAP is known as the Simple Object Access Protocol.

SOAP is simply an XML-based messaging protocol for


exchanging information among computers, , as
explained in detail here. But hey, who would like to
write lines of XML code for only a simple request? Yeah,
neither would I. But, the good thing is that we actually
need not to. Because, Zeep does all the “hard work” for
us while all we need to do is to create a dictionary that
contains the required fields.

What is ZEEP ?

Zeep is a pure-python module. Zeep inspects the WSDL


document and generates the corresponding code to use
the services and types in the document. This provides an
easy to use programmatic interface to a SOAP server.

Downloaded by sri yoga sankar


Implementing ZEEP Client:

The first thing that you‟ll need to do is, install the zeep
python
library as:
pip install zeep

In my case, the client‟s system had a relatively simple


XML
schema for requests. Pretty simple, I admit.
<username>SAP_username</username>
<password>SAP_password</password>

Now, in your python code, you‟ll need to import Client


from zeep and then instantiate the same by passing the
WSDL URL. This can simply be done as follows:
from zeep import Client
wsdl = "http://xxxxxxxxxxx:8181/ws/xxxxxxxxx?wsdl"
client = Client(wsdl)

You can also pass user autherntication


details(username and passowrd) in case the wsdl is
password protected. For this, you‟ll need to create
from zeep import Client
the
from Session objectimport
zeep.transports as shown below:
Transport
from requests import Session
from requests.auth import HTTPBasicAuthwsdl = <wsdl_url>
session = Session()
session.auth = HTTPBasicAuth(<username>, <password>)

#An additional argument „transport‟ is passed with the


authentication details
client=Client(wsdl,transport=Transport(session=session))

Passing Parameters

Downloaded by sri yoga sankar


As I mentioned above, you just need to pass the request
parameters as a standard python dictionary and zeep
will internally convert it to the final xml.
request_data={'SAPUsername' : SAP_username ,
'SAPPassword' : SAP_password}

Zeep detects the xml schema from the wsdl file that is
passed while creating the client object. Wsdl(Web
Service Description Language) contains the required
description about the endpoint. It contains the list of
operations available and also states the parameters that
each operation requires. Zeep uses this information to
map the passed request dictionary to the corresponding
xml.

Envoking Web Service Methods:

You can use the operations defined in the wsdl using the
simple syntax shown below:
response=client.service.xxxxxxx(**request_data)#Here
'request_data' is the request parameter dictionary.

Downloaded by sri yoga sankar


Unit-5

Downloaded by sri yoga sankar


A Step by Step Guide to
Making Your First
GitHub Contribution
1. Fork the repository

Fork the First Contributions repo by clicking on the fork


button on the top of the page. This will create a copy of
this repository in your account.

2. Clone the repository

Now clone the repo to your machine. Click on the clone


button and then click the copy to clipboard icon.

Downloaded by sri yoga sankar


Open a terminal and run the following git command:
git clone "url you just copied"

where “url you just copied” (without the quote marks) is


the url
to the First Contributions repository. See the previous
steps to

Downloaded by sri yoga sankar


obtain the url.

For example:
git clone https://github.com/this-is-you/first-contributions.git

where this-is-you is your GitHub username. Here you're


copying the contents of the first-contributions repository
in GitHub to your computer.

3. Create a branch

Change to the repository directory on your computer (if


you are not already there):
cd first-contributions

Downloaded by sri yoga sankar


Now create a branch using the git checkout command:
git checkout -b <add-your-name>

For example:
git checkout -b add-alonzo-church

(The name of the branch does not need to have the word
add in it, but it’s a reasonable thing to include because
the purpose of this branch is to add your name to a list.)

4. Make necessary changes and commit those changes

Now open Contributors.md file in a text editor, add your name


to it, and then save the file. If you go to the project
directory and execute the command git status , you'll see
there are changes.
Add those changes to the branch you just created using
the git
add command:
git add Contributors.md

Now commit those changes using the git commit command:


git commit -m "Add <your-name> to Contributors list"

replacing <your-name> with your name.

5. Push changes to GitHub

Push your changes using the command git push :


git push origin <add-your-name>

replacing <add-your-name> with the name of the branch you


created earlier.

6. Submit your changes for review


Downloaded by sri yoga sankar
If you go to your repository on GitHub, you’ll see a
Compare & pull request button. Click on that button.

Now submit the pull request.

Soon I’ll be merging all your changes into the master


branch of this project. You will get a notification email
once the changes have been merged.

The master branch of your fork won’t have the


changes. In order to keep your fork synchronized with
mine, follow the steps below.

7. Keeping your fork synced with this repository

First, switch to the master branch.


git checkout master

Then add my repo’s url as :


upstream remote url
git remote add upstream https://github.com/Roshanjossey/first-
contributions

This is a way of telling git that another version of this


project exists in the specified url and we’re calling it
upstream. Once the changes are merged, fetch the new
git fetch upstream
version of my repository:

Downloaded by sri yoga sankar


Here we’re fetching all the changes in my fork
(upstream
remote). Now, you need to merge the new revision of my
repository into your master branch.
git rebase upstream/master

Here you’re applying all the changes you fetched to


master
branch. If you push the master branch now, your fork will
also have the changes:
git push origin master

Notice here you’re pushing to the remote named origin.

At this point I have merged your branch <add-your-name> into


my master branch, and you have merged my master
branch into your own master branch. Your branch is
now no longer needed,
so you may delete it:
git branch -d <add-your-name>

and you can delete the version of it in the remote


repository, too:
git push origin --delete <add-your-name>

This isn’t necessary, but the name of this branch


shows its rather special purpose. Its life can be
made correspondingly short.

You now have the skills to contribute to open source


projects across the web.

Downloaded by sri yoga sankar


Documentation

Readability is a primary focus for Python developers, in both project and code
documentation. Following some simple best practices can save both you and others a lot of
time.

Project Documentation
A :file:`README` file at the root directory should give general information to both users and
maintainers of a project. It should be raw text or written in some very easy to read markup,
such as :ref:`reStructuredText-ref` or Markdown. It should contain a few lines explaining the
purpose of the project or library (without assuming the user knows anything about the
project), the URL of the main source for the software, and some basic credit information.
This file is the main entry point for readers of the code.

An :file:`INSTALL` file is less necessary with Python. The installation instructions are often
reduced to one command, such as pip install module or python setup.py install, and
added to the :file:`README` file.
A :file:`LICENSE` file should always be present and specify the license under which the
software is made available to the public.

A :file:`TODO` file or a TODO section in :file:`README` should list the planned development
for the code.
A :file:`CHANGELOG` file or section in :file:`README` should compile a short overview
of the changes in the code base for the latest versions.

Project Publication
Depending on the project, your documentation might include some or all of the following
components:

 An introduction should give a very short overview of what can be done with the
product, using one or two extremely simplified use cases. This is the thirty-second
pitch for your project.
 A tutorial should show some primary use cases in more detail. The reader will follow
a step-by-step procedure to set-up a working prototype.
 An API reference is typically generated from the code (see :ref:`docstrings
<docstring-ref>`). It will list all publicly available interfaces, parameters, and return
values.
 Developer documentation is intended for potential contributors. This can include code
convention and general design strategy of the project.

Sphinx

Downloaded by sri yoga sankar


Sphinx is far and away the most popular Python documentation tool. Use it. It
converts :ref:`restructuredtext-ref` markup language into a range of output formats including
HTML, LaTeX (for printable PDF versions), manual pages, and plain text.

There is also great, free hosting for your Sphinx docs: Read The Docs. Use it. You can
configure it with commit hooks to your source repository so that rebuilding your
documentation will happen automatically.

When run, Sphinx will import your code and using Python's introspection features it will
extract all function, method, and class signatures. It will also extract the accompanying
docstrings, and compile it all into well structured and easily readable documentation for your
project.

Note

Sphinx is famous for its API generation, but it also works well for general project
documentation. This Guide is built with Sphinx and is hosted on Read The Docs

reStructuredText
Most Python documentation is written with reStructuredText. It's like Markdown, but with all
the optional extensions built in.

The reStructuredText Primer and the reStructuredText Quick Reference should help you
familiarize yourself with its syntax.

Code Documentation Advice


Comments clarify the code and they are added with purpose of making the code easier to
understand. In Python, comments begin with a hash (number sign) (#).
In Python, docstrings describe modules, classes, and functions:

def square_and_rooter(x):
"""Return the square root of self times self."""
...

In general, follow the comment section of :pep:`8#comments` (the "Python Style Guide").
More information about docstrings can be found at :pep:`0257#specification` (The Docstring
Conventions Guide).

Commenting Sections of Code


Do not use triple-quote strings to comment code. This is not a good practice, because line-
oriented command-line tools such as grep will not be aware that the commented code is
inactive. It is better to add hashes at the proper indentation level for every commented line.
Your editor probably has the ability to do this easily, and it is worth learning the
comment/uncomment toggle.

Docstrings and Magic

Downloaded by sri yoga sankar


Some tools use docstrings to embed more-than-documentation behavior, such as unit test
logic. Those can be nice, but you won't ever go wrong with vanilla "here's what this does."

Tools like Sphinx will parse your docstrings as reStructuredText and render it correctly as
HTML. This makes it very easy to embed snippets of example code in a project's
documentation.

Additionally, Doctest will read all embedded docstrings that look like input from the Python
commandline (prefixed with ">>>") and run them, checking to see if the output of the
command matches the text on the following line. This allows developers to embed real
examples and usage of functions alongside their source code. As a side effect, it also ensures
that their code is tested and works.

def my_function(a, b):

"""

>>> my_function(2, 3)

>>> my_function('a',

3) 'aaa'

"""

return a * b

Docstrings versus Block comments


These aren't interchangeable. For a function or class, the leading comment block is a
programmer's note. The docstring describes the operation of the function or class:

# This function slows down program execution for some


reason. def square_and_rooter(x):
"""Returns the square root of self times self."""
...

Unlike block comments, docstrings are built into the Python language itself. This means you
can use all of Python's powerful introspection capabilities to access docstrings at runtime,
compared with comments which are optimized out. Docstrings are accessible from both the
doc dunder attribute for almost every Python object, as well as with the built in help()
function.

While block comments are usually used to explain what a section of code is doing, or the
specifics of an algorithm, docstrings are more intended towards explaining other users of
your code (or you in 6 months time) how a particular function can be used and the general
purpose of a function, class, or module.

Writing Docstrings

Downloaded by sri yoga sankar


Depending on the complexity of the function, method, or class being written, a one-line
docstring may be perfectly appropriate. These are generally used for really obvious cases,
such as:

def add(a, b):

"""Add two numbers and return the result."""

return a + b

The docstring should describe the function in a way that is easy to understand. For simple
cases like trivial functions and classes, simply embedding the function's signature (i.e. add(a,
b) -> result) in the docstring is unnecessary. This is because with Python's inspect module, it
is already quite easy to find this information if needed, and it is also readily available by
reading the source code.

In larger or more complex projects however, it is often a good idea to give more information
about a function, what it does, any exceptions it may raise, what it returns, or relevant details
about the parameters.

For more detailed documentation of code a popular style used, is the one used by the NumPy
project, often called NumPy style docstrings. While it can take up more lines than the
previous example, it allows the developer to include a lot more information about a method,
function, or class.

def random_number_generator(arg1,

arg2): """

Summary line.

Extended description of function.

Parameters

arg1 : int

Description of

arg1 arg2 : str

Description of arg2

Returns

int

Downloaded by sri yoga sankar


Description of return value

"""

return 42

The sphinx.ext.napoleon plugin allows Sphinx to parse this style of docstrings, making it easy
to incorporate NumPy style docstrings into your project.

At the end of the day, it doesn't really matter what style is used for writing docstrings; their
purpose is to serve as documentation for anyone who may need to read or make changes to
your code. As long as it is correct, understandable, and gets the relevant points across then it
has done the job it was designed to do.

Downloaded by sri yoga sankar


Unit test reports
Version history
It is very common that a CI/CD pipeline contains a test job that will verify your
code. If the tests fail, the pipeline fails and users get notified. The person that
works on the merge request will have to check the job logs and see where the
tests failed so that they can fix them.

You can configure your job to use Unit test reports, and GitLab will display a
report on the merge request so that it’s easier and faster to identify the
failure without having to check the entire log. Unit test reports currently only
support test reports in the JUnit report format.

If you don’t use Merge Requests but still want to see the unit test report
output without searching through job logs, the full Unit test reports are
available in the pipeline detail view.

Consider the following workflow:

1. Your master branch is rock solid, your project is using GitLab CI/CD and
your
pipelines indicate that there isn’t anything broken.
2. Someone from your team submits a merge request, a test fails and the
pipeline gets the known red icon. To investigate more, you have to go
through the job logs to figure out the cause of the failed test, which
usually contain thousands of lines.
3. You configure the Unit test reports and immediately GitLab collects and
exposes them in the merge request. No more searching in the job logs.
4. Your development and debugging workflow becomes easier, faster and
efficient.

How it works
First, GitLab Runner uploads all JUnit report format XML files as artifacts to
GitLab. Then, when you visit a merge request, GitLab starts comparing the
head and base branch’s JUnit report format XML files, where:

 The base branch is the target branch (usually master).


 The head branch is the source branch (the latest pipeline in each merge
request).

The reports panel has a summary showing how many tests failed, how many
had errors and how many were fixed. If no comparison can be done because
data for the base branch is not available, the panel will just show the list of
failed tests for head.

Downloaded by sri yoga sankar


There are four types of results:

1. Newly failed tests: Test cases which passed on base branch and
failed on head branch
2. Newly encountered errors: Test cases which passed on base
branch and failed due to a test error on head branch
3. Existing failures: Test cases which failed on base branch and
failed on head branch
4. Resolved failures: Test cases which failed on base branch and
passed on head branch

Each entry in the panel will show the test name and its type from the list
above. Clicking on the test name will open a modal window with details of its
execution time and the error output.

How to set it up
To enable the Unit test reports in merge requests, you need to
add artifacts:reports:junit in .gitlab-ci.yml, and specify the path(s) of the
generated test reports. The reports must be .xml files, otherwise GitLab returns
an Error 500.

In the following examples, the job in the test stage runs and GitLab collects
the Unit test report from each job. After each job is executed, the XML reports
are stored in GitLab as artifacts and their results are shown in the merge
request widget.

To make the Unit test report output files browsable, include them with
the artifacts:paths keyword as well, as shown in the Ruby example. To
upload the report even if the job fails (for example if the tests do not
pass), use
the artifacts:when:always keyword.

You cannot have multiple tests with the same name and class in your JUnit
report format XML file.

Python example
This example uses pytest with the --junitxml=report.xml flag to format the
output into the JUnit report XML format:

pytest:

stage: test

Downloaded by sri yoga sankar


script:

- pytest --junitxml=report.xml

artifacts:

when: always

reports:

junit: report.xml

Downloaded by sri yoga sankar


Version control
systems What is version
control?
Version control allows you to keep track of your work and helps you to easily
explore the changes you have made, be it data, coding scripts, notes, etc.
You are probably already doing some type of version control, if you save
multiple files, such
as Dissertation_script_25thFeb.R, Dissertation_script_26thFeb.R,.
This approach will leave you with tens or hundreds of similar files, making
it rather cumbersome to directly compare different versions, and is not
easy to share among collaborators. With version control software such as
Git, version control is much smoother and easier to implement. Using an
online platform like Github to store your files means that you have an
online back up of your work, which is beneficial for both you and your
collaborators.

Git uses the command line to perform more advanced actions and we
encourage you to look through the extra resources we have added at the end
of the tutorial later, to get more comfortable with Git. But until then, here we
offer a gentle introduction to syncing RStudio and Github, so you can start
using version control in minutes.

What are the benefits of using


version control?
Having a GitHub repo makes it easy for you to keep track of collaborative and
personal projects - all files necessary for certain analyses can be held
together and people can add in their code, graphs, etc. as the projects
develop. Each file on GitHub has a history, making it easy to explore the
changes that occurred to it at different time points. You can review other
people’s code, add comments to certain lines or the overall document, and
suggest changes. For collaborative projects, GitHub allows you to assign

Downloaded by sri yoga sankar


tasks to different users, making it clear who is responsible for which part of
the analysis. You can also ask certain users to review your code. For personal
projects, version control allows you to keep track of your work and easily
navigate among the many versions of the files you create, whilst also
maintaining an online backup.

Downloaded by sri yoga sankar


How to get started
Please register on the Github website.

If you are on a personal Windows machine, download and install Git for your
operating system. Below are some recommended installation instructions, to
keep things simple. However, if you know what these options do, and want to
change them to suit you, go ahead:

1. For “Select Components”, check:


 “Git Bash Here”
 “Git GUI Here”
 “Git LFS (Large File Support)”
 “Associate .git* …”
 “Associate .sh …”
2. When prompted to choose the default editor, pick Nano (a
simple terminal editor) or Notepad++ (a simple graphical
editor):
3. For “Adjust your PATH environment”, select: “Use Git from Git
Bash only”
4. For “Choose HTTPS transport backend”, select: “Use the
OpenSSL library”
5. For “Configure the line ending conversions”, select: “Checkout
Windows- style,…”
6. For “Configure the terminal emulator …”, select: “Use MinTTY …”
7. For “Configure extra options”, select: “Enable file system caching”
8. “Enable Git Credential Manager”

If you are on a personal Mac machine, install Git via Homebrew, which is a
package manager for command line programs on Mac. First, open a terminal,
which can be found at ~/Application/Utilities/Terminal.app. Then,
copy and paste this line into the terminal and hit “Enter”:

Copy contents
/usr/bin/ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install
)"

Downloaded by sri yoga sankar


Now enter the following to install Git:

Copy contents
brew install git

Follow any instructions in the terminal window, you may need to enter your
Mac’s
password or agree to questions by typing yes.

The files you put on GitHub will be public (i.e. everyone can see them &
suggest changes, but only the people with access to the repository can
directly edit and add/remove files). You can also have private repositories on
GitHub, which means that only you can see the files. GitHub now offers free
private repositories as standard with up to three collaborators per repository.
They also offer a free education package, with access to software and other
perks, you can apply for one using this link.

How does version control work?


What is a repository?
You can think of a repository (aka a repo) as a “master folder”, everything
associated with a specific project should be kept in a repo for that project.
Repos can have folders within them, or just be separate files.

You will have a local copy (on your computer) and an online copy (on GitHub)
of all the files in the repository.

Downloaded by sri yoga sankar

You might also like