Sie sind auf Seite 1von 112

Complete CORE PYTHON

Introduction to Script

✓ What is Scripting language


✓ What is a programming language?
✓ Types of Scripts
✓ Difference between Script & Programming Languages
✓ Features of Scripting
✓ Types of programming Language Paradigms

What is Scripting language?


The term SCRIPTING is also used as loosely or weakly typed or light weight programming.
Scripting languages are becoming more popular due to the emergence of web-based
applications.

What is Programming language?


A programming language is a formal language that specifies a set of instructions that can be
used to produce various kinds of output. Programming languages generally consist of
instructions for a compute

Major advantages of scripting languages:


1 Easy to learn and use
2 Minimum programming knowledge or experience required
3 Allow complex tasks to be performed in relatively few steps
4 Allow simple creation and editing in a variety of text editors
5 Allow the addition of dynamic and interactive activities to web pages
6 Editing and running code is fast.

Types of Scripting Languages:


Scripting Languages are Classified into the following two types:
1. Client Side Scripting Languages
2. Server Side Scripting Languages

Client Side Scripting Languages


The script which is running within the browser is called as client side scripting.
Example:
1. Live Script
2. JavaScript
3. Type Script
4. Actionscript

Server Side Scripting Languages


The Script which is running within the web server is called as server side scripting.
Example:
Python ==>SimpleHTTPServer
ASP ==>IIS (Internet Information Services)
JSP ==>Tomcat/Sun Java System Web Server
PHP ==>Apache

Difference between Scripting Languages and Programming Languages


Scripting Languages:
1. Interpreted based (Read Line by Line)
2. Implicit Declaration of data types
Example:
var x=100;
var str='Raju';
var x=100.000;
3. Easily Integrated with other Technologies

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

Types of programming Language Paradigms:


There are two types of Programming Language Paradigms:
1. Imperative Paradigm
2. Declarative Paradigm

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

2. Object-oriented Programming Paradigm


It is based on the concept of "objects", Example: C++, JAVA

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)

2. Logical Programming Paradigm:


It is largely based on formal logic Example: PROLOG (Programming in Logic)

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

Who Uses Python?


1. YouTube
2. Google
3. DropBox
4. RospBerryPI
5. BitTorrent
6. NASA
7. NSA
8. NETFLIX
9. Yahoo
10. Honeywell , HP , Philips and United Space Alliance

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.

Define PSF? (Python Software Foundation)


It (PSF-2001) is an organization devoted to advancing open source technology related to the
Python programming language.
1 PEPs ==> Python Enhancement Proposals
2 PyPI ==> Python Package Index

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

Python in the real world:


Web-SITES
Quora
Youtube
Reddit
Piterest
Yahoo Maps

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 Installation Process in Windows Environment:


1. Goto https://www.python.org/downloads/
2. Download the latest version for Windows ==> Download Python 3.6.1
3. Double click on that exe file
4. Select Install for all users, click on NEXT Button
5. Select Customize python, click on NEXT Button
6. Finally click on Finish button.
C:\Users\admin\AppData\Local\Programs\Python\Python36-32

After successful Installation You will find:


IDLE (Integrated DeveLopment Environment or Integrated Development and Learning
Environment) is an integrated development environment for Python) Right click on theat
IDLE Create short cut icon on the taskbar for easy Accesss..!!

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

Python is considered an interpreted language because Python programs are executed by an


interpreter.
There are two ways to use the interpreter: (Run Modes)
1 Interactive mode
2 Script mode

1 Interactive mode
Python offers a comfortable command line interface with the Python shell, which is also
known as the "Python interactive shell".

>>> (Triple Chevron) the Prompt of the PYTHON..!!


Goto CLI (Command Line Interface) of windows or Linux and execute below

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=":-)")

Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard input.
1. raw_input (2.x)
2. input (from 3.x)

Raw_Input: It is used to read data from the user or from the keyboard:

Syntax
raw_input("Message")

Example: (2.x -Version)


name = raw_input("What is your name? ")
type(name)
print "Received input is : ", name

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)

How to Quit the Python Shell (quit(), exit())


It's easy to end the interactive session: You can either use quit(), exit() or Ctrl-D on UNIX
Ctrl-Z, Enter on Windows(i.e. EOF) to exit.

Script mode or Development mode


You can store code in a file and use the interpreter to execute the contents of the file, which
is called a script. Python scripts have names that end with .py Extension.

Example1:
1. Goto IDLE, Select File and click on New or Ctrl+N (to Open New Window)
2. Enter required python statements or commands

print("Python Scripting"); (Semicolon Optional)


print("It is Interpreter and Compiler based")
print("IOT Data Science");print("IOT Data Science") (Semicolon Mandatory)

3. Save with .py Extension


4. Hit the key F5 or Goto run menu click Run
5. The out put displayed in readonly format on the IDLE
6. Do required modifications in the saved file and re-run..!!

File Extensions are:


Before 3.0 versions
.py ==> Python File (Regular Scripts)
.py3 ==> (rarely used) Python3 script
.pyc==> This is the compiled bytecode. or compiled scripts
.pyd ==> This is basically a windows dll file
.pyo ==> This is optimized pyc file
.pyw==Python script for Windows
.pyz ==> Python script archive (Compressed or Zip formated)

SETTING PATH IN Windows:


1 Right click on My Computer ->Properties ->Advanced System setting ->Environment
Variable ->New
In Variable name write path and in Variable value copy path up to C://Python(i.e., path where
Python is installed). Click Ok ->Ok.

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

In Unix Python can be executed in two Run Modes:


1. Interactive Run Mode
2. Script Run Mode

Execute a Python script (Interactive Run Mode)


$ python
>>> print("Hello World!")
>>> "Spam!!"*5

2. Script Run Mode:


It is popularly known as Development mode. You can store code in a file and use the
interpreter to execute the contents of the file, which is called a script

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

Python supports two types of comments.


1 Single lined comment.
2 Multi lined Comment.

1 Single lined comment.


In Python, we use the hash (#) symbol to start writing a comment. If developer want to only
specify one line comment than use single line comment, then comment must start with #

# This is single line comment. (hash or pound)


#print("Hello")

#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 a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes


These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

"""print("Comm")
print("Comm")
print("Comm")"""

Python Implementation Alternatives


There are at least five implementations of the Python language
1. CPython (Standard, implementation of Python)
2. Jython(Python for Java)
3. IronPython(Python for .NET)
4. Stackless (Python for concurrency)
5. PyPy(Python for speed)

The Zen of Python


1.Beautiful is better than ugly.
2.Explicit is better than implicit.
3.Simple is better than complex.
4.Complex is better than complicated.
5.Flat is better than nested.
6.Sparse is better than dense.
7.Readability counts.
8.Special cases aren't special enough to break the rules.
9.Although practicality beats purity.
10.Errors should never pass silently.
11.Unless explicitly silenced.
12.In the face of ambiguity, refuse the temptation to guess.
13.There should be one -- and preferably only one -- obvious way to do it.
14.Although that way may not be obvious at first unless you're Dutch.
15.Now is better than never.
16.Although never is often better than *right* now.
17.If the implementation is hard to explain, it's a bad idea.
18.If the implementation is easy to explain, it may be a good idea.
19. Namespaces are one honking great idea -- let's do more of those!

What is Data Science?


Data science, also known as data-driven science, is an interdisciplinary field about scientific
methods, processes, and systems to extract knowledge or insights from data in various
forms.

Uses of Python in Data Science


Python's popularity for data science is largely due to the strength of its core libraries
1. NumPy==> It is the fundamental package for scientific computing with Python
2. SciPy ==> It contains modules for optimization, linear algebra, integration, interpolation
etc.!
3. pandas ==> It is providing high-performance, easy-to-use data structures and data analysis
tools
4 matplotlib ==> It is a Python 2D plotting library
5 IPython ==> It is an interactive command-line terminal for Python

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.

Raspberry Pi: (From Python)


1 Raspberry Pi is a fully-functional single-board computer with a Broadcom processor
2 On Raspberry Pi, you can run operating system like Linux, Free BSD, even Windows10

Script mode or Development mode


You can store code in a file and use the interpreter to execute the contents of the
file, which is called a script. Python scripts have names that end with .py Extension.
Example1:
1. Goto IDLE, Select File and click on New or Ctrl+N (to Open New Window)
2. Enter required python statements or commands

print("Python Scripting"); (Semicolon Optional)


print("It is Interpreter and Compiler based")
print("IOT Data Science");print("IOT Data Science") (Semicolon Mandatory)

3. Save with .py Extension


4. Hit the key F5 or Goto run menu click Run
5. The out put displayed in readonly format on the IDLE
6. Do required modifications in the saved file and re-run..!!

File Extensions are:


Before 3.0 versions
.py ==> Python File (Regular Scripts)
.py3 ==> (rarely used) Python3 script
.pyc==> This is the compiled bytecode. or compiled scripts (Bytecode)
.pyd ==> This is basically a windows dll file
.pyo ==> This is optimized pyc file

3.0 onwards
.pyw==Python script for Windows
.pyz ==> Python script archive (Compressed or Zip formated)

SETTING PATH IN Windows:


1 Right click on My Computer ->Properties ->Advanced System setting ->Environment
Variable ->New
In Variable name write path and in Variable value copy path up to C://Python(i.e., path
where Python is installed). Click Ok ->Ok.

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

In Unix Python can be executed in two Run Modes:


1. Interactive Run Mode
2. Script Run Mode

Execute a Python script (Interactive Run Mode)


$ python
>>> print("Hello World!")
>>> "Spam!!"*5

2. Script Run Mode:


It is popularly known as Development mode. You can store code in a file and use the
interpreter to execute the contents of the file, which is called a script

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.

What is PyCharm: Best IDE for RealTime PYTHON Projects:


PyCharm is an Integrated Development Environment (IDE) used in computer
programming, specifically for the Python language. It provides code analysis, a
graphical debugger, an integrated unit tester, integration with version control
systems and supports web development with Django.

PyCharm comes in two editions, community edition and professional edition.


Community edition is free for everyone and professional edition costs $199 for 1st
year.

PyCharm IDE (https://www.jetbrains.com/pycharm/download/#section=windows)


1 It is developed by the Czech company JetBrains.
2 Python must be installed before Pycharm installation
3 PyCharm supports Python from version 2.4 up to the all latest versions
4 Install any Edition Community(OpenSource) and Professional(Commercial)
5 PyCharm is cross-platform and works on Windows, macOS, and Linux.

PyCharm IDE Features List:


1 Intelligent Coding Assistance
i Intelligent Code Editor
ii Smart Code Navigation

2 Built-in Developer Tools


i Debugging, Testing and Profiling
ii VCS, Deployment and Remote Development
3 Web Development
i Python Web frameworks
ii JavaScript & HTML

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)

Top 5 Python IDEs For Data Science:


The best Python IDEs for data science, that make data analysis and machine learning
easier!
1. Spyder
2. Jupyter Notebook
3. PyCharm
4. Rodeo
5. Atom

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)

As per Realtime Standard follow the steps:


1. https://www.anaconda.com/download/
3. Click on Python 3.6 version 64-Bit Installer
4. After successful Installation of Anaconda Framework
5. Go to command prompt type spyder or jupyter notebook (Internet Connection
Required)
6. SPYDER(Scientific PYthon Development EnviRonment)
7. JUPYteR (formerly==>iPython, JUlia, PYthon and R)

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

Spyder Shortcut Keys


The following is a list of some useful spyder shortcut keys which makes you more
productive.
1 Press F5 to run the entire script
2 Press F9 to run selection or line
3 Press Ctrl + 1 to comment / uncomment
4 Ctrl+Enter executes the current cell.
5 Shift+Enter executes the current cell and advances the cursor to the next cell

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

What is Anaconda Navigator?


Anaconda Navigator is a desktop graphical user interface (GUI) that allows you to
launch applications and easily manage conda packages, environments and channels
without using command-line commands.

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.!

Features of Jupyter Notebook:


1 Edit code in the browser
2 Run code from the browser,
3 Language of choice: It supports 40+ programming languages, like Python, R, Julia,
and Scala.
4 Share notebooks: using email, Dropbox, GitHub and the Jupyter Notebook Viewer.
5 Interactive output: HTML, images, videos, LaTeX, and custom MIME types.
6 Big data integration: Leverage big data tools, such as Apache Spark, from Python, R
and Scala.

Example: (Plotting Examle)


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()

A few commands related UNIX:


1 lsmagic
2 ls
3 pwd

The four most helpful commands


command description
? Introduction and overview of IPython’s features.
%quickref Quick reference.
help Python’s own help system.
object? Details about ‘object’, use ‘object??’ for extra details.

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.

conda list ==>It list all installed packages

Goto Ancondata Prompt and do the follwing:


1 conda update conda
2 conda update spyder
3 conda install numpy
4 conda install pandas
5 conda install matplotlib
6 conda install seaborn
Anconda Navigator
Using jupyter notebook online
go to http://jupyter.org/
https://try.jupyter.org/
C:\Users\admin\.anaconda\navigator (In Our local System)
conda --help (Unix)

PIP List (Python Installs Packages)


List installed packages, including editables. Packages are listed in a case-insensitive
sorted order.

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.

$ pip install SomePackage # latest version


$ pip install SomePackage==1.0.4 # specific version
$ pip install 'SomePackage>=1.0.4' # minimum version

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.

Python Variable Name Rules


1 Python Variables Must begin with a letter (a - z, A - B) or underscore (_)
2 Python Variables should be characters like letters, numbers or _
3 Python Variables are Case Sensitive
4 Python Variables can be any reasonable length
5 Python Variables must not be reserved word or Keyword.
6 The variable names should be written in camelCase

Illegal Variable Names:


76trombones = 'Big Data'
#illegal because it does not begin with number
SyntaxError: invalid syntax

more@ = 1000000 #illegal because it contains an illegal character


SyntaxError: invalid syntax

class = 'Advanced Theoretical' #class is one of Python’s keywords.


SyntaxError: invalid syntax

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.

Examples:"iPhone ", "eBay", "FedEx", "PayPal", etc...!!

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)

type() function: It returns type of the given object.

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"))

'<' The field will be left-aligned within the available space


'>' The field will be right-aligned within the available space
'^' Forces the field to be centered within the available space

Example:
print(format(123, "<40"))
print(format(123, ">40"))
print(format("Hello", "^40"))

Data types in Python


Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of
these classes.

Standard Data Types


In Python Standard data types are Classified into 6 types:
1. Numbers
2. String
3. List
4. Tuple
5. Set
6. Dictionary

Python Numbers
Number data types store numeric values. Numeric objects are mutable, which means
when an object is created its value can be changed.

Python supports four different numerical types:


1 int 2 long 3 float 4 complex

1. int: Plain integers


Example:
x=100
y=300

2 long or Long integers (Deprecated)


Python 2 has two integer types: int and long. There is no "long int" in Python3
anymore.

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)

NOTE: A complex number is created by adding a real and an imaginary number

Example:
x=complex(1,2)
print x

Example:
y=complex(3,4)
print y

Operators and Operands


Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.

x=10
y=20
z=x+y is an Expression

Mnemonic Variable Names


This can confuse beginning students because well-named variables often “sound” so
good.

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]]]]

Delete a single object or Multiple objects:


del var
del var_a, var_b

Octal literals (base 8)


A number prefixed by 0o (zero and a lowercase "o" or uppercase "O") will be
interpreted as an octal number

Syntax:
oct(number)

Example:
a = 0o10
print(a)

Example
x = oct(65)
print(x)

Hexadecimal literals (base 16)


Hexadecimal literals have to be prefixed either by "0x" or "0X". (Zero followed by x
or X)

Syntax:
hex(number)

Example:
x = hex(19)
print(x)
Example:
x = hex(64)
print(x)

Binary literals (base 2)


Binary literals can easily be written as well. They have to be prefixed by a leading "0",
followed by a "b" or "B":

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.

TYPE CONVERSION OR TYPE CASTING

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))

Type float(x) to convert x to a floating-point number.


Example:
print(float('1.99'))
print(float(5))

str() : Used to convert integer into a string.


Example:
print(str(3.141592))
print(str([1,2,3,4]))

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))

tuple() : This function is used to convert to a tuple.


Example:
print(tuple('Mary'))
print(tuple([1,2,3,4]))

Example:
s='PYTHON'
print(tuple(s))

set() : This function returns the type after converting to set


Example:
print(set('Mary'))
print(set([1,2,3,4]))
Example:
s='PYTHON'
print(set(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))

ord() : This function is used to convert a character to integer.


Example:
s='A'
print(ord(s))

hex() : This function is to convert integer to hexadecimal string.


Example:
c = hex(19)
print (c)

oct() : This function is to convert integer to octal string.


Example:
c=56
print (oct(c))

complex(real,imag) : : This function converts real numbers to complex(real,imag)


number.
Example:
c = complex(1,2)
print (c)

String Formatting Operator:


One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf()
family.

Format Symbol Conversion


%c character
%s string conversion via str() prior to formatting
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)

Example:
print("%s having %s Years Experience in IT." %("KSRAJU","15+"))
print("%s having %d Years Experience in IT." %("KSRAJU",15))

Example:
name = "RaaJ"

print("Hello, %s!" % name)

Example:
name = "RaaJ"

age = 23

print("%s is %d years old." % (name, age))

Python math Module:


Python offers modules like math and random to carry out different mathematics like
trigonometry, logarithms, probability and statistics, etc.

Mathematical Functions:
Python includes following functions that perform mathematical calculations.

Python Number abs() Method:


The method abs() returns absolute value of x - the (positive) distance between x and
zero.

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))

Python Number floor() Method


The method floor() returns floor of x - the largest integer not greater than x.

Syntax
math.floor( x )

Example:
import math
print(math.floor(-45.17))
print(math.floor(100.12))
print(math.floor(100.72))

pow() Method: This method returns value of x to the power of y.

Syntax:
math.pow(x,y)

Example:
import math
print(math.pow(100, 2))
print(math.pow(2, 4))
print(math.pow(3, 0))

Python Number round() Method


The method round() returns x rounded to n digits from the decimal point.

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))

Python Number random() Method:


The method random() returns a random float r, such that 0 is less than or equal to r
and r is less than 1.

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

Python Arithmetical Operators


Operator Description
+ Addition Adds values on either side of the operator.
- Subtraction Subtracts right hand operand from left hand operand.
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and returns
remainder
** Exponent Performs exponential (power) calculation on operators
//Floor division Division that results into whole number adjusted to the left in
the number line

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)

Python Comparison Operators


These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.

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)

Python Assignment Operators


Operator Description
= Assigns values from right side operands to left side operand
+= Add AND It adds right operand to the left operand and assign the result to left
operand
-= Subtract AND It subtracts right operand from the left operand and assign the
result to left operand
*= Multiply AND It multiplies right operand with the left operand and assign the
result to left operand
/= Divide AND It divides left operand with the right operand and assign the
result to left operand
%= Modulus AND It takes modulus using two operands and assign the result to
left operand
**= Exponent AND Performs exponential (power) calculation on operators and
assign value to the left operand
//= Floor Division It performs floor division on operators and assign value to the left
operand

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)

Python Logical(Boolean) Operators


There are following logical operators supported by Python Scripting Language.

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)

Python Special Operators:


Python Scripting Language offers some special type of operators:
1. Membership operators
2. Identity operators

Python Membership Operators


They are used to test whether a value or variable is found in a sequence (string, list,
tuple, set and dictionary).

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)

Python Identity Operators


They are used to check if two values (or variables) are located on the same part of
the memory. Identity operators compare the memory locations of two objects.

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)

Python Bitwise Operators


These are used to perform bit operations. All the decimal values will be converted
into binary values and bitwise operators will work on these bits such as shifting them
left to right or converting bit value from 0 to 1 etc.

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.

Lets see the calculations


The bitwise AND operator (&) compares each bit of the first operand to the
corresponding bit of the second operand. If both bits are 1, the corresponding result
bit is set to 1.

Bitwise AND Operation = a & b


00001001 & 01000001 = 00000001 = 1

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)

The bitwise exclusive OR operator (^) :


It compares each bit of its first operand to the corresponding bit of its second
operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.

Bitwise Exclusive OR Operation = a ^ b


00001001 ^ 01000001 = 01001000 = 72
Example:
a=9
b = 65
print(a ^ b)

~ Binary Ones Complement


It is unary and has the effect of 'flipping' bits
>>> a = 2
>>> print(~a) #-3
First Convert 2 into 8 bit Binary 00000010 ==> 2
Compelement that 11111101 =>Starting 1 means -, 0 means +
Complement 00000010
add +1
00000011

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 ==>

<< Binary Left Shift


The left operands value is moved left by the number of bits specified by the right
operand.
a = 10 # 10=1010
a << 2; # 40=101000==>Add Two digits right side

>> Binary Right Shift


The left operands value is moved right by the number of bits specified by the right
operand.
a = 10 #10=1010
a >> 2; #2=10==>Remove two digits right side

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))

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

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); # (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)

PYTHON CONTROL STRUCTURES:


In PYTHON Programming Control Structures are classified into:
1. Sequential Control Structures
2. Selection Control Structures
3. Iterative Control Structures

1. Sequential Control Structures:


It get excutes the lines of code in sequential order.

Example:
print("First Line")
print("Second Line")
print("Third Line")

2. Selection Control Structures: (Conditional Control Statements)


It is popularly known as Python Decision Making. It is anticipation of conditions
occurring while execution of the program and specifying actions taken according to
the conditions. Python programming language provides following types of decision
making statements.
1 if statement (One-Way Decisions)
2 if .. else statement (Two-Way Decisions)
3 if .. elif .. else statement (Multi-Way Decisions)
4 Nested if .. else (inner Decisions)

In Conditions, the following Comparison or Relational Operators Commonly Using:


1 > greater than

2 >= greater than equalto

3 < less than

4 <= less than equalto

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")

Nested if .. else statement


In general nested if-else statement is used when we want to check more than one
conditions. Conditions are executed from top to bottom and check each condition
whether it evaluates to true or not. If a true condition is found the statement(s) block
associated with the condition executes otherwise it goes to next condition.

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")

Example: Use the and operator in an if statement


x = False
y = True
if x and y:
print('Both x and y are True')
else:
print('x is False or y is False or both x and y are False')

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.

Iterative Control Structures (Python Loops)


In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.

TYPES OF LOOPS in PYTHON:


1. for
2. while
3. do-while (not recomended)
4. nested loops
5. break and continue (Loop Control Statements)

Different kinds of for loops:


1 Count-controlled for loop (Three-expression for loop):
This statement is the one used by C. The header of this kind of for loop consists of a
three-parameter loop control expression. Generally it has the form: for (i=0; i <= n;
i++), This kind of for loop is not implemented in Python!

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

3 Vectorized for loops


Array programming, a style of computer programming where operations are applied
to whole arrays instead of individual elements.

4 Iterator-based for loop:


This kind of a for loop iterates over an enumeration of a set of items. It is usually
characterized by the use of an implicit or explicit iterator. It is implemented in
Python.

for loop in PYTHON:


It is used to iterate over the items of any sequence including the Python list, string,
tuple etc. The for loop is also used to access elements from a container like list,
string, tuple etc..
Syntax
for variable_name in sequence :
statement_1
statement_2

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.

3 variations of range() function:


range(stop) - Starts from O till (stop - 1)
range(start,stop) - Ends at (stop - 1)
range(start,stop,step) - Step can not be 0, default is 1

Syntax:
range(a)
range(a,b)
range(a,b,c)

range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing


by 1.

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)

range(a,b) : Generates a sequence of numbers from a to b excluding b, incrementing


by 1.
Syntax
for "variable" in range("start_number", "end_number"):

Note: Start Value must be less than end Value..!!

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)

range(a,b,c) : Generates a sequence of numbers from a to b excluding b,


incrementing by c.

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)

for loop with else clause


A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts. break statement can be used to stop
a for loop. In such case, the else part is ignored.

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 :)')

LOOPING CONTROL STATEMENTS:


A statement that alters the execution of a loop from its designated sequence is a
loop control statement.

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")

Python while Loop Statements:


while Loop is used to execute number of statements or body till the condition passed
in while is true. Once the condition is false, the control will come out of the loop.

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..!!

Python: while and else statement


There is a structural similarity between while and else statement. Both have a block
of statement(s) which is only executed when the condition is true.

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")

Python nested loops


Python programming language allows to use one loop inside another loop.

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: (Stars in Right Angle Triangle Shape)


pattern=int(input("Enter Number of Rows: "))
for i in range(1, pattern+1): #To Print rows
for j in range(1,i+1): # To Print Columns
print("*",end=" ")
print()

Example: (Print star pyramid patterns)


pattern=int(input("Enter Number of rows: "))
for i in range(pattern,0,-1): #To Print rows
for j in range(0,i): # To Print Columns
print("*",end="")
print()

Example:(Printing Stars in Pyramid Shape)


pattern=int(input("Enter Number of rows: "))
for i in range(0,pattern):
for j in range(0,pattern-i-1):
print(end=" ")
for j in range(0,i+1):
print("*",end=" ")
print()

Example:(Printing Stars in Reverse Pyramid Shape)


pattern=int(input("Enter Number of rows: "))
for i in range(pattern,0,-1):
for j in range(0,pattern-i):
print(end=" ")
for j in range(0,i):
print("*",end=" ")
print()

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()

Python pass statement:


In Python programming, pass is a null statement. The difference between a comment
and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored. However, nothing happens when pass is executed. It
results into no operation (NOP).
OR
It is used when a statement is required syntactically but you do not want any
command or code to execute.

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 Data Structure?


A data structure is a specialized format for organizing and storing data.

Define Algorithm?
A set of rules or steps used to solve a problem

A data structure is classified into two categories:


1 Linear data structures
2 Non-Linear data structures

Linear data structure:


A data structure which is sequential and continues in nature i.e. access the data in
sequential manner.
Example:
array,linked list,stack and queue.

Non Linear data structures


These are arranged in random manner. It can be used to hierarchical relationship
among data elements. Elements in non-linear data structure are attached one to
many.
Example:
Tree, Hash tree, Binary tree, Heap and graph.

Data Structures in PYTHON:


In PYTHON builtin data structures are:
1. lists (Lists are enclosed in brackets [])
2. tuples (Tuples are enclosed in parentheses())
3. sets (Sets are enclosed in curly brackets {,})
4. dictionaries (Dictionaries are built with curly brackets{})

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)

STRING OPERATIONS IN PYTHON:


In general, you can’t perform mathematical operations on strings, even if the strings
look like numbers. The + operator performs string concatenation, which means it
joins the strings by linking them end-to-end.

Example:
first="First"
second="Second"
fullstr=first+" "+second
print(fullstr)

Example:
print('Spam'*3)

Special characters in strings


In Python The backslash (\) character is used to introduce a special character.
Escape Sequence Meaning
\n Newline
\t Horizontal Tab
\\ Backslash
\' Single Quote
\" Double Quote
Example:
print("This is Back Slash (\\)Mark.")
print("This is Back Slash \t Mark.")
print("This is Back Slash \'Single Quotrs\' Mark.")
print("This is Back Slash \n Mark.")

Define String Slicing?


To cut a substring from a string is called string slicing.

String Indices or Indexing


Strings are arrays of characters and elements of an array can be accessed using
indexing. Indices start with 0 from left side and -1 when starting from right side.

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')

How to change or delete a string?


Strings are immutable. This means that elements of a string cannot be changed once
it has been assigned. We can simply reassign different strings to the same name.

Example:
str1="Naresh i Technologies"
print(str1)
str1[0]='A'
print(str1)

NOTE: TypeError: 'str' object does not support item assignment

We cannot delete or remove characters from a string. But deleting the string entirely
is possible using the keyword del.

Syntax: del string variable

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.

1 Increase indent indent after an if statement or for statement (after : )


2 Maintain indent to indicate the scope of the block (which lines are affected by the
if/for)
3 Reduce indent back to the level of the if statement or for statement to indicate the
end of the block
4 Blank lines are ignored - they do not affect indentation
5 Comments on a line by themselves are ignored with regard to indentation

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())

Python String isdigit() Method


The method isdigit() checks whether the string consists of digits only.

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 ))

Python String max() Method


the method max() returns the max alphabetical character from the string str.

Syntax
max(str)

Example:
str1="abcd"
print(max(str1))
str2="abcddcba"
print(max(str2))
str3="Maximum"
print(max(str3))
str4="12344321"
print(max(str4))

Python String replace() Method


It returns a copy of the string in which the occurrences of old have been replaced
with new, optionally restricting the number of replacements to max.

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))

Python String isalnum() Method


It checks whether the string consists of alphanumeric characters.

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.).

List has the following five characteristics:


1. MUTABLE
2. Linear Data Structure
3. Mixed Type Elements
4. Variable Length
5. Zero Based Indexing

NOTE: Traditional arrays can not be created in Python.

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)

Mixed List: A list with different datatypes is called Mixed list.


Example:
student_info = ["Sara", 1, 2.03]
print(student_info)

Nested List: A list with in another list is called Nested List.


Example:
my_list = ["mouse", [8, 4, 6], ['a']]
print(my_list)

Basic List Operations


Lists respond to the + and * operators, concatenation and repetition
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Py!'] * 3 ['Py!', Py!', 'Py!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration

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: Iteration (for)


My_Friends_List=['Raju','Smith','Sara','Scott']
for friend in My_Friends_List:
print("Advanced Happy New Year: "+friend)

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)

How to Access elements from a list?


There are various ways in which we can access the elements of a list.

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[:])

Python List Methods


In Python Scripting The following list of methods existed in List object. They are
accessed as list.method().
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
append():Add an element to the end of the 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)

NOTE:We can Modify an element by using the index of the element

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)

extend(): Add all elements of a list to the another list

Syntax:
list.extend(iterable)

Example:
alist1 = ['a', 'b', 'c']
alist1.extend(['d', 'e','f'])
print(alist1)

Python List insert()


The insert() method inserts the element to the list at the given index.

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]:

NOTE: Deprecated from PYTHON 3.x onwards

remove(): Remove an item from the list

Syntax:
list.remove(item)

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.remove("IoT")
print(py_list)

clear(): Removes all items from the 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)

count():Returns the count of number of items passed as an argument


Syntax:
list.count(item)

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT", "Hadoop"]
py_list.count("Hadoop")

sort():Sort the items of the list in place.

Syntax:
list.sort(reverse="True/False") By Default False

NOTE:sort() doesn't supports mixed data lists..!!


Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT","Big Data"]
print(py_list)
py_list.sort()
print(py_list)
py_list.sort(reverse=True)
print(py_list)
NOTE: reverse - If true, the sorted list is reversed

reverse(): Reverse the order of items in the list


Syntax:
list.reverse()

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
py_list.reverse()
print(py_list)

copy(): Returns a shallow copy of the list


Syntax:
list.copy()

Example:
py_list=["Big Data", "Hadoop", "Spark", "IoT"]
print(py_list)
print(py_list.copy())

Convert a list to a tuple in Python


MyNumList=[1,2,3,4,5]
print(type(MyNumList))
print(MyNumList)
tup=tuple(MyNumList)
print(tup)
print(type(tup))

Compare two lists in Python


listx1, listx2=[3, 5, 7, 9], [3, 5, 7, 9]
print (listx1 == listx2)
listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9]
print(listx1 == listx2)
listx1, listx2 =[2, 3, 5, 7], [3, 5, 7, 2]
print(listx1 == listx2)
print(listx1.sort() == listx2.sort())

Using Lists as Stacks


A stack is a container of objects that are inserted and removed according to the last-
in first-out (LIFO) principle

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)

Using Lists as Queues: It is a FIFO( First in First Out ) structure.


A deque, also known as a double-ended queue, is an ordered collection of items
similar to the queue. It is important to note that even though the deque can assume
many of the characteristics of stacks and queues, it does not require the LIFO and
FIFO orderings that are enforced by those data structures.

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)

List Assignment and Copying:


list1=[1,2,3,4,5,6]
list2=list1
print(list2)
print(list1)
list1[0]="PYHTON"
print(list2)
print(list1)
list3=list(list1)
print(list3)
list1[0]=0
print(list1)
print(list3)

With for loop:


result=[x**2 for x in [3,4,5]]
print(result)

How to use the double colon [ : : ]?


listx=[1, 5, 7, 3, 2, 4, 6]
print(listx)
sublist=listx[2:7:2] #list[start:stop:step]
print(sublist)
sublist=listx[::3] #returns a list with a jump every 2 times.
print(sublist)
sublist=listx[6:2:-1] #when step is negative the jump is made back
print(sublist)

Built-in Functions with List


Function Description
all() Return True if all elements of the list are true (or if the list is empty).
any() Return True if any element of the list is true. If the list is empty,return
False.
enumerate() Return an enumerate object. It contains the index and value of all the
items of list as a tuple.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sum() Return the sum of all elements in the 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:

iterable - a sequence, an iterator, or objects that supports iteration


start (optional) - enumerate() starts counting from this number. If start is omitted, 0
is taken as start.

How enumerate() works in Python?


bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
enumerateBData = enumerate(bd)
print(type(enumerateBData))
print(list(enumerateBData))

Looping Over an Enumerate object


bd = ['Big Data', 'Hadoop', 'Spark','Data Science']
for item in enumerate(bd):
print(item)

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)

Find the largest and the smallest item in a list


listx=[5, 10, 3, 25, 7, 4, 15]
print(listx)
print(max(listx))
print(min(listx))
Line 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)
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.

Advantages of Tuple over List


1 We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
2 Since tuple are immutable, iterating through tuple is faster than with list. So there is
a slight performance boost.
3 Tuples that contain immutable elements can be used as key for a dictionary. With
list, this is not possible.
4 If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

More About Tuple:


1.You can't add elements to a tuple. Tuples have no append or extend method.
2.You can't remove elements from a tuple. Tuples have no remove or pop method.
3.You can't find elements in a tuple. Tuples have no index method.

How to Create a tuple?


To create a tuple, just list the values within parenthesis separated by commas. The
"empty" tuple is just an empty pair of parenthesis.

Creating Empty Tuple:


my_tuple = ()
print(my_tuple)

Creating tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

Creating tuple with mixed datatypes


my_tuple = (1, "Data Science", 3.4)
print(my_tuple)

Creating nested tuple


my_tuple = ("Data Science", (8, 4, 6), (1, 2, 3))
print(my_tuple)

Tuple packing.
Creating tuple without parentheses, also called tuple packing.
my_tuple = 3, 4.6, "Data Science"
print(my_tuple)

#Tuple unpacking is also possible


a, b, c = my_tuple
print(a)
print(b)
print(c)

NOTE:
if a value is more, it dislays "Value Error",
if a variable is more, it displays "not enough values"

Creating a tuple with one element is a bit tricky.


Having one element within parentheses is not enough. We will need a trailing comma
to indicate that it is in fact a tuple.

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))

How to get an item From the tuple?


tuplez = ("P", "Y", "T", "H", "O", "N", "S", "C", "R", "I","P","T")
print(tuplez)
item = tuplez[3]
print(item)
item1 = tuplez[-4]
print(item1)

Tuple Membership Test:


We can test if an item exists in a tuple or not, using the keyword in.

Example:
tuplez = ("P", "Y", "T", "H", "O", "N", "S", "C", "R", "I","P","T")
print(tuplez)
print("R" in tuplez)
print(5 in tuplez)

Iterating Through a Tuple


Using a for loop we can iterate though each item in a tuple.

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)

Slice of a tuple using step parameter


tuplez = tuple("DATA SCIENCE")
print(tuplez)
x = tuplez[2:9:2]
print(x)
y = tuplez[::4]
print(y)
z = tuplez[9:2:-3]
print(z)

How operators + and * are used with a Python tuple?

#+ 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)

Python Tuple Methods


In Tuple Only the following two methods are available.

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

In Python how to know the number of times an item has repeated


tuplez = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplez)
count = tuplez.count(4)
print(count)
count = tuplez.count(7)
print(count)
count = tuplez.count(5)
print (count)

Find the index of an item of the tuple


tuplez = tuple("index tuple")
print(tuplez)
index = tuplez.index("p")
print(index)
index = tuplez.index("e", 5)
print(index)
index = tuplez.index("e", 3, 6)
print(index)

Add item in tuple!


Method-I
tuplez = (4, 6, 2, 8, 3, 1)
print(tuplez)
tuplez = tuplez + (9,)
print(tuplez)

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)

Remove an item from a tuple (Through List)


tuplez = "P", "Y", "T", "H", "O", "N", "S"
print(tuplez)
listx = list(tuplez)
listx.remove("P")
tuplez = tuple(listx)
print(tuplez)

Built-in Functions with Tuple


Function Description
all() Return True if all elements of the tuple are true (or if the tuple is
empty).
any() Return True if any element of the tuple is true. If the tuple is empty,
return False.
enumerate() Return an enumerate object. It contains the index and value of all the
items of tuple as pairs.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
sorted() Take elements in the tuple and return a new sorted list (does not
sort the tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a 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

The all() method returns:


True - If all elements in an iterable are true
False - If any element in an iterable is false

Truth table for all()


When Return Value
All values are true True
All values are false False
One value is true (others are false) False
One value is false (others are true) False
Empty Iterable True

NOTE: 0 and 1 are the binary values like False, True

Example:How all() works for tuple and lists?


s = (1, 3, 4, 5)
print(all(s))

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)

The any method returns:


True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty

When Return Value


All values are true True
All values are false False
One value is true (others are false) True
One value is false (others are true) True
Empty Iterable False

NOTE: 0 and 1 are the binary values like False, True

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)

Sort a given sequence: string, list and tuple


Example:
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))

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)

Python tuple() Function


The tuple() built-in is used to create a tuple in Python.

Syntax:
tuple(iterable)

Parameter:
iterable (optional) an iterable (list, range etc.) or an iterator object

# creating a tuple from a list


t2 = tuple([1, 4, 6])
print(t2)

# creating a tuple from a string


t1 = tuple('Python')
print(t1)

#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.

How to create a set?


A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set(). It can have any number of items and
they may be of different types (integer, float, tuple, string etc.)

There are currently two built-in set types:


1 set ==> The set type is mutable
2 frozenset. ==> It is immutable and hashable
Example:
fruit_basket={"Apple","Mango","orange","banana","Apple","Mango"}
print(type(fruit_basket))
print(fruit_basket)

Example:
We should not use empty curly brackets, treat as dictionary..!!
b={}
type(b)

Set not allowed duplicates but list allows


numbers=[1,2,3,4,1,2,3,4,5]
unique_numbers=set(numbers)
print(unique_numbers)

Iteration Over Sets


We can move over each of the items in a set using a loop. However, since sets are
unorded

Example:
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)

Different Python Set Methods


Method Description
add() Add an element to a set
clear() Remove all elements form a set
copy() Return a shallow copy of a set
difference() Return the difference of two or more sets as a new set
discard() Remove an element from set if it is a member. (Do nothing if the
element is not in set)
intersection() Return the intersection of two sets as a new set
isdisjoint() Return True if two sets have a null intersection
issubset() Return True if another set contains this set
issuperset() Return True if this set contains another set
pop() Remove and return an arbitary set element. Raise KeyError if the set is
empty
remove() Remove an element from a set. If the element is not a
member, raise a KeyError
symmetric_difference() Return the symmetric difference of two sets as a new
set
union() Return the union of sets in a new set
update() Update a set with the union of itself and others

How to change a set in Python?


We can add single element using the add() method and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as
its argument. In all cases, duplicates are avoided.

Python Set add():


It adds a given element to a set. If the element is already present, it doesn't add any
element.

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)

Add tuple to a set


vowels = {'a', 'e', 'u'}
tup = ('i', 'o')# a tuple
vowels.add(tup)# adding tuple
print('Vowels are:', vowels)

Python Set update():


It adds elements from a set (passed as an argument) to the set (calling the update()
method).

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)

Example:add list and set


data_set=set()
data_set.update([4,5], {1,6,8})
print(data_set)

How to remove elements from a set?


Python Set pop()
It removes an arbitrary element from the set and returns the element removed.

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)

Python Set remove()


It searches for the given element in the set and removes it, but not a member of the
set, a KeyError will be raised.

Syntax:
set.remove(element)

Example:
num_set = set([0, 1, 2, 3, 4, 5])
num_set.remove(0)
print(num_set)

Trying to Delete Element That Doesn't Exist


Example:
animal = {'cat', 'dog', 'rabbit'}
animal.remove('fish')
print('Updated animal set: ', animal)

Python Set discard()


An element will be removed from the set, if it is contained in the set. If not a member
of the set, nothing will be done.

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.

setx = set(["Big Data", "Data Science"])


sety = set(["Data Science", "Spark"])
seta = setx | sety #Union
print (seta)

Python Set difference()


The difference() method returns the set difference of two sets.
A = {1, 2, 3, 4}
B = {2, 3, 9}
Then,
A - B = {1, 4}
B - A = {9}
Syntax
A.difference(B)

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))

Set copy(): It returns a shallow copy of the set.

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())

Example:Set Union Using | Operator


A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C= {1, 2, 3}
print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)

Special Operators with set (Membership operators)


x={"a","b","c","d","e"}
print("a" in x)
print("d" in x)
Iterations with for loop:
x={"a","b","c","d","e"}
for i in x:
print(i)

Built-in Functions with Set


Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any() Return True if any element of the set is true. If the set is empty, return
False.
enumerate() Return an enumerate object.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set(does not sort
the set itself).

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)

frozensets have less methods than sets.


There are some operators similar to sets intersection(), union(),
symmetric_difference(), difference(), issubset(), isdisjoint(), issuperset()) and a
copy() method.

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)

AttributeError: 'frozenset' object has no attribute 'add'

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

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma. An item has a key and the corresponding value expressed as a pair, key:
value. While values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must be
unique.

Create a new dictionary in Python


Example:
# empty dictionary
my_dict = {}
print(type(my_dict))

# dictionary with integer keys


my_dict = {1: 'Bigdata', 2: 'Hadoop'}
print(type(my_dict))

# dictionary with mixed keys


my_dict = {'name': 'NareshIT', 1: [2, 4, 3]}
print(type(my_dict))

Using dict Keyword:


# using dict()
my_dict = dict({1:'Bigdata', 2:'Hadoop'})
print(type(my_dict))

# from sequence having each item as a pair


my_dict = dict([(1,'Bigdata'), (2,'Hadoop')])
print(type(my_dict))

#with col keys


color = {"col1" : "Blue", "col2" : "Green", "col3" : "White" }
print(type(color ))

Get value by key in Python dictionary


Example:
dict1 = {1:20.5, 2:3.03, 3:23.22, 4:33.12}
print(dict1[1])
print(dict1[3])

Add key/value to a dictionary in Python


Example:
dic = {'pdy1':'DICTIONARY'}
print(dic)
dic['pdy2'] = 'STRING'
print(dic)

Example:
my_dict = {'name':'NareshIT', 'age': 15}
print(my_dict)
my_dict['age'] = 27
print(my_dict)

Comparing Lists and Dictionaries:


Dictionaries are like lists except that they use keys instead of numbers to look up
values.

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

Python Dictionary Methods


Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v
(defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if key is not found. If
d is not provided and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises KeyError
if the dictionary is empty.
update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values

The fromkeys() method


It creates a new dictionary from the given sequence of elements with a value
provided by the user.

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()

NOTE: The items() method doesn't take any parameters.

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])

NOTE: It doesn't return any value (returns None).

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()

NOTE: The keys() doesn't take any parameters.

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()

NOTE: The values() method doesn't take any parameters.

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()

NOTE: The popitem() doesn't take any parameters.

Example:
person = {'name': 'NareshIT', 'age': 15, 'salary': '$35000.0'}
result = person.popitem()
print('person = ',person)
print('Return Value = ',result)

Other Dictionary Operations (Dictionary Membership Test)


We can test if a key is in a dictionary or not using the keyword in. Notice that
membership test is for keys only, not for values.

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)

Built-in Functions with Dictionary


Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty,
return False.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
len()
It returns the number of items (length) of an object.

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))

range() vs xrange() in Python


range() and xrange() are two functions that could be used to iterate a certain
number of times in for loops in Python. In Python 3, there is no xrange , but the range
function behaves like xrange in Python 2.If you want to write code that will run on
both Python 2 and Python 3, you should use range().

1 range() – This returns a list of numbers created using range() function.


2 xrange() – This function returns the generator object that can be used to display
numbers only by looping.

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))

Main Difference between range and xrange:


1. range() always returns list output for any version
2. xrange() always returns genarator xrange object (Deprecated)
3. range() displays without for loop-range(1,5) in PYTHON-2.x
4. xrange() required for loop to return values in PYTHON-2.x (Deprecated)
5. range() takes More Memory, xrange() takes Less Memory
6. range() for list operations, xrange() is not for list
7. range() faster, xrange() slower
8. xrange() renamed as range() in Python-3.0
9. Python-2.0 range() function deprecated from PYHTON-3.0
10. in Python-2 <type xrange>, in Python-3 <class range>

2 Memory
import sys
print(sys.getsizeof(range(100))) #More Memory
print(sys.getsizeof(xrange(100))) # Less Memory

Das könnte Ihnen auch gefallen