Python Full Notes
Python Full Notes
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:
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 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):
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:
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.
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
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!"
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!")
readable.
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!")
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
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.
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)
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:
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
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.
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)
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.
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 has the following data types built-in by default, in these categories:
Example
Print the data type of the variable x:
x = 5
print(type(x))
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.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= 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
== Equal x == y
!= Not equal x != y
<< 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.
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
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".
Example
a = 200
b = 33
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:
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:
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.")
Example
a = 33
b = 200
if b > a:
pass
Python Loops
Python has two primitive loop commands:
while loops
for loops
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.
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:
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:
The for loop does not require an indexing variable to set beforehand.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Example
Exit the loop when x is "banana":
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
Example
Do not print banana:
Example
Using the range() function:
for x in range(6):
print(x)
Example
Using the start parameter:
for x in range(2,
6): print(x)
Example
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:
for x in adj:
for y in fruits:
print(x, y)
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
Example
print("Hello")
print('Hello')
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:
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.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
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.
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
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
Example
Check if the phrase "ain" is NOT present in the following text:
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:
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))
Example
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
Code Result
\\ Backslash
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
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
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last
position of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Example
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
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:
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:
Note: The search will start at index 2 (included) and end at index 5 (not
included).
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:])
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])
Example
Change the second item:
Example
Print all items in the list, one by one:
Example
Check if "apple" is present in the list:
List Length
To determine how many items a list has, use the len() function:
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:
Example
Insert an item as the second position:
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
Example
The del keyword removes the specified index:
Example
The del keyword can also delete the list completely:
Example
The clear() method empties the list:
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
Example
Make a copy of a list with the list() method:
Example
Join two list:
Another way to join two lists are by appending all the items from list2 into list1,
one by one:
Example
Append list2 into list1:
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.extend(list2)
print(list1)
Example
Using the list() constructor to make a List:
List Methods
Python has a set of built-in methods that you can use on lists.
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
Example
Create a Tuple:
Example
Print the second item in the tuple:
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:
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
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).
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])
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:
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:
Example
Check if "apple" is present in the tuple:
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to 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
Example
Join two tuples:
Example
Using the tuple() method to make a tuple:
Tuple Methods
Python has two built-in methods that you can use on tuples.
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:
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:
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
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:
"cherry"} thisset.add("orange")
Example
Add multiple items to a set, using the update() method:
Example
Get the number of items in a set:
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:
"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.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.
Example
Remove the last item by using the pop() method:
"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:
"cherry"} thisset.clear()
print(thisset)
Example
The del keyword will delete the set completely:
print(thisset)
Example
The union() method returns a new set with all items from both sets:
set3 = set1.union(set2)
print(set3)
Example
The update() method inserts the items in set2 into set1:
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.
Example
Using the set() constructor to make a set:
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference_update() Removes the items in this set that are also included in
anot
specified set
update() Update the set with the union of this set and others
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")
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model":
"Mustang", "year":
1964
}
thisdict["year"] = 2018
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:
Example
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
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
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)
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.
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
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
}
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
the specified value
The try block lets you test a block of code for errors.
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.
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:
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")
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
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")
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"
Modules
Regular Expressions
Text handling
Classes
Objects
Inheritance
Overloading
Polymorphism
Introduction to MySQL
The key function for working with files in Python is the open() function.
"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
f = open("demofile.txt")
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.
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())
Example
f = open("demofile.txt", "r")
print(f.read(5))
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
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:
f = open("demofile.txt", "r")
for x in f:
print(x)
f = open("demofile.txt", "r")
print(f.readline())
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
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
f = open("myfile.txt", "x")
f = open("myfile.txt", "w")
Delete a File
import os
os.remove("demofile.txt")
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
import os
os.rmdir("myfolder")
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")
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import mymodule
a = mymodule.person1["age"]
print(a)
Re-naming a Module
Example
import mymodule as mx
a = mx.person1["age"]
print(a)
import platform
x = platform.system()
print(x)
import platform
x = dir(platform)
print(x)
Example:The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 =
{ "name": "John",
"age": 36,
"country": "Norway"
}
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"]
import re
Example
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.findall("Portugal", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in
position:", x.start())
import re
txt = "The rain in Spain"
x = re.search("Portugal", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt,
2) print(x)
import re
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object
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())
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
class MyClass:
x=5
Example
p1 = MyClass()
print(p1.x)
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)
Example
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.
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
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
p1.age = 40
Example
Delete the age property from the p1 object:
del p1.age
del p1
Example
class Person:
pass
Any class can be a parent class, so the syntax is the same as creating any
other class:
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()
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()
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.
Example
class Student(Person):
def init (self, fname, lname):
Person. init (self, fname, lname)
Example
class Student(Person):
def init (self, fname, lname):
super(). init (fname, lname)
class Student(Person):
def init (self, fname, lname):
super(). init (fname, lname)
self.graduationyear = 2019
Example
class Student(Person):
def init (self, fname, lname,
year): super(). init (fname, lname)
self.graduationyear = year
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.
>>> x=10
>>> y=20
>>> x+y
30
>>> z=10.4
>>> x+z
20.4
Method Overloading
Method Overriding
Method Overriding:
Method Overriding:
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")
Installing mysql
Python can be used in database applications.
MySQL Database
https://www.youtube.com/watch?reload=9&v=GIRcpjg
-3Eg
Navigate your command line to the location of PIP, and type the
following:
C:\Users\Your Name\AppData\Local\Programs\
Python\Python36- 32\Scripts>python -m pip install
mysql-connector-python
demo_mysql_test.py:
import mysql.connector
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
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 pygame.examples.aliens
Once you have installed pygame, you’re ready to create your very first pygame instance.
# initialize pygame
pygame.init()
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.
Arrays are very frequently used in data science, where speed and resources
are very important.
This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
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
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.
import numpy as np
Example
import numpy as np
arr = np.array([1, 2, 3, 4,
5]) print(arr)
Try it Yourself »
print(np. version )
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.
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 −
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
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.
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.
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.
Some of the important methods of the gtk.Window class are listed below −
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.
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-focus This is emitted when the child widget with the focus is
activated usually by the user pressing the Space key.
STOCK_OK
STOCK_STOP
STOCK_YES
STOCK_NO
STOCK_QUIT
STOCK_CANCEL
STOCK_CLOSE
The Button class has the following important methods −
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()
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.
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.
1
set_text()
This sets new text as label
2
get_text()
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
activate-current-link This gets emitted when the user activates a link in the label.
copy-clipboard This gets emitted when text is copied from the label to the
clipboard.
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.
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.
paste-clipboard This is emitted when the contents of the clipboard are pasted into
the entry.
PyMedia is a Python module available on Linux, Windows and cygwin and features the
following:
In this section we are going to see some basics of image processing in python.
#Open Image
im = Image.open("TajMahal.jpg")
Output
>>> im
<PIL.JpegImagePlugin.JpegImageFile image mode = RGB size = 1000x667 at
0x65AB990<
>>> im.size
(1000, 667)
>>> im.format
'JPEG'
>>>
>>> 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 −
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.
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)
Output
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.
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.
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 −
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.
A Simple Client
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 −
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.
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.
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 −
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
Operator Description
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
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 place Method -This geometry manager organizes widgets by placing them
in a specific position in the parent widget.
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.
Installation of SciPy
If you have Python and PIP already installed on a system, then installation of
SciPy is very easy.
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:
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:
print(constants.liter)
Example
import scipy
print(scipy. 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.
Example
Print the constant value of PI:
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:
print(dir(constants))
Unit Categories
The units are placed under these categories:
Metric
Binary
Mass
Angle
Time
Length
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)
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
#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
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)
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)
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)
What is SOAP?
What is ZEEP ?
The first thing that you‟ll need to do is, install the zeep
python
library as:
pip install zeep
Passing Parameters
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.
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.
For example:
git clone https://github.com/this-is-you/first-contributions.git
3. Create a branch
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.)
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
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.
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).
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.
"""
>>> my_function(2, 3)
>>> my_function('a',
3) 'aaa'
"""
return a * b
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
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.
Parameters
arg1 : int
Description of
Description of arg2
Returns
int
"""
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.
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.
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 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.
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
- pytest --junitxml=report.xml
artifacts:
when: always
reports:
junit: report.xml
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.
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:
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
)"
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.
You will have a local copy (on your computer) and an online copy (on GitHub)
of all the files in the repository.