Data Analytics Using Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Data Analytics using Python

History of Python
 Python was developed by Guido van Rossum in the late eighties

and early nineties at the National Research Institute for Mathematics and Computer

Science in the Netherlands.

 Python is derived from many other languages, including ABC,

Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other

scripting languages.

What is Python

Python is a general-purpose, dynamic, high-level, and interpreted programming


language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.

Python is an easy-to-learn yet powerful and versatile scripting language, which


makes it attractive for Application Development.

With its interpreted nature, Python's syntax and dynamic typing make it an ideal
language for scripting and rapid application development.

Python supports multiple programming patterns, including object-oriented,


imperative, and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. It is


a multipurpose programming language because it can be used with web, enterprise,
3D CAD, etc.
Python makes development and debugging fast because no compilation step is
included in Python development, and the edit-test-debug cycle is very fast.

Python is an open-source, cost-free programming language. It is utilized in several


sectors and disciplines as a result.

In Python, code readability and maintainability are important. As a result, even if


the code was developed by someone else, it is easy to understand and adapt by
some other developer.

Python has many third-party libraries that can be used to make its functionality
easier. These libraries cover many domains, for example, web development,
scientific computing, data analysis, and more.

Python Basic Syntax

There is no use of curly braces or semicolon in Python programming language. It is


English-like language. But Python uses the indentation to define a block of code.
Indentation is nothing but adding whitespace before the statement when it is
needed. For example -

1. Print (“Cambridge College”)

In the above example, the statements that are the same level to the right belong to
the function. Generally, we can use four whitespaces to define indentation.

Python is a case-sensitive language, which means that uppercase and lowercase


letters are treated differently. For example, 'name' and 'Name' are two different
variables in Python.

In Python, comments can be added using the '#' symbol. Any text written after the
'#' symbol is considered a comment and is ignored by the interpreter. This trick is
useful for adding notes to the code or temporarily disabling a code block. It also
helps in understanding the code better by some other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords
in Python that cannot be used as variable names. These terms are used in the
language for particular reasons and have fixed meanings. If you use these
keywords, your code may include errors, or the interpreter may reject them as
potential new Variables.

Python Features

Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.

 Easy-to-read − Python code is more clearly defined and visible to the eyes.

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

 A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.

 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.

 Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

 Databases − Python provides interfaces to all major commercial databases.

 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.

 Scalable − Python provides a better structure and support for large programs than
shell scripting. It supports functional and structured programming methods as
well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for
building large applications

. It provides very high-level dynamic data types and supports dynamic type
checking.

 IT supports automatic garbage collection.  It can be easily integrated with C,


C++, COM, ActiveX, CORBA, and Java.

Where is Python used?

Python is a general-purpose, popular programming language, and it is used in


almost every technical field. The various areas of Python use are given below.

o Data Science: Data Science is a vast field, and Python is an important


language for this field because of its simplicity, ease of use, and availability
of powerful data analysis and visualization libraries like NumPy, Pandas, and
Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used
in GUI - Graphical User Interface-based Desktop Applications. There are
better languages for this field, but it can be used with other languages for
making Applications.
o Software Development: Python is considered one of the best software-
making languages. Python is easily compatible with both from Small Scale to
Large Scale software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a
perfect language for artificial intelligence and machine learning because of
the availability of powerful libraries such as TensorFlow, Keras, and
PyTorch.
o Web Applications: Python is commonly used in web development on the
backend with frameworks like Django and Flask and on the front end with
tools like JavaScript and HTML.
o Machine Learning: Python is widely used for machine learning due to its
simplicity, ease of use, and availability of powerful machine learning
libraries.
o Speech Recognition: Python can be used for speech recognition applications
through libraries such as SpeechRecognition and PyAudio.
o Gaming: Python has libraries like Pygame, which provide a platform for
developing games using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices
like Raspberry Pi, Arduino, and others.

Python Popular Frameworks and Libraries

Python has wide range of libraries and frameworks widely used in various fields
such as machine learning, artificial intelligence, web applications, etc. We define
some popular frameworks and libraries of Python as follows.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy,
etc.
o Mathematics - Numpy, Pandas, etc.
o SQLite: a library for working with SQL databases

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or


other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9). Python does not
allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.Here are naming conventions for

Python identifiers –

 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.

 Starting an identifier with a single leading underscore indicates that the identifier
is private.
 Starting an identifier with two leading underscores indicates a strongly private
identifier.

 If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name. Reserved Words The following list shows the
Python keywords. These are reserved words and you cannot use them as constant
or variable or any other identifier names

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters
after the

# and up to the end of the physical line are part of the comment and the Python
interpreter ignores them. #!/usr/bin/python

# First comment print"Hello, Python!"# second comment

Python - Variable

Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory. Based on the
data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

counter =100 # An integer assignment

miles =1000.0# A floating point

name ="John"# A string

print (counter)

print (miles)

print (name)

KEYWORDS

The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python

keywords contain lowercase

INPUT Function:

To get input from the user you can use the input function. When the input function
is
called the program stops running the program, prompts the user to enter something
at the
keyboard by printing a string called the prompt to the screen, and then waits for the
user to
press the Enter key. The user types a string of characters and presses enter. Then
the input
function returns that string and Python continues running the program by executing
the next
statement after the input statement.

Python provides the function input(). input has an optional parameter, which is the
prompt string.

For example, n=int(input(“Enter No “))

Indentation

Code blocks are identified by indentation rather than using symbols like curly
braces.

Without extra symbols, programs are easier to read. Also, indentation clearly
identifies which

block of code a statement belongs to. Of course, code blocks can consist of single
statements,

too. When one is new to Python,


Operators
In Python programming, Operators in general are used to perform operations on
values and variables. These are standard symbols used for the purpose of logical
and arithmetic operations. In this article, we will look into different types
of Python operators.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.

Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
1. Python Arithmetic Operators
 Mathematical operations including addition, subtraction, multiplication, and
division are commonly carried out using Python arithmetic operators.
 They are compatible with integers, variables, and expressions.
 In addition to the standard arithmetic operators, there are operators for
modulus, exponentiation, and floor division.

Operator Name Example
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
// Floor Division 9//2 = 4
a =int(input(“enter no “)
b = int(input(“enter no”)
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)

Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators
compare the values of the two operands and return a true or false Boolean value in
accordance. The example of comparison operators are ==, !=, <=, >=, >, <. In the
below table, we explain the works of the operators.

a =int(input(“enter no “)
b = int(input(“enter no”)
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)

Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left
operand. There are some examples of assignment operators like =, +=, -=, *=, %=,
**=, //=. In the below table, we explain the works of the operators.

a =int(input(“enter no “)
b = int(input(“enter no”)
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)

Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The
examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR
(^), negation (~), Left shift (<<), and Right shift (>>). Consider the case below.

a =int(input(“enter no “)
b = int(input(“enter no”)
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)

Logical Operators
The assessment of expressions to make decisions typically uses logical operators.
The examples of logical operators are and, or, and not. In the case of logical AND,
if the first one is 0, it does not depend upon the second one. In the case of logical
OR, if the first one is 1, it does not depend on the second one. Python supports the
following logical operators. In the below table, we explain the works of the logical
operators.

a=5 # initialize the value of a


print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5
)))

Membership Operators
The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data structure;
otherwise, it returns false.

x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)

A conditional statement as the name suggests itself, is used to handle conditions


in your program. These statements guide the program while making decisions
based on the conditions encountered by the program. In this article, we will explore
three conditional statements in Python: if statement, if-else statements, if-elif-else
ladder.

If Statement

The if statement is a conditional statement in Python used to determine whether a


block of code will be executed. If the program finds the condition defined in the if
statement true, it will execute the code block inside the if statement.

num = 5
if (num < 10):
print(“Num is smaller than 10”)

If-else Statement
As discussed above, the if statement executes the code block when the condition is
true. Similarly, the else statement works in conjuncture with the if statement to
execute a code block when the defined if condition is false.

num = 5
if(num > 10):
print(“number is greater than 10”)
else:
print(“number is less than 10”)

Elif statements

In Python, we have one more conditional statement called “elif” statements. “elif”
statement is used to check multiple conditions only if the given condition is false.
It’s similar to an “if-else” statement and the only difference is that in “else” we will
not check the condition but in “elif” we will check the condition.

“elif” statements are similar to “if-else” statements but “elif” statements evaluate
multiple conditions.

num = 10
if (num == 0):
print(“Number is Zero”)

elif (num > 5):


print(“Number is greater than 5”)

else:
print(“Number is smaller than 5”)

LOOPING STATEMENTS
The following loops are available in Python to fulfil the looping needs. Python
offers 3 choices for running the loops. The basic functionality of all the techniques
is the same, although the syntax and the amount of time required for checking the
condition differ.

We can run a single statement or set of statements repeatedly using a loop


command.

The following sorts of loops are available in the Python programming language.

The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating
through a list, tuple, dictionary, or other iterable objects of Python. The process of
traversing a sequence is known as iteration.

EX : for I in range(0,20)

Print(i)

It will print series 0-19 nos

While Loop
While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is executed
once the condition changes to false.

counter = 0
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

Break Statement
It stops the execution of the loop when the break statement is reached.
for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.

for a string in "Python Loops":


pass
print( 'Last Letter:', string)

Continue Statement
It returns the control to the beginning of the loop.

for string in "Python Loops":


if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)

What is a Switch Statement in Python?


In general, the switch is a control mechanism that tests the value stored in a
variable and executes the corresponding case statements. Switch case statement
introduces control flow in your program and ensures that your code is not
cluttered by multiple ‘if’ statements.

lang = input("What's the programming language you want to learn? ")

match lang:

case "JavaScript":
print("You can become a web developer.")
case "Python":
print("You can become a Data Scientist")

case "PHP":
print("You can become a backend developer")

case "Solidity":
print("You can become a Blockchain developer")

case "Java":
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is solving problems.")

Functions

A Python function is a block of organized, reusable code that is used to perform a


single, related action. Functions provide better modularity for your application and
a high degree of code reusing.

Parts of a function definition:

 def - A function begins with the word def


 name - def is followed by the function's name, here foo
The name is chosen by the programer to reflect what the function does
Here "foo" is just a CS nonsense word
 parenthesis - the name is followed by a pair of parenthesis and a colon ():
Functions and parenthesis pairs () frequently go together in Python syntax
 body lines - Indented within the def are the "body" lines of code which
make up the function.
When a function runs, the computer runs its body lines from top to bottom.
Key points: A function starts with the word "def", has a name, and some lines of
code

Python Library Functions

In Python, standard library functions are the built-in functions that can be used
directly in our program. For example,

 print() - prints the string inside the quotation marks


 sqrt() - returns the square root of a number
 pow() - returns the power of a number

Advantages of Python Functions

Pause We can stop a program from repeatedly using the same code block by
including functions.

o Once defined, Python functions can be called multiple times and from any
location in a program.
o Our Python program can be broken up into numerous, easy-to-follow
functions if it is significant.
o The ability to return as many outputs as we want using a variety of
arguments is one of Python's most significant achievements.
o Python programs have always incurred overhead when calling functions.

There are three types of functions in Python:

 Built-in functions, such as help() to ask for help, min() to get the minimum
value, print() to print an object to the terminal,… You can find an overview with
more of these functions
 Ex : len(), abs(),pi() sum(),type()
 User-Defined Functions (UDFs), which are functions that users create to help
them out; And
 Ex : def (x,y)
Return(x-y)
Print(sub(5,2))

 Anonymous functions, which are also called lambda functions because they are
not declared with the standard def keyword.
lambda_ = lambda argument1, argument2: argument1 + argument2;

print( "Value of the function is : ", lambda_( 20, 30 ) )


print( "Value of the function is : ", lambda_( 40, 50 ) )

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy