Beruflich Dokumente
Kultur Dokumente
Introduction to Script
Programming Languages:
1. Compiler based
2. Explicit Declaration of data types
Example:
int a=100;
float b=200.00;
String s="python" or 'python';
3. Difficult to Inegrate with Other Technologies
1. Imperative Paradigm:
It consists of commands for the computer to perform.
1. Procedural Programming Paradigm
It is based on the concept of using procedures. Example: C, Pascal
Declarative Paradigm:
A style of building the structure and elements of computer programs,without describing its
control flow.
1. Functional Programming Paradigm
It is the process of building software by composing pure functions.
Example: LISP (List Processing)
INTRODUCTION TO PYTHON
✓ What is Python?
✓ Why Python?
✓ Who Uses Python?
✓ Characteristics of Python
✓ History of Python
✓ What is PSF?
✓ Python Versions
✓ Features of Python
✓ Limitations of Python
✓ Python in the real world
✓ How to Install Python
What is Python?
Python is an easy to learn (clean) and powerful programming language. The application
development process much faster and easier. It is under GNU or General Public License
(GPL)
WHY PYTHON?
1 Software Quality
2 Developer Productivity
3 Program Portability
4 Support Libraries
5 Enjoyment
Characteristics of Python
1) General-purpose programming
2) Automatic memory management
3) It has a large and comprehensive standard library
4) Python is a strong high level language
5) Python is interpreted
6) Python is reflective
7) It is a dynamical type
8) It is an open source
9) Automatic garbage collection.
10) It is a multi-paradigm
History of Python
1 Invented in 1990s by Guido Van Rossum at CWI (Centrum Wiskunde & Informatica).
2 Python was named for the BBC TV show "Monty Python's Flying Circus".
3 Open source and interpreted language.
4 Used by Google and Microsoft, increasingly popular.
Python Versions:
There are a many version of python started from 1994 to current date.
Python Version Released Date
Python 1.0 January 1994
Python 2.0 16 October 2000
Python 2.7 3 July 2010
Python 3.0("Python 3000" or "Py3K) 3 December 2008
Python 3.3 29 September 2012
Python 3.6 December 23, 2016
Features of Python
1 Easy to Use
2 Interpreted Language
3 Cross-platform language (Mac OS X, Windows, Linux, and Unix)
4 Free and Open Source
5 Object-Oriented language
6 Large Standard Library
7 GUI Programming
8 Python is easy to integrate with other language like C, C++ and JAVA etc
TEXT EDITORS
Sublime Text
Koding
NetBeans
PyCharm
Geany
APPLICATIONS
Blender
Openshot Video Editor
Ubuntu Software Centre
BitTorrent
Juice
VIDEO GAMES
Battlefield 2
Civilization IV
Vega Strike
Unity of Command
Bridge Commander
PYTHON_CMS_3
Different Modes in PYTHON
✓ RUN Modes in PYTHON
✓ Interactive Mode
✓ Print() and input() functions
✓ Quit from interactive Mode
✓ Script Mode
✓ Python File Extensions
✓ SETTING PATH IN Windows
✓ Clear screen inside python
✓ Working with Python in Unix/Linux
✓ What is UNIX?
✓ RUN MODES
✓ What is Shebang?
✓ A few changes in Python 3.0
✓ Python Comments
✓ Python Implementation Alternatives
✓ The Zen of Python
✓ Uses of Python in Data Science
✓ Uses of Python in Data Science
✓ IoT Companies, Areas
✓ USES OF PYTHON IN IOT
1 Interactive mode
Python offers a comfortable command line interface with the Python shell, which is also
known as the "Python interactive shell".
Python print():
The print() function prints the given object to the standard output device (screen) or to the
text stream file.
Syntax:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
print() Parameters
objects - object to the printed.
sep-objects are separated by sep.Default value:''
end - end is printed at last
file - must be an object with write(string) method.
flush - If True, the stream is forcibly flushed. Default value: False
Example:
print("a","b",sep="")
print("a","b",sep=":-)")
Raw_Input: It is used to read data from the user or from the keyboard:
Syntax
raw_input("Message")
Input: It is used to read data from the user or from the keyboard:
Syntax:
input("Enter Any Number")
Example:
age = input("What is your age? ")
print("Your age is: ", age)
Example:
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
Example:
colors = input("Your favourite colours? ")
Your favourite colors? ["red","green","blue"]
print(colors)
Example1:
1. Goto IDLE, Select File and click on New or Ctrl+N (to Open New Window)
2. Enter required python statements or commands
Clear screen:
There is no Python command for IDLE in windows, to do clear the interactive screen. We can
perform using the following simple commands..!!
$python
$python -v
$python ---version
$man python
What is Shebang?
The term shebang refers to the "#!" located at the top of many script files that points to the
path of the associated program. It has the following alias Names:
1. She-bang
2. Hashbang
3. Pound-bang
4. Hash-pling
5. Crunchbang....etc..!!
The usage of #!/usr/bin/python plays a role if the script is executable, and called without the
preceding language.
Example:
#!/usr/bin/python
print("Hello Welcome to PYTHON with Unix")
Save with .py Extension and Run it...!!
A few changes in Python 3.0:
1 Print is now a function
2 Views and iterators instead of lists
3 The rules for ordering comparisons have been simplified.
4 There is only one integer type left, i.e. int. long is int as well.
5 The division of two integers returns a float instead of an integer.
6 Text Vs. Data Instead Of Unicode Vs. 8-bit
Python Comments
Anything after a # is ignored by Python.
Why comment?
Describe what is going to happen in a sequence of code
Document who wrote the code or other ancillary information
Turn off a line of code - perhaps temporarily
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:
"""This is also a
perfect example of
multi-line comments"""
"""print("Comm")
print("Comm")
print("Comm")"""
What is IoT?
A network of internet-connected objects able to collect and exchange data using embedded
sensors.
IoT Companies
Google, Amazon, AT&T, Cisco, IBM, Honeywell, Apple etc............
IoT Areas:
1. Smart Health
2. Smart Living
3. Smart Industry
4. Animal Tracking
5. Smart Agriculture
6. Smart Homes
7. Smart Transport
8. Smart Energy
8. Smart Cities
IoT Features:
1 Product identity management
2 Real-time data management
3 Security & access control
4 Rich analytics & insights
5 Product connection management
6 LOCAL CLOUD GATEWAY.
3.0 onwards
.pyw==Python script for Windows
.pyz ==> Python script archive (Compressed or Zip formated)
Clear screen:
There is no Python command for IDLE in windows, to do clear the interactive screen.
We can perform using the following simple commands..!!
1. Using Keyboard shortcut: (UNIX)
Press CTRL + L
2. print("\n"*10) (in Windows)
3. clear="\n"*10
print(clear)
Working with Python in Unix/Linux
What is Unix?
Unix is a family of multitasking, multiuser computer operating systems. In Unix
Python default installed, It is called standard PYTHON.
$python
$python -v
$python ---version
$man python
What is Shebang?
The term shebang refers to the "#!" located at the top of many script files that points
to the path of the associated program. It has the following alias Names:
1. She-bang
2. Hashbang
3. Pound-bang
4. Hash-pling
5. Crunchbang....etc..!!
The usage of #!/usr/bin/python plays a role if the script is executable, and called
without the preceding language.
Example:
#!/usr/bin/python
print("Hello Welcome to PYTHON with Unix")
Save with .py Extension and Run it...!!
Some changes in Python 3.0:
1 Print is now a function
2 Views and iterators instead of lists
3 The rules for ordering comparisons have been simplified.
4 There is only one integer type left, i.e. int. long is int as well.
5 The division of two integers returns a float instead of an integer.
6 Text Vs. Data Instead Of Unicode Vs. 8-bit
Define IDE?
An Integrated Development Environment (IDE) is a software application that
provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor, build automation
tools, a compiler or interpreter and a debugger.
4 Scientific Tools
i IPython Notebook integration
ii Interactive Python console
Components of Pycharm:
It has maily the following Components:
1. Menu or Dashboard
2. Project Panel
3. Code Editor
4. Console or Output Window
Debugging in PYCHARM:
It is the process of identifying and fixing problems in Code. The following short-cut
keys are required to debug..!!
1 Step Over (F8)
2 Step Into (F7)
3 Force Step Into (Alt+Shift+F7)
4 Step Out (Shift+F8)
5 Run to Cursor (Alt+F9)
What is Anaconda?
The Most Popular Python Data Science Platform.
Anaconda is a freemium open source distribution of the Python and R programming
languages for large-scale data processing, predictive analytics, and scientific
computing, that aims to simplify package management and deployment
NOTE:
Other Python Scientific Distributions: WinPython, Python(x,y)
Coding Environments
Anaconda comes with two popular IDEs :
1 Spyder
2 Jupyter (Ipython) Notebook
What is Spyder?
It is a powerful interactive development environment for the Python language with
advanced editing, interactive testing, debugging and introspection features and a
numerical computing environment.
General features:
1. iPython==> Enhanced interactive Python interpreter
2. NumPy ==> Nummerical PYthon-Linear Algebra
3. SciPy ==> Scientific Python-Signal and Image Processing
4. Matplotlib ==> Interactive 2D/3D plotting
5. Pandas ==> For Data Analysis with Data Frames
Project Explorer:
Spyder allows users to associate a given directory with a project. This has two main
advantages:
1 Projects remember the list of open files in Editor. This permits to easily work on
several coding efforts at the same time.
2 The project’s path is added to the list of paths Python looks modules for, so that
modules developed as part of a project can be easily imported in any console.
Editor:
Syntax coloring (Python, C/C++, Fortran)
breakpoints and conditional breakpoints (debugger: pdb)
run or debug Python scripts (see console features)
run configuration dialog box:
working directory
command line options
run in a new Python interpreter or in an existing Python interpreter or IPython
client
Python interpreter command line options
Console:
1 all consoles are executed in a separate process
2 code completion/calltips and automatic link to help
3 open Python interpreters or basic terminal command windows
4 run Python scripts
Jupyter Notebook:(http://jupyter.org/)
Formerly known as the IPython Notebook. It is a server-client application that allows
editing and running notebook documents via a web browser.
The Jupyter Notebook is an open-source web application that allows you to create
and share documents that contain live code, equations, visualizations and narrative
text.!
What is Conda?
It is an open source package management system and environment management
system for installing multiple versions of software packages and their dependencies
and switching easily between them.
Syntax:
pip list [options]
Options
-o, --outdated
List outdated packages
-u, --uptodate
List uptodate packages
-e, --editable
List editable projects.
-l, --local
If in a virtualenv that has global access, do not list globally-installed packages.
--user
Only output packages installed in user-site.
VARIABLES IN PYTHON
Define Variable?
A variable is a name that refers to a value. Variables point to the memory location
where data is read and modified.
What is an identifier?
An identifier is just the name of the variable.
camelCase:
In Real Time Projects, camelCase is a naming convention in which a name is formed of
multiple words that are joined together as a single word for better readability.
NOTE:
Programmer's perspective, PascalCase means the first char should be capitalized
while camelCase means the first char should be lowercased.
Constants:
Fixed values such as numbers, letters, and strings, are called “constants”.
What is Literal?
a literal is a notation for representing a fixed value.
What is a literal in Python?
Python supports the following literals:
I. String literals:
II.Numeric literals: 1 Int 2 Long 3 float 4 Complex
III. Boolean literals: True or False
IV. Special literals:None ==> In Python is same as "null" , means non existent, not
known, or empty.
V.Literal Collections: Tuples, lists, Sets and Dictionaries..!!
Example:
x=100
print("Numeric literal is: ", x)
y=100.123
print("Numeric Float literal is: ", y)
z=complex(1,2)
print("Numeric Complex literal is: ", z)
MyStr="PYTHON"
print("String literal is: ", MyStr)
a=True
print("Boolean literal is: ", a)
b=[1,2,3,4]
print("List literal is: ", b)
c=(1,2,3,4)
print("Tuple literal is: ", c)
d={1,2,2,2,3,4}
print("Set literal is: ", d)
e={1:"ONE",2:"TWO"}
print("Dict literal is: ", e)
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously
Example:
a=b=c=5
print(a)
print(b)
print(c)
Example:
a,b,c = 5,6,"PYTHON"
print(a)
print(b)
print(c)
Syntax:
type(object)
Syntax:
type(name, bases, dict)
__name__: Class name.
__bases__ : A possibly empty tuple containing the base classes
__dict__ : Dictionary containing the class's namespace.
Example:
print(type(42))
print(type("PYTHON"))
print(type(print))
fomat() function:
It returns a formatted representation of the given value controlled by the format
specifier.
Syntax:
format(value[, format_spec])
Example:
print(format(123, "d"))
print(format(123.4567898, "f"))
print(format(8/9,".3f"))
Example:
print(format(123, "<40"))
print(format(123, ">40"))
print(format("Hello", "^40"))
Python Numbers
Number data types store numeric values. Numeric objects are mutable, which means
when an object is created its value can be changed.
3 Floating-Point Numbers
Floating-point numbers are based on scientific notation, where numbers are written
as a mantissa and an exponent.
Example:
a=.0625
print(type(a))
b=0.0625
print(type(b))
4 Complex Numbers
Besides plain integers, long integers and floating point numbers, Python also
provides for imaginary and complex numbers. These use the European convention of
ending with J or j. j reprsents. j for the square root of -1.
Example:
x=complex(1,2)
type(x)
Example:
x=complex(1,2)
print x
Example:
y=complex(3,4)
print y
x=10
y=20
z=x+y is an Expression
Example:
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
Example:
a = 35.0
b = 12.50
c=a*b
print(c)
del Statement:
You can also delete the reference to a number object by using the del statement.
Syntax
del var1[,var2[,var3[....,varN]]]]
Syntax:
oct(number)
Example:
a = 0o10
print(a)
Example
x = oct(65)
print(x)
Syntax:
hex(number)
Example:
x = hex(19)
print(x)
Example:
x = hex(64)
print(x)
Syntax:
bin(number)
Example:
x = 0b101010
print(x )
Example
x = bin(65)
print(x)
Swap variables
In Python swap values in a single line and this applies to all objects in python.
Syntax
var1, var2 = var2, var1
Example :
x = 10
y = 20
print(x)
print(y)
x, y = y, x
print(x)
print(y)
Order of Operations
When an expression contains more than one operator, the order of evaluation
depends on the order of operations. For mathematical operators, Python follows
mathematical convention. The acronym PEMDAS is a useful way.
PEMDAS
Parentheses Exponentiation Multiplication Division Addition Subtraction
Parentheses
2 * (3-1) ==> 4
(1+1)**(5-2) ==> 8
Exponentiation
1 + 2**3 ==> 9, not 27,
2 * 3**2 ==> 18, not 36.
Multiplication and Division have higher precedence than Addition and Subtraction.
2*3-1 ==> 5, not 4,
6+4/2 ==> 8, not 5.
Python defines type conversion functions to directly convert one data type to
another which is useful in day to day and competitive programming. type name is
used for type conversion.
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
list(s) Converts s to a list.
tuple(s) Converts s to a tuple.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value)
tuples.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
complex(real) Creates a complex number.
int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base
in which string is if data type is string.
Example:
print(int('2014'))
print(int("1001",2))
print(int(3.141592))
list() : This function is used to convert any data type to a list type.
Example:
print(list('Mary') )
print(list((1,2,3,4)))
Example:
s='PYTHON'
print(list(s))
Example:
s='PYTHON'
print(tuple(s))
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
Example:
tup = (('a', 1) ,('b', 2), ('c', 3))
print(dict(tup))
Example:
print("%s having %s Years Experience in IT." %("KSRAJU","15+"))
print("%s having %d Years Experience in IT." %("KSRAJU",15))
Example:
name = "RaaJ"
Example:
name = "RaaJ"
age = 23
Mathematical Functions:
Python includes following functions that perform mathematical calculations.
Syntax
abs( x )
Example:
print(abs(-45))
print(abs(100.12))
ceil() Method:
The method ceil() returns ceiling value of x - the smallest integer not less than x.
Syntax
math.ceil( x )
EXAMPLE:
import math
print(math.ceil(-45.17))
print (math.ceil(100.12))
print (math.ceil(100.72))
Syntax
math.floor( x )
Example:
import math
print(math.floor(-45.17))
print(math.floor(100.12))
print(math.floor(100.72))
Syntax:
math.pow(x,y)
Example:
import math
print(math.pow(100, 2))
print(math.pow(2, 4))
print(math.pow(3, 0))
Syntax
round( x [, n] )
Example:
print(round(80.23456, 2))
print(round(100.5623, 3))
sqrt() Method
The method sqrt() returns the square root of x for x > 0.
Syntax
math.sqrt( x )
Example:
import math
print(math.sqrt(100))
print(math.sqrt(7))
Syntax
random ( )
Example:
import random
print(random.random())
print(random.random())
Mathematical Constants
The module also defines two mathematical constants
Constants Description
pi The mathematical constant pi.
e The mathematical constant e.
PYTHON OPERATORS
An operator is a character that represents an action. Python Supports different types
of Operators:
Types of Operators
Python Scripting language supports the following types of operators.
1 Arithmetical Operators
2 Comparison (Relational) Operators
3 Assignment Operators
4 Logical Operators
5 Membership Operators
6 Identity Operators
7 Bitwise Operators
Example:
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Example:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
z=x+y
print("Sum is: ",z)
z=x-y
print("Diff is: ",z)
z=x*y
print("Product is: ",z)
z=x/y
print("Div is: ",z)
z=x%y
print("Mod is: ",z)
z=x**y
print("Expo is: ",z)
z=x//y
print("Fdiv is: ",z)
Operator Description
== If the values of two operands are equal, then the condition becomes true.
!= If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then
condition becomes true.
< If the value of left operand is less than the value of right operand, then
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right
operand, then condition becomes true.
Example:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
z=(x==y)
print("Equal is: ",z)
z=(x!=y)
print("Not Equal is: ",z)
z=x>y
print("Greater is: ",z)
z=x<y
print("Lesser is: ",z)
z=x>=y
print("Greater or Equalto is: ",z)
z=x<=y
print("Less or Equalto is: ",z)
Example:
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Example:
a=int(input("Enter Any Number: "))
b=int(input("Enter Any Number: "))
c=0
c=a+b
print("The Result is: ",c)
c+=a#c=c+a
print("The Result is: ",c)
c*=a#c=c*a
print("The Result is: ",c)
c/=a#c=c/a
print("The Result is: ",c)
c=2
c%=a#c=c%a
print("The Result is: ",c)
c**=a #c=c^a
print("The Result is: ",c)
c//=a #c=c//a
print("The Result is: ",c)
Operator Description
and Logical AND If both the operands are true then condition becomes
true.
or Logical OR If any of the two operands are non-zero then condition
becomes true.
not Logical NOT Used to reverse the logical state of its operand.
Example:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
NOTE: In a dictionary we can only test for presence of key, not the value.
Operator Meaning
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence
Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
Operator Meaning
is True if the operands are identical
is not True if the operands are not identical
Example:
x = "Hello"
y = "hello"
x1=512
y1=215
print('x is y is',x is y)
print('x is not y is',x is not y)
print('x1 is y1',x1 is y1)
print('x1 is not y1',x1 is not y1)
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
ANALYSIS
We declared 2 integers a and b and assigned the values 9 and 65.
The binary form of 9 = 00001001 and 65 = 01000001.
Example:
a=9
b = 65
print(a & b)
A bitwise OR takes two bit patterns of equal length. The result in each position is 0 if
both bits are 0, while otherwise the result is 1
Bitwise OR Operation = a | b
00001001 | 01000001 = 01001001 = 73
Example:
a=9
b = 65
print(a | b)
Non-Pythonic Approach:
2==> 00000010
11111101 ==> One's Complement
+1
11111111 ===> Two's Complement
Example:
One's and Two's complements of 21
21 ==> 00010101
11101010 ==> -
One's Complement:
00010101
+1
00010110 ==> -22
Two's Complement"
00010110
+1
00010111 ==> -23
Example:
a=21
print(~a) #-23
Non-Pythonic Approach
21 ==> 00010101
One's Complement:
11101010 ==>
Two's Complement:
11101010
+1
11101011 ==>
Python bin()
The bin() method converts and returns the binary equivalent string of a given integer.
Syntax
bin(num)
Example:
number = 5
print(bin(number))
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive 'OR' and regular 'OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is,is not Identity operators
in,not in Membership operators
not or and Logical operators
Example:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print( "Value of ((a + b) * c) / d is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
Example:
print("First Line")
print("Second Line")
print("Third Line")
5 == equal
6 != not equal
Python IF Statement
It executes a set of statements conditionally, based on the value of a logical
expression.
Syntax:
if expression :
statement_1
statement_2
....
Example:
num = 3
if num > 0:
print(num, "It is a Positive Number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "It is a Positive Number.")
print("This is also always printed.")
Example:
num=input("Enter any Number: ")
if int(num) > 0:
print(num, "It is a Positive number.")
Example:
x=int(input("Enter Any Number: "))
if x>0:
print("Value is +VE");
print("It is always get Executed");
y=int(input("Enter Any Number: "))
if y<0:
print("Value is -VE");
print("It is always get Executed");
Example:(Try in 2.x)
num=input("Enter Any Data: ")
print("Type of the Data is: ")
print(type(num))
2 if .. else Statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
Syntax
if expression:
Statement(s)_1
Statement(s)_2
else:
Statement(s)_3
Statement(s)_4
Example:
num=input("Enter any Number: ")
if int(num) > 0:
print(num, "It is a Positive number.")
else:
print(num, "It is a Negative number.")
Example:
num=input("Enter any Number: ")
print(type(num))
if int(num) > 0:
print(num, "It is a Positive number.")
else:
print(num, "It is a Negative number.")
Example:
num = 3
if num > 0:
print(num, "It is a Positive Number.")
print("This is always Printed.")
else:
print(num, "It is a Negative Number.")
rint("This is also Printed.")
Example:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("is Even")
else:
print("is Odd")
Python if...elif...else
The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Syntax
if Expression1:
statement(s)_1
statement(s)_2
elif Expression2:
statement(s)_3
statement(s)_4
elif Expression3:
statement(s)_5
statement(s)_6
else:
statement(s)_7
statement(s)_8
NOTE:
Core Python does not provide switch or case statements as in other languages.
Example:
num=input("Enter any Number: ")
print(type(num))
if int(num) > 0:
print(num, "It is a Positive number.")
elif int(num)<0:
print(num, "It is a Negative number.")
else:
print(num, "It is a ZERO.")
Example:
x=int(input("Enter Any Number: "))
y=int(input("Enter Any Number: "))
if x>0 and y>0:
print("X and Y are Positives: ")
elif x==0 and y==0:
print("Values are Zero")
else:
print("Sorry Unable to Calculate")
print("Thank U")
Example:
grade=int(input("Enter Your Marks: "))
if grade >= 90:
print("Your Grade is A+")
elif grade >=80:
print("Your Grade is A")
elif grade >=70:
print("Your Grade is B+")
elif grade >=60:
print("Your Grade is B")
elif grade >=50:
print("You are Pass")
else:
print("Sorry You Failed")
Syntax:
if expression1 :
if expression2 :
Statement_3
Statement_4
....
else :
Statement_5
Statement_6
....
else :
Statement_7
Statement_8
Example:
num = int(input("Enter a number: "))
if num >= 0:
if (num == 0):
print("ZEROZERO")
else:
print("Positive number")
else:
print("Negative number")
Example:
grade=int(input("Enter Your Marks: "))
if grade >= 90:
print("Your Grade is A+")
else:
if grade >=80:
print("Your Grade is A")
else:
if grade >=70:
print("Your Grade is B+")
else:
if grade >=60:
print("Your Grade is B")
else:
if grade >=50:
print("You are Pass")
else:
print("Sorry You Failed")
Example:
year =int(input("Enter Any Year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("is a leap year")
else:
print("is not a leap year")
else:
print("is a leap year")
else:
print("is not a leap year")
Define a negative if
If a condition is true the not operator is used to reverse the logical state, then logical
not operator will make it false.
Example:
x = int(input("Enter Any Number: "))
print(x)
if not x == 50:
print('the value of x different from 50')
else:
print('the value of x is equal to 50')
WHAT IS A LOOP?
A loop is a sequence of instructions that is continually repeated until a certain
condition is reached.
Why Loop?
In a loop structure, the loop asks a question. If the answer requires an action, it is
executed. The same question is asked again and again until no further action is
required. Each time the question is asked is called an iteration.
2 Numeric Ranges
This kind of for loop is a simplification of the previous kind. It's a counting or
enumerating loop. Starting with a start value and counting up to an end value, like for
i = 1 to 100
Syntax
for variable_name in sequence :
Action_1
Action_2
Example:
course_list = ["Big Data", "Hadoop", "Spark", "Scala"]
for list in course_list:
print(list)
Example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
Example:
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print(x)
Example:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
Example:
for num in [10,20,30,40,50]:
if num >=40:
print("Greater Than equal 40 is: ",num)
else:
print("Lesser Than 40 is: ",num)
Example:
dataset = ['BigData', 'python', 'Deep Learning']
for data in dataset:
print(data.upper())
Range Function
It generates lists containing arithmetic progression. It returns a list of consecutive
integers. The function has one, two or three parameters where last two parameters
are optional. It is widely used in for loops.
Syntax:
range(a)
range(a,b)
range(a,b,c)
Syntax
for <variable> in range(<number>):
Example:
range(5)
Example:
for a in range(4):
print(a)
Example:
MyData=int(input("Enter Any Number in Range: "))
for data in range(MyData):
print(data)
Example:
range(5,10)
Example:
for a in range(2,7):
print(a)
Example:
snumber=int(input("Enter Any Start Number: "))
enumber=int(input("Enter Any End Number: "))
for data in range(snumber,enumber):
print(data)
Syntax
for "variable" in range("start_number", "end_number",increment):
Example:
range(0,10,2)
Example:
for a in range(2,19,5):
print(a)
Example:
snumber=int(input("Enter Any Start Number: "))
enumber=int(input("Enter Any End Number: "))
incre=int(input("Enter Any increment Number: "))
for data in range(snumber,enumber,incre):
print(data)
Syntax-2:
for <variable> in <sequence>:
<statements>
<statements>
else:
<statements>
<statements>
Example:
digits = [0, 1, 5, 7]
for i in digits:
print(i)
else:
print("No items left.")
Example:
for i in range(5):
print(i)
else:
print('Iterated over everything :)')
Break
To break out from a loop, you can use the keyword "break".
or
A break statement inside a loop terminates the loop immediately.
Syntax:
break
Syntax
for variable_name in sequence :
statement_1
statement_2
......
if expression:
break
Example:
digi = [0, 1, 5, 7]
for data in digi:
if data==4:
break
print(data)
else:
print("Loop Success")
Example:
for i in range(5):
if i==2:
break
print(i)
else:
print('Iterated over everything :)')
NOTE:
if we stop the loop, say with a break statement, then the else suite will not be
executed
Example:
for x in "PYTHON":
if(x=='O'):
break
print(x)
else:
print("Loop Completed")
Continue
The continue statement is used to tell Python to skip the rest of the statements in the
current loop block and to continue to the next iteration of the loop.
or
A continue statement jumps to the next iteration of the loop, skipping any code in
between.
Syntax:
continue;
Syntax
for variable_name in sequence :
statement_1
statement_2
......
if expression:
continue;
Example:
for i in range(1,10):
if i == 3:
continue
print(i)
Example:
digi=[1,2,3,4,5]
for data in digi:
if data==4:
continue
print(data)
else:
print("Loop Success")
Syntax:
while <expression>:
Body
Syntax
while (expression) :
statement_1
statement_2
Example:
x=1
while x<=5:
print(x)
x=x+1
print("loop Finished")
Example:
x=int(input("Enter Any Number less than 10: "))
while(x<=10):
print(x)
x+=1
print("Loop OK")
NOTE: Any infinite loop hit Ctrl+C to Exit from infinite loop..!!
Syntax:
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
Example:
x=1
while x<=5:
print(x)
x=x+1
else:
print("loop Finished")
Example:
a=10
while a>0:
print("Value of a is",a)
a=a-2
else:
print("Loop is Completed")
Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something]
Example:
for a in range(1,3):
for b in range(1,3):
print(a,b)
Example:
for x in range(1, 4):
for y in range(1, 4):
print('%d * %d = %d' % (x, y, x*y))
Example:
nlist=[1,2,3,4]
alist=['a','b','c']
for number in nlist:
print(number,end=",")
for letter in alist:
print(letter,end=";")
Example:
for row in range(6):
for col in range(6):
if col==0 or col==5 or(row==col and col>0 and col<5):
print("*",end="")
else:
print(end=" ")
print()
Syntax
pass
Example:
for letter in 'Python':
if letter == 'h':
pass
print( 'This is pass block')
print( 'Current Letter :', letter)
Example:
x=1
while(x<=3):
if(x==1):
print("1. PYTHON is SCRIPTING");
elif(x==2):
pass
else:
print("3. It is Fun to learn");
x+=1
WHAT IS DATA?
Data is a set of values of qualitative or quantitative variables.
Qualitative data is descriptive information (it describes something)
Quantitative data, is numerical information (numbers).
DATA CAPACITY:
1 1 Bit = Binary Digit
2 8 Bits = 1 Byte
3 1024 bytes=1KB
4 1024 KB =1 MB
5 1024 MB=1 GB
6 1024 GB=1 TB (TB =Terabyte)
7 1024 TB=1 PB (PB =Petabyte)
8 1024 PB=1 Exabyte (EB)
9 1024 EB=1 Zettabyte (ZB)
10 1024 ZB=1 Yottabyte (YB)
11 1024 YB=1 Brontobyte(BB)
12 1024 BB= 1 Geopbyte(GB)
What is Information?
If we arrange some data in an appropriate sequence, then it forms a Structure and
gives us a meaning. We found two things in Information: One is Data and the other is
Structure.
Define Algorithm?
A set of rules or steps used to solve a problem
SEQUENCE IN PYTHON
A sequence is a succession of values bound together by a container that reflects their
type. There are six sequence types in PYTHON:
1 Strings
2 Unicode Strings
3 Lists
4 Tuples
5 buffer renamed as memoryview(Python-3.0)
6 xrange (renamed as range())Python-3.0)
Example:
first="First"
second="Second"
fullstr=first+" "+second
print(fullstr)
Example:
print('Spam'*3)
Here two indices are used separated by a colon (:). A slice 3:7 means indices
characters of 3rd, 4th, 5th and 6th positions. The second integer index i.e. 7 is not
included. You can use negative indices for slicing.
string1 ="PYTHON"
Character P Y T H O N
Index (from left) 0 1 2 3 4 5
Index (from right) -6 -5 -4 -3 -2 -1
Example:
str1="Naresh i Technologies"
print(str1[0])
print(str1[-1])
print(str1[1:4])
print(str1[-4])
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string.
str1="Technologies"
print(str1)
print(str1[:6]+ ' Nacre')
print(str1[:]+ ' Nacre Services')
print(str1[4:]+ ' Nacre Services')
Example:
str1="Naresh i Technologies"
print(str1)
str1[0]='A'
print(str1)
We cannot delete or remove characters from a string. But deleting the string entirely
is possible using the keyword del.
Example
del str1
Example:
str1="Technologies"
print(str1)
print(str1[0])
del str1
str1="technologies"
print(str1)
print(str1[0])
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, Storing ASCII characters
in an 8-bit byte. while Unicode strings are stored as 16-bit Unicode.
NOTE:
8-bit, 16-bit, 32-bit and 64-bit all refer to a processor's word size. It also refers to the
size of the memory address space.
Example:
str1=r"Normal String"
print("PYTHON Normal String is: ",str1)
str2=u"Unicode String"
print("PYTHON Unicode String is: ",str2)
NOTE:
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Define Indentation?
When referring to text, indent or indentation is the increase or decrease of space
between the left and right margin of a paragraph. But in Python, it is required for
indicating what block of code a statement belongs to.
Example:
if True:
print "True"
else:
print "False"
NOTE: "..." Indicate input to Python. Everything else is output from Python
PYTHON-String Library:
Built-in String Methods
Python includes the following built-in methods to manipulate strings
capitalize() Method
It returns a copy of the string with only its first character capitalized.
Syntax
str.capitalize()
Example:
str1="naresh i Technologies"
print(str1.capitalize())
str2="HELLO HOW ARE U"
print(str2.capitalize())
Syntax
str.isdigit()
Example:
str1="PYTHON"
print(str1.isdigit())
str2="12345"
print(str2.isdigit())
islower() Method
The method islower() checks whether all the case-based characters (letters) of the
string are lowercase.
Syntax
str.islower()
Example:
str1="PYTHON"
print(str1.islower())
str2="python"
print(str2.islower())
str3="pYthOn"
print(str3.islower())
len() Method
The method len() returns the length of the string.
Syntax
len( str )
Example:
str1="PYTHON"
print(len(str1))
str2="DataScience is ROCKING"
print(len(str2))
join() Method
It returns a string in which the string elements of sequence have been joined by str
separator.
Syntax
str.join(sequence)
Example:
#Characters Masking
s = "****";
seq = ("98", "66", "11");
print(s.join( seq ))
Syntax
max(str)
Example:
str1="abcd"
print(max(str1))
str2="abcddcba"
print(max(str2))
str3="Maximum"
print(max(str3))
str4="12344321"
print(max(str4))
Syntax:
str.replace(old, new[, max])
Example:
str = "Hello How are You"
print(str.replace("You", "U"))
print(str.replace("are", "was", 3))
title() Method
It returns a copy of the string in which first characters of all the words are capitalized.
Syntax:
str.title();
Example:
str = "this is powerful python scripting !";
print(str.title())
isdecimal() Method
It checks whether the string consists of only decimal characters. This method are
present only on unicode objects.
Syntax:
str.isdecimal()
Example:
str = u"this2009";
print(str.isdecimal())
str = u"23443434";
print(str.isdecimal())
zfill() Method
The method zfill() pads string on the left with zeros to fill width.
Syntax:
str.zfill(width)
Example:
str="Python Rocks"
print(str.zfill(20))
Syntax
str.isalnum()
Example:
str = "this2009";
print(str.isalnum())
str = "this is string example....wow!!!";
print(str.isalnum())
PYTHON LISTS:
A list is a container which holds comma-separated values (items or elements)
between square brackets[ ] where items or elements need not all have the same
type. It can have any number of items and they may be of different types (integer,
float, string etc.).
Types of lists :
Empty List: A list without any element is called an empty list
Example:
my_list = []
print(my_list)
Number List:
1 Integers List:
A list with only numbers is called an integer list
Example:
My_List1=[1,2,3,4,5]
print(type(My_List1))
print(My_List1)
Float List:
A list with only decimal numbers is called float list
Example:
My_List1=[1.1,2.88,3.33,4.1,5.0]
print(type(My_List1))
print(My_List1)
String List:A list with only strings and Chars is called a string list
Example:
names = ["Sara", "David", "Raju", "Sandy"]
print(names)
Len Example:(Length)
MyDataSet=[1,2,4,4]
Num_Ele=len(MyDataSet)
print("Number of Elements are: ",Num_Ele)
Example2: Concatenation
MyDataSet1=[1,2,4,4]
MyDataSet2=['a','b','c','d']
All_DataSets=MyDataSet1+MyDataSet2
print(All_DataSets)
Example: Repetition
MyDataSet1=[1,2]
Rep_DataSets=MyDataSet1*4
print(Rep_DataSets)
Example : Membership
MyDataSet1=[1,2,3]
Data_Result=1 in MyDataSet1
print(Data_Result)
Example:
Use * operator to repeat a list.
number = [1,2,3]
print(number[0]*4)
print(number*4)
#Example
US_Gdp_Data=['a','b','c','d','e']
print(US_Gdp_Data*2)
print(US_Gdp_Data[0]*2)
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a
list having 5 elements will have index from 0 to 4. The index must be an integer.
Nested list are accessed using nested indexing.
NOTE:
We can't use float or other types, this will result into TypeError.
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
Item Big Data Hadoop Spark IoT
Index (from left) 0 1 2 3
Index (from right) -4 -3 -2 -1
my_list = ['P','Y','T','H','O','N']
print(my_list[0]) # Indexing
print(my_list[4]) # Indexing
n_list = ["Happy", [2,0,1,5]]# Nested List
print(n_list[0][1]) # Nested indexing
print(n_list[1][3]) # Nested indexing
print(n_list[4.0]) # Error! Only integer can be used for indexing
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
Example:
my_list = ['p','y','t','h','o','n']
print(my_list[-1])
print(my_list[-5])
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
py_list[0]
print(py_list[0],py_list[3]) # Print First and Last Elements
py_list[-1] # Return Last Element
print(py_list[4]) # Creates Error as the indices is out of range
List Slices
Lists can be sliced like strings and other sequences. We can access a range of items in
a list by using the slicing operator (colon).
Syntax :
sliced_list = List_Name[StartIndex:EndIndex]
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list[0:2])
print(py_list[1:2])
print(py_list[1:-2])
print(py_list[:3])
print(py_list[:])
Example:
my_list = ['P','Y','T','H','O','N','S','C','R']
print(my_list[2:5])
print(my_list[:-5])
print(my_list[5:])
print(my_list[:])
Syntax:
list.append(item)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.append("PYTHON")
print(py_list)
Example:
alist = ['a', 'b', 'c']
alist.append(['d', 'e','f'])
print(alist)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list[0])
py_list[0]="DataScinece"
print(py_list)
print(py_list[0])
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list[2]="PYTHON"
print(py_list)
Syntax:
list.extend(iterable)
Example:
alist1 = ['a', 'b', 'c']
alist1.extend(['d', 'e','f'])
print(alist1)
Syntax:
list.insert(index, element)
Parameters:
index - position where element needs to be inserted
element - this is the element to be inserted in the list
Example:
MyData = ['Big', 'Data', 'Hadoop', 'Spark']
MyData.insert(2, 'TERADATA')
print('Updated List: ', MyData)
del(): Stands for "delete." We call del to remove the element in a list.
Syntax:
del list[index]:
Syntax:
list.remove(item)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.remove("IoT")
print(py_list)
Syntax:
list.clear()
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.clear()
print(py_list) #Empty List Displayed
index(): Return the index in the list of the first item whose value is x. OR Search the
Lists and find Elements
Syntax:
list.index(item)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
print(py_list.index("Spark"))
Example:
listy = list("HELLO WORLD")
print(listy)
index = listy.index("L")
print(index)
index = listy.index("L", 4)
print(index)
index = listy.index("O", 3, 5)
print(index)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT", "Hadoop"]
py_list.count("Hadoop")
Syntax:
list.sort(reverse="True/False") By Default False
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.reverse()
print(py_list)
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
print(py_list.copy())
Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.append("DataScinece")
py_list.append("PYTHON")
print(py_list)
py_list.pop()
py_list.pop()
print(py_list)
Example:
from collections import deque
py_list = deque(["Big Data", "Hadoop", "Spark", "IoT"])
py_list.append("DataScinece")
print(py_list)
py_list.append("PYTHON")
print(py_list)
py_list.popleft()
print(py_list)
py_list.popleft()
print(py_list)
Python enumerate()
The enumerate() method adds counter to an iterable and returns it (the enumerate
object).
Syntax
enumerate(iterable, start=0)
enumerate() Parameters
The enumerate() method takes two parameters:
Example:
bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for count, item in enumerate(bd):
print(count, item)
Example:
bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for count, item in enumerate(bd, 100):
print(count, item)
Example:
import matplotlib.pyplot as plt
x = [2,3,4,5,7,9,13,15,17]
plt.plot(x)
plt.ylabel('Sunlight')
plt.xlabel('Time')
plt.show()
Example2:
import matplotlib.pyplot as plt
x = [2,3,4,5,7,9,13,15,17]
plt.plot(x, 'ro-')
plt.ylabel('Sunlight')
plt.xlabel('Time')
plt.show()
We create a red graph with dots, where the r in ‘ro-‘ indicates red. Changing this to
‘bo-‘ would create a blue dotted line. If you only want to display the dots, use ‘ro’ or
‘bo’ instead.
PYTHON TUPLES
A tuple in Python is a collection that cannot be modified. A tuple is defined using
parenthesis.
OR
A tuple is a container which holds a series of comma-separated values (items or
elements) between parentheses such as an (x, y) co-ordinate. Tuples are like lists,
except they are immutable.
Tuple packing.
Creating tuple without parentheses, also called tuple packing.
my_tuple = 3, 4.6, "Data Science"
print(my_tuple)
NOTE:
if a value is more, it dislays "Value Error",
if a variable is more, it displays "not enough values"
Example:
my_tuple = ("Data Science")
print(type(my_tuple))
Example:
my_tuple = ("Data Science",)
print(type(my_tuple))
Example:
my_tuple = "Data Science",
print(type(my_tuple))
Example:
tuplez = ("P", "Y", "T", "H", "O", "N", "S", "C", "R", "I","P","T")
print(tuplez)
print("R" in tuplez)
print(5 in tuplez)
Example:
for name in ('KSRaju','Dinesh',"NareshIT"):
print("Hai",name)
Slice a tuple: We can access a range of items in a tuple by using the slicing operator -
colon ":"
tuplez = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
x = tuplez[3:5]
print(x)
y = tuplez[:6]
print(y)
z= tuplez[5:]
print(z)
a = tuplez[:]
print(a)
b = tuplez[-8:-4]
print(b)
#+ Operator Concatenation
tuplez1 = (3, 6, 9, 12, 15)
tuplez2 = ("P", "Y", "T", "H", "O", "N")
tuplez3 = (True, False)
tuplez = tuplez1 + tuplez2 + tuplez3
print(tuplez)
#Repetation * Operator
tuplez = 5,
print(tuplez * 6)
tuplez = (5, 10, 15) * 4
print(tuplez)
Method Description
count(x) Return the number of items that is equal to x
index(x) Return index of first item that is equal to x
Method-II
tuplez = (4, 6, 2, 8, 3, 1)
print(tuplez)
listx = list(tuplez)
listx.append(30)
tuplez = tuple(listx)
print(tuplez)
Deleting a Tuple:
We cannot change the elements in a tuple. That also means we cannot delete or
remove items from a tuple. But deleting a tuple entirely is possible using the keyword
del.
Example:
my_tuple=('P','Y','T','H','O','N','S','C','R')
print(my_tuple)
del my_tuple
print(my_tuple)
Python enumerate()
The enumerate() method adds counter to an iterable and returns it (the enumerate
object).
Syntax
enumerate(iterable, start=0)
Example:
bd = ['Big Data', 'Hadoop', 'Spark']
enumerateData = enumerate(bd)
print(type(enumerateData))
print(list(enumerateData))
enumerateData = enumerate(bd, 10)
print(list(enumerateData))
Example:
bd = ['Big Data', 'Hadoop', 'Spark']
for item in enumerate(bd):
print(item)
Example:
for count, item in enumerate(bd, 100):
print(count, item)
all() Function:
It returns True when all elements in the given iterable are true. If not, it returns False.
Syntax:
all(iterable)
all() Parameters
iterable - any iterable (list, tuple, dictionary, etc.) which contains the elements
s = (0, False)
print(all(s))
s = [0, False, 5]
print(all(s))
s = []
print(all(s))
Python any()
It Returns True if any element of an iterable is true. If not, this method returns False.
Syntax:
any(iterable)
Example:
s = (1, 3, 4, 0)
print(any(s))
s = (0, False)
print(any(s))
s = [0, False, 5]
print(any(s))
s = []
print(any(s))
Python len()
The len() function returns the number of items (length) of an object.
Syntax
len(s)
Example:
testList = []
print(len(testList))
Example:
#The size of a tuple
tuplez = tuple("PYTHON")
print(tuplez)
print(len(tuplez))
Example:
testRange = range(1, 10)
print(len(testRange))
Python sorted()
The sorted() method sorts the elements of a given iterable in a specific order -
Ascending or Descending.
Syntax
sorted(iterable[, reverse])
Parameters:
iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any
iterator
reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order)
Example
pyString = 'Python'
print(sorted(pyString))
Example
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))
Example
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple,reverse=True))
Python sum()
The sum() function adds the items of an iterable and returns the sum.
Syntax:
sum(iterable)
sum() Parameters
iterable - iterable (list, tuple, dict etc) whose item's sum is to be found. Normally,
items of the iterable should be numbers.
Example:
numbers = [2.5, 3, 4, -5]
numbers = sum(numbers)
print("Sum of Numbers is: " ,numbers)
Syntax:
tuple(iterable)
Parameter:
iterable (optional) an iterable (list, range etc.) or an iterator object
#tuple to List
MyTuple=(1,2,3,4)
print(type(MyTuple))
print(MyTuple)
MyList=list(MyTuple)
print(type(MyList))
print(MyList)
***********************************************************************
*****************Dotted Charts:
You can use Matplotlib to create a line chart with Python. Matplotlib is a plotting
library for the Python programming language and its numerical mathematics
extension numpy. This takes only a few lines:
Example:
import matplotlib.pyplot as plt
x = (2,3,4,5,7,9,13,15,17)
plt.plot(x,'ro')
plt.ylabel('Light')
plt.xlabel('Time')
plt.show()
Example:
import matplotlib.pyplot as plt
x = (2,3,4,5,7,9,13,15,17)
plt.plot(x,'bo')
plt.ylabel('Light')
plt.xlabel('Time')
plt.show()
Example:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
PYTHON SETS
SET is an unordered collection of unique elements
or
A set object is an unordered collection of distinct hashable objects. It is commonly
used in membership testing, removing duplicates from a sequence, and computing
mathematical operations such as intersection, union, difference, and symmetric
difference.
Example:
We should not use empty curly brackets, treat as dictionary..!!
b={}
type(b)
Example:
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
Syntax:
set.add(elem)
Example:
a={1,2,3,4,5,6,1,2,3}
print(set(a))
a.add(11)
a.add(12)
print(a)
Example:
vowels = {'a', 'e', 'i', 'u'}
vowels.add('o')
print('Vowels are:', vowels)
vowels.add('a')
print('Vowels are:', vowels)
Example:
data_set = set()
data_set.add("Hadoop")
print(data_set)
Syntax
A.update(B)
NOTE:
A and B are two sets. The elements of set B are added to the set A.
Example:
data_set = set()
data_set.update(["Data Science", "Big Data"])
print(data_set)
Syntax:
set.pop()
Example:
A ={'a', 'b', 'c', 'd'}
print('Return Value is', A.pop())
print('A = ', A)
Example:
num_set = set([0, 1, 2, 3, 4, 5])
num_set.pop()
print(num_set)
num_set.pop()
print(num_set)
Syntax:
set.remove(element)
Example:
num_set = set([0, 1, 2, 3, 4, 5])
num_set.remove(0)
print(num_set)
Syntax:
s.discard(x)
Example:
num_set = set([0, 1, 2, 3, 4, 5])
num_set.discard(3)
print(num_set)
Example:
numbers = {2, 3, 4, 5}
numbers.discard(3)
print('numbers = ', numbers)
numbers.discard(10)
print('numbers = ', numbers)
Python Set clear()
The clear() method removes all elements from the set.
Syntax
set.clear()
Example:
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowels (before clear):', vowels)
vowels.clear()# clearing vowels
print('Vowels (after clear):', vowels)
intersection(s)
Returns the intersection of the instance set and the set s as a new set. In other
words: A set with all the elements which are contained in both sets is returned.
Example:
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
print(x.intersection(y))
print(x & y) #ampersand operator "&":
Union of sets
In set theory, the union (denoted by ∪) of a collection of sets is the set of all distinct
elements in the collection. It is one of the fundamental operations through which
sets can be combined and related to each other.
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A.difference(B))# Equivalent to A-B
print(B.difference(A))# Equivalent to B-A
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A-B)
print(B-A)
Example:
x = set(["Big Data", "Data Science"])
y = set(["Data Science", "Spark"])
z=x&y
print(z)
b=x-z
print(b)
Set symmetric_difference()
It returns a new set which is the symmetric difference of two sets. The symmetric
difference of two sets A and B is the set of elements which are in either of the sets A
or B but not in both. (A-B)UNION(B-A)
Syntax:
A.symmetric_difference(B)
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
C = {}
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
print(A.symmetric_difference(C))
print(B.symmetric_difference(C))
Example:
setx = set(["Big Data", "Data Science"])
sety = set(["Data Science", "Spark"])
setc = setx.symmetric_difference(sety)
print(setc)
setd = setx ^ sety
print(setd)
Set issuperset():
It returns True if a set has every elements of another set (passed as an argument). If
not, it returns False.
Syntax:
A.issuperset(B)
Example:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print(A.issuperset(B))
print(B.issuperset(A))
print(C.issuperset(B))
Example:
setx = set(["Big Data", "Data Science","Spark"])
sety = set(["Data Science", "Spark"])
issuperset = sety <= setx
print(issuperset)
print(sety.issuperset(setx))
Set issubset()
It returns True if all elements of a set are present in another set (passed as an
argument). If not, it returns False. Set A is said to be the subset of set B if all elements
of A are in B .
Syntax:
A.issubset(B)
Example:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print(A.issubset(B))
print(B.issubset(A))
print(C.issubset(B))
Example:
setx = set(["Big Data", "Data Science"])
sety = set(["Data Science", "Spark"])
issubset = setx <= sety
print(issubset)
print(setx.issubset(sety))
isdisjoint()
This method returns True if two sets have a null intersection.
or
The isdisjoint() method returns True if two sets are disjoint sets. False if two sets are
not disjoint sets.
Syntax:
set_a.isdisjoint(set_b)
Example:
A = {1, 2, 3, 4}
B = {5, 6, 7}
C = {4, 5, 6}
print(A.isdisjoint(B))
print(A.isdisjoint(C))
Syntax:
set.copy()
Example:
setx = set(["Big Data", "Data Science"])
setd = setx.copy()
print(setd)
Set union()
The union() method returns a new set with distinct elements from all the sets.
Syntax:
A.union(*other_sets)
Note: * is not part of the syntax. It is used to indicate that the method allows
arbitrary number of arguments.
Example:
A = {1, 2}
B = {2, 3, 4}
C = {5}
Then,
A∪B = B∪A ={1, 2, 3, 4}
A∪C = C∪A ={1, 2, 5}
B∪C = C∪B ={2, 3, 4, 5}
A∪B∪C = {1, 2, 3, 4, 5}
Example:
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C= {1, 2, 3}
print('A U B =', A.union(B))
print('B U C =', B.union(C))
print('A U B U C =', A.union(B, C))
print('A.union() = ', A.union())
len() The len() function returns the number of items (length) of an object.
Syntax:
len(s)
Example:
testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))
testSet = set()# Empty Set
print(testSet, 'length is', len(testSet))
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot
be changed once assigned. While tuples are immutable lists, frozensets are
immutable sets. Frozensets can be created using the function frozenset().
Example:
a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
print(a.union(b))
Example:
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
print(A.isdisjoint(B))
print(A.difference(B))
print(A | B)
Example:
a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
print(a.union(b))
print(a & b)
print(a.intersection(b))
print(a.symmetric_difference(b))
print(a.issubset(b))
print(a.issuperset(b))
Example:
a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
print(a.union(b))
a.add(5)
print(a)
PYTHON DICTIONARIES
A "bag" of values, each with its own label
OR
A dictionary is a sequence of items. Each item is a pair made of a key and a value.
Dictionaries are not sorted. You can access to the list of keys or values independently.
OR
Each object or value accessed by key and keys are unique in the dictionary. As keys
are used for indexing.
Why Dictionary?
1 Dictionaries are Python’s most powerful data collection
2 Dictionaries allow us to do fast database-like operations in Python
3 Dictionaries have different names in different languages
4 Associative Arrays - Perl / PHP
5 Properties or Map or HashMap - Java
6 Property Bag - C# / .Net
Example:
my_dict = {'name':'NareshIT', 'age': 15}
print(my_dict)
my_dict['age'] = 27
print(my_dict)
Pic:List_Dict
Example:
lst = list()
lst.append(21)
lst.append(183)
print(lst)
lst[0] = 23
print(lst)
Key Value
[0] 23
[1] 183
Example:
dic = dict()
dic['exp'] = 14
dic['course'] = 'Python'
print(dic)
dic['exp'] = 15
print(dic)
Dictionary
Key Value
['course'] 'PYTHON'
['Exp'] 14
Syntax:
dictionary.fromkeys(sequence[, value])
fromkeys() Parameters
sequence - sequence of elements which is to be used as keys for the new dictionary
value (Optional) - value which is set to each each element of the dictionary
Example:
keys = {'a', 'e', 'i', 'o', 'u' }
vowels = dict.fromkeys(keys)
print(vowels)
Example:
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'
vowels = dict.fromkeys(keys, value)
print(vowels)
Dictionary get()
It returns the value for the specified key if key is in dictionary.
Syntax:
dict.get(key[, value])
get() Parameters
key - key to be searched in the dictionary
value (optional) - Value to be returned if the key is not found. The default value is
None.
Example:
person = {'name': 'NareshIT', 'Exper': 15}
print('Name: ', person.get('name'))
print('Exper: ', person.get('Exper'))
print('Salary: ', person.get('salary'))
print('Salary: ', person.get('salary', '$100000'))
Dictionary items()
It returns a view object that displays a list of dictionary's (key, value) tuple pairs.
Syntax:
dictionary.items()
Example:
sales = { 'apple': 5, 'orange': 4, 'grapes': 2 }
print(sales.items())
How items() works when a dictionary is modified?
Example:
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
items = sales.items()
print('Original items:', items)
del[sales['apple']]
print('Updated items:', items)
Dictionary update()
It updates the dictionary with the elements from the another dictionary object or
from an iterable of key/value pairs.
Syntax:
dict.update([other])
Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
d.update(d1)
print(d)
Dictionary keys()
It returns a view object that displays a list of all the keys in the dictionary
Syntax:
dict.keys()
Example:
person = {'name': 'NareshIT', 'age': 15, 'salary': '$35000.0'}
print(person.keys())
empty_dict = {}
print(empty_dict.keys())
Example:
person = {'name': 'NareshIT', 'age': 15, }
print('Before dictionary is updated')
keys = person.keys()
print(keys)
person.update({'salary': '$350000'})
print('\nAfter dictionary is updated')
print(keys)
Dictionary values()
The values() method returns a view object that displays a list of all the values in the
dictionary.
Syntax:
dictionary.values()
Example:
books = { 'BigData': 5, 'Hadoop': 6, 'Data Science': 4 }
print(books.values())
Example:
books = { 'BigData': 5, 'Hadoop': 6, 'Data Science': 4 }
print(books.values())
print('Original items:', books)
del[books['BigData']]
print('Updated items:', books)
print(books.values())
Dictionary pop()
It removes and returns an element from a dictionary having the given key.
Syntax
dictionary.pop(key)
pop() Parameters
key - key which is to be searched for removal
Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = books.pop('BigData')
print('The popped element is:', element)
print('The dictionary is:', books)
Example:
books = { 'BigData': 2, 'Hadoop': 3, 'Data Science': 4 }
element = books.pop('Spark')
#Key Error
Dictionary popitem()
It returns and removes an arbitrary element (key, value) pair from the dictionary.
Syntax:
dict.popitem()
Example:
person = {'name': 'NareshIT', 'age': 15, 'salary': '$35000.0'}
result = person.popitem()
print('person = ',person)
print('Return Value = ',result)
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares)
print(49 in squares)
Syntax:
len(s)
Example:
fruits = {"mango": 2, "orange": 6}
print("Length:", len(fruits))
Python sorted()
The sorted() method sorts the elements of a given iterable in a specific order -
Ascending or Descending.
Syntax
sorted(iterable[, reverse])
Example:
pyDict = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print(sorted(pyDict))
pyFSet = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(pyFSet, reverse=True))
Both are implemented in different ways and have different characteristics associated
with them. The points of comparisons are:
1 Return Type
2 Memory
3 Operation Usage
4 Speed
Return Type
range() returns – the list as return type.
xrange() returns – generator xrange() object.
Example:
a = range(1,100)
print ("The return type of range() is : ")
print (type(a))
2 Memory
import sys
print(sys.getsizeof(range(100))) #More Memory
print(sys.getsizeof(xrange(100))) # Less Memory