0% found this document useful (0 votes)
2 views22 pages

PYTHON_THEORY

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Data visualization is the representation of data through use of common graphics, such as charts,

plots, infographics, and even animations. These visual displays of information communicate
complex data relationships easy to understand.
Matplotlib and Seaborn are python libraries that are used for data visualization. They have
inbuilt modules for plotting different graphs. While Matplotlib is used to embed graphs into
applications, Seaborn is primarily used for statistical graphs.
PYTHON is a fastest growing programming language in terms of no.of developers using it, no.
of libraries, no. of companies using it and no. of areas we can implement it. Be it m/c learning ,
GUI, s/w development, web development python is used everywhere. That’s why its called a
general purpose language.
PYTHON is an interpreted, object oriented and HLL. It can also be used for procedure oriented
programming. An interpreted language is a language in which the implementations execute
instructions directly without earlier compiling a program into machine language. Python is an
interpreted language, which means the source code of a Python program is converted into
bytecode that is then executed by the Python virtual machine.
object-oriented programming (OOP) is a programming paradigm based on the concept
of objects,[1] which can contain data and code: data in the form of fields (often known
as attributes or properties), and code in the form of procedures (often known as methods).
PYTHON was developed in 1989. It became faous as m/c learning and AI advanced. It is much
simpler than C,C++,JAVA. GOOGLE, YOUTUBE, DROPBOX, YAHOO, NASA etc uses
PYTON.
Anaconda is a distribution( collection of software components built, assembled and configured
so that it can essentially be used "as is") of the Python and R programming
languages for scientific computing (data science, machine learning applications, large-scale data
processing, predictive analytics, etc.), that aims to simplify package
management and deployment. The distribution includes data-science packages suitable
for Windows, Linux, and macOS.
Anaconda consists of jupyterlab, jupyter notebook, qtconsole, spyder , rStudio and all.

Which is used for the data science projects.

Various differences are:—

 Python’s PyCharm is an IDE, anaconda is a set of libraries or distribution of various


libraries packed into one.
 Anaconda is professional data science platform and python IDE’s where we can use as
console as well as GUI .

C PYTHON
Variables are declared in C. Python has no declaration.

C doesn't have native OOP. Python has OOP which is a part of the language.

Pointers are available in C language. No pointers functionality is available in Python.

C is a compiled language. Python is an interpreted language.

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

None Type: NoneType

Sequences allow you to store multiple values in an organized and efficient fashion. There are
seven sequence types: strings, bytes, lists, tuples, bytearrays, buffers, and range objects.
Dictionaries and sets are containers for sequential data.
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
 – type() function is used to determine the type of data type.
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote, or triple-quote. In python there is
no character data type, a character is a string of length one. It is represented by str class.
a tuple is also an ordered collection of Python objects. The only difference between a tuple and
a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class.
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types
in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with
different qualities and usage. A tuple is a collection which is ordered and unchangeable..
Tuples can contain any number of elements and of any datatype (like strings, integers, lists,
etc.)

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of


elements. Each element or value that is inside of a list is called an item. Just as strings are
defined as characters between quotes, lists are defined by having values between square
brackets [ ]

A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its
associated value.

A formatted string literal or f-string is a string literal that is prefixed with f or F. These strings
may contain replacement fields, which are expressions delimited by curly braces {}
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary

Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can
be evaluated in a Boolean context as well and determined to be true or false. It is denoted by
the class bool.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
 Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

** Exponentiation

// Floor division

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example
= x=5

+= x += 3

-= x -= 3

*= x *= 3

/= x /= 3

%= x %= 3

//= x //= 3

**= x **= 3

&= x &= 3

|= x |= 3

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

<<= x <<= 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name

== Equal

!= Not equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Python Logical Operators

Logical operators are used to combine conditional statements:


Operator Description

and Returns True if both statements are true

or Returns True if one of the statements is true

not Reverse the result, returns False if the result is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description

is Returns True if both variables are the same object

is not Returns True if both variables are not the same object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:


Operator Description

in Returns True if a sequence with the specified value is present in


object

not in Returns True if a sequence with the specified value is not presen
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 Shift left by pushing zeros in from the right and let the leftmost bit
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, an
rightmost bits fall off

Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))
Run example »
Example

Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:

print(100 + 5 * 3)
Run example »

The precedence order is described in the table below, starting with the highest precedence at the
top:

Operator Description

() Parentheses

** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not in Comparisons, identity, and membership operators

not Logical NOT

and AND

or OR
If two operators have the same precedence, the expression is evaluated from left to right.

Some decision control statements are:


if – It help us to run a particular code, but only when a certain condition is met or satisfied. A if
only has one condition to check.
if
if-else
nested if
if-elif-else

n = 10
if n % 2 == 0:
print("n is an even number")

n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")

a = 20
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")

x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")

c program
#include<stdio.h>
void main()
{
int x=15;
int y=12;
if(x==y)
printf(“equal\n”);
else if(x>y)
printf(“x is big\n”);
else
printf(“y is big\n”);
}

for loop – A for loop is used to iterate over a sequence that is either a list, tuple, dictionary, or a
set. We can execute a set of statements once for each item in a list, tuple, or dictionary.
print("1st example")

lst = [1, 2, 3]
for i in range(len(lst)):
print(lst[i], end = " \n")

C
a[]={1,2,3}
int n=3;
for(i=0;i<3;i++)
printf(“%d\n”,a[i]);

print("2nd example")
for j in range(0,5):
print(j, end = " \n")

C
for(j=0;j<5;j++)
printf(“j\n”);

m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")

C
int m=5;
int i=0;
while(i<m)
{
printf(“%d\n”,i);
i=i+1;
}
printf(“End”);
PROGRAM 3B

SequenceMatcher is a class that is available in the difflib Python


package.

The difflib module provides classes and functions for comparing


sequences. It can be used to compare files and can produce
information about file differences in various formats.

This class can be used to compare two input sequences or strings. In


other words, this class is useful to use when finding similarities
between two strings on the character level.

The basic idea behind SequenceMatcher() is to find the longest


contiguous matching subsequence (LCS) that contains no “junk”
elements. Junk are the things that we don’t want the algorithm to
match on, like blank lines in ordinary text files, <P> lines in HTML
files, etc. This does not yield minimal edit sequences, but does tend
to yield matches that “look right” to people.
 The ratio() method of this class returns the similarity ratio between the two
arguments passed. The similarity ratio is determined using the formula
below.
2*X/Y
Where X is the number of similar matches and
Y is the total elements present in both the sequences.
PROGRAM 1A

A formatted string literal or f-string is a string literal that is prefixed


with f or F. These strings may contain replacement fields, which are
expressions delimited by curly braces {}. While other string literals
always have a constant value, formatted strings are really
expressions evaluated at run time.
F-strings are faster than the two most commonly used string
formatting mechanisms, which are % formatting and str.format()
Strings in Python are usually enclosed within double quotes ("" ) or
single quotes (''). To create f-strings, you only need to add an f or
an F before the opening quotes of your string.
When using f-Strings to display variables, you only need to specify
the names of the variables inside a set of curly braces {}. And at
runtime, all variable names will be replaced with their respective
values.
If you have multiple variables in the string, you need to enclose
each of the variable names inside a set of curly braces.
In Python Dictionary, items() method is used to return the list with
all dictionary keys with values.
Dictionary holds key : value pair.
In Python Dictionary, items() method is used to return the list with
all dictionary keys with values.
Dictionary holds key : value pair.
In Python Dictionary, items() method is used to return the list with
all dictionary keys with values.
name of dictionary = {key:value}
The items, that is, the data that is stored in the dictionary are
unordered and mutable. Thus, they can be changed after the
creation of the dictionary. However, the items cannot be duplicated
within the same dictionary. These items can be of any data type,
including numeric and characters such as integers, strings, floats,
complex numbers. Boolean type, etc.

The items () method in the dictionary is used to return each item in


a dictionary as tuples in a list. Thus, the dictionary key and value
pairs will be returned in the form of a list of tuple pairs.
Syntax of items () method: dictionary_name.items ()
The items () method does not take any parameters.
Return Value from items ()
When you use the items () method on a dictionary, the key and
value pair stored in it will be displayed in the form of tuples in a list.
Note that the returned list is a view of the items stored in the
dictionary. The method does not change a dictionary into a list. Also,
all the changes that will be done in the dictionary will be shown in
the list view as well.
PROGRAM 1B
In mathematics, the Fibonacci sequence is a sequence in which each number is the sum of the two
preceding ones.

PROGRAM 2A
PROGRAM 2B
The hex() function converts the specified number into a hexadecimal value. The returned string
always starts with the prefix 0x

PROGRAM 3A

Split a string into a list where each word is a list item:


You can specify the separator, default separator is any whitespace.
PROGRAM 4
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:

Now the Pyplot package can be referred to as plt.

Matplotlib is a comprehensive library for creating static, animated, and


interactive visualizations in Python. Matplotlib makes easy things easy and
hard things possible.

 Create publication quality plots.


 Make interactive figures that can zoom, pan, update.
 Customize visual style and layout.
 Export to many file formats.
 Embed in JupyterLab and Graphical User Interfaces.
 Use a rich array of third-party packages built on Matplotlib.

https://www.rose-hulman.edu/class/cs/csse120/Resources/C/Python_vs_C.html
https://www.interviewbit.com/blog/difference-between-c-and-python/

PROGRAM 4A
The . bar() function returns a chart/graph that represents categorical data using vertical bars
with heights proportional to the values that they represent.
Show() . Display a figure. When running in ipython with its pylab mode, display all figures and
return to the ipython prompt.

PROGRAM 4B
The Matplotlib module has a method for drawing scatter plots, it needs two
arrays of the same length, one for the values of the x-axis, and one for the
values of the y-axis:

x = [5,7,8,7,2,17,2,9,4,11,12,9,6]

y = [99,86,87,88,111,86,103,87,94,78,77,85,86]

The x array represents the age of each car.


The y array represents the speed of each car.

Scatter Plot Explained


The x-axis represents ages, and the y-axis represents speeds.

What we can read from the diagram is that the two fastest cars were both 2
years old, and the slowest car was 12 years old.

Note: It seems that the newer the car, the faster it drives, but that could be a
coincidence, after all we only registered 13 cars.

You might also like