Python Atb
Python Atb
1. Simple Language:
Coding in Python is very simple. A user with the non-coding background can easily learn this language if
they have the good logical skill as python use basic English language for coding.
Python is a freeware and open source software so it can be easily downloaded and used. It doesn’t require
any activation key or subscription to work on it.
3. Portability :
Python can run any operating system. Also, we use the python code written on one system onto another
system without making any changes to the code.
This feature is provided to the user as to extend python from its initial state.
An extensible software program, for example, might support add-ons or plug-ins that add extra functionality
to the program.
In this feature the code which execute instruction directly and freely, without previously compiling a
program into machine language instructions.
6. Object Oriented :
Python Functionality
2. It can be used to connect to the database system and also perform a various task like read and modify.
• Number
• String
• List(A list can store a sequence of objects in a certain order such that you can index into the list, or
iterate over the list. List is a mutable type meaning that lists can be modified after they have been
created.)
• Tuple(A tuple is similar to a list except it is immutable. There is also a semantic difference between
a list and a tuple)
• Dictionary(A dictionary is a key-value store. It is not ordered and it requires that the keys are
hashable. It is fast for lookups by key)
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
It is used when a statement is required syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes.
Indentation is required for Python. It specifies a block of code. All code within loops, classes, functions, etc
is specified within an indented block. If python code is not indented necessarily, it will not execute
accurately and will throw errors as well.
Arrays and lists store data in same way . But, arrays can hold only a single data type elements whereas lists
can hold any data type elements.
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file
by using dump function, this process is called pickling. While the process of retrieving original Python
objects from the stored string representation is called unpickling.
Number data types store numeric values. Number objects are created when you assign a value to them. For
example
var1= 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
For example
del var1
del var1, var2
x=0.6
x=3.9 * x * (1-x)
Operators are the constructs that can manipulate the value of operands. Like different programming
languages, Python supports the following operators:
• Arithmetic operators
• Relational operators
• Assign operators
• Logical operators
Arithmetic Operators
print (13//5)
Perform calculation
print (13+5) ;
print (13-5) ;
print (2*5) ;
print (13/5);
print (13%5)
print (2**3)
Relational Operators
Assign Operator
X =10 ; print(X)
Logical Operators
import calendar
calendar.prcal(2019)
Python Strings
s="PYTHON"
print (s[0:4])
print (s[1:3])
print (s[:2])
print (s[2:])
print (s [:])
print (s)
print(s[-4:-1])
Update String
You can "update" an existing string by (re)assigning a variable to another string. The new value can be
related to its previous value or to a completely different string altogether.
For example-
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and
enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One of the differences
between them is that all the items belonging to a list can be of different data type. The values stored in a list
can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator.
For example-
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
Next Example
UPDATE
DELETE
LIST Indexing
print(list1[3])
print(list1[3][1])
Conversion
list1 = list(aTuple)
print ("List elements : ", list1) str="Hello World"
list2=list(str)
print ("List elements : ", list2)
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are enclosed within parenthesis. The main difference
between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed,
while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-
only lists.
For example-
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists –
Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl
and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python object.
Prices = {"Honda":40000, "Suzuki":50000, "Mercedes":85000, "Nissan":35000,
"Mitsubishi": 43000}
print (Prices)
Staff_Salary = { 'Omar Ahmed' : 30000 , 'Ali Ziad' :24000,'Ossama Hashim': 25000, 'Majid
Hatem':10000}
print(Staff_Salary)
STDMarks={"Salwa Ahmed":50, "Abdullah Mohamed":80, "Sultan Ghanim":90}
print(STDMarks)
next examples
example 2
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
Dictionaries have no concept of order among the elements. It is incorrect to say that the elements are
"out of order"; they are simply unordered.
next examples
Updating and Adding a New Item to a Dictionary
A Pandas data frame can be created using various input forms such as the following:
• List
• Dictionary
• Series
• Numpy ndarrays
• Another data frame
Sometimes you have to import the Pandas package since the standard Python distribution doesn’t
come bundled with the Pandas module. A lightweight alternative is to install Numpy using popular
the Python package installer pip. The Pandas library is used to create and process series, data frames,
and panels.
A Pandas Series
A series is a one-dimensional labeled array capable of holding data of any type (integer, string,
float, Python objects, etc.). Listings hows how to create a series using the Pandas library.
Creating a Series Using the Pandas Library
import pandas as pd
import numpy as np
data = np.array([90,75,50,66])
s = pd.Series(data,index=['A','B','C','D'])
print (s)
A 90
B 75
C 50
D 66
print (s[1])
75
Ali 55
Ahmed 92
Omar 83
print (s[1:])
Ahmed 92
Omar 83
A data frame is a two-dimensional data structure. In other words, data is aligned in a tabular
fashion in rows and columns. In the following table, you have two columns and three rows of data.
Listing shows how to create a data frame using the Pandas library.
Name Age
ahmed 35
ali 17
omar 25
You can retrieve data from a data frame starting from index 1 up to the end of rows.
DataFrame1[1:]
Name Age
1 Ali 17
2 Omar 25
import pandas as pd
data = {'Name':['Ahmed', 'Ali', 'Omar','Salwa'],'Age':[35,17,25,30]}
dataframe2 = pd.DataFrame(data, index=[100, 101, 102, 103])
print (dataframe2)
Age Name
100 35 Ahmed
101 17 Ali
102 25 Omar
103 30 Salwa
You can select only the first two rows in a data frame.
dataframe2[:2]
Age Name
100 35 Ahmed
101 17 Ali
dataframe2['Name']
100 Ahmed
101 Ali
102 Omar
103 Salwa
Name: Name, dtype: object
Key Differences:
Pandas provides us with some powerful objects like DataFrames and Series which are very useful
for working with and analyzing data whereas numpy library which provides objects for multi-
dimensional arrays, Pandas provides in-memory 2d table object called Dataframe.
Pandas works when data is in Tabular Format whereas Numpy works really well when data is
Numeric.
Numpy performs real good when there are 50000 and less rows whereas pandas works really well
when there are around 500000 or more rows.
If else Statement
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
The elif Statement
Nested IF Statements
LOOP
While Loop
count = 0
FOR Loop
Use of Break
numbers=[11,33,55,39,55,70,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number')
Use of Continue
ticket=4
while ticket>0:
print ("Your ticket number is ", ticket) ticket -=1
Numpy is a Python package that stands for “numerical Python.” It is a library consisting of
multidimensional array objects and a collection of routines for processing arrays.
The Numpy library is used to apply the following operations:
• Operations related to linear algebra and random number generation
• Mathematical and logical operations on arrays
• Fourier transforms and routines for shape manipulation
For instance, you can create arrays and perform various operations such as adding or subtracting
arrays, as shown in Listing
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[7,8,9],[10,11,12]])
np.add(a,b)
array([[ 8, 10, 12], [14, 16, 18]])
np.subtract(a,b) #Same as a-b
array([[-6, -6, -6], [-6, -6, -6]])
Data Visualization
A fundamental part of the data scientist’s toolkit is data visualization. Although it is very easy to create
visualizations, it’s much harder to produce good ones. There are two primary uses for data visualization:
To explore data
To communicate data
Matplotlib
This is useful for simple bar charts, line charts, and scatterplots. In particular, we will be using the
matplotlib.pyplot module. In its simplest use, pyplot maintains an internal state in which you build up a
visualization step by step. Once you’re done, you can save it (with savefig()) or display it (with show()).
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
In the first example, the x-axis and y-axis were divided by the value of 10 and 2 respectively. Let’s make it 5
and 1.
import matplotlib.pyplot as plt
import numpy as np
x = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5]
plt.plot(x, y, 'b')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(np.arange(0, 51, 5))
plt.yticks(np.arange(0, 11, 1))
plt.show()
Bar Chart
A bar chart can also be a good choice for plotting histograms of bucketed numeric values,in order to visually
explore how the values are distributed
Scatterplots
A scatterplot is the right choice for visualizing the relationship between two paired sets of
data. For example, Figure illustrates the relationship between the number of friends
your users have and the number of minutes they spend on the site every day:
friends = [ 70, 65, 72, 63, 71, 64, 60, 64, 67]
minutes = [175, 170, 205, 120, 220, 130, 105, 145, 190]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
plt.scatter(friends, minutes)
# label each point
for label, friend_count, minute_count in zip(labels, friends, minutes):
plt.annotate(label,xy=(friend_count, minute_count), # put the label with its point
xytext=(5, -5), # but slightly offset
textcoords='offset points')
plt.title("Daily Minutes vs. Number of Friends")
plt.xlabel("# of friends")
plt.ylabel("daily minutes spent on the site")
plt.show()