What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications.
Python Popular Frameworks and Libraries
Web development (Server-side) - Django Flask, Pyramid, CherryPy
GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
Mathematics - Numpy, Pandas, etc.
------------------------------------------------------------
Python Variables
Variable is a name that is used to refer to memory location.
Camel Case --nameOfStudent,
Pascal Case--NameOfStudent
Snake Case --name_of_student
Multiple Assignment
x=y=z=50
Python Variable Types
Local Variable
Global Variables--if you want to use global variable inside function use global
keyword.
java VS python:-Python variables are dynamically typed whereas Java variables are
statically typed
------------------------------------------------------------
Python Data Types
Variables can hold values, and every value has a data-type.
Numbers
Sequence Type
Boolean
Set
Dictionary
1.Numbers:-Int,float,complex
2.Sequence:-String,List,Tuple
Java Vs python:-no tuples in java. java uses ArrayList<integer>(); for create
list.java uses HashSet<String>aSet=new HashSet<String>();for set.
HashMap<String,String>phoneBook=new HashMap<String,String>(); use for dictionaries.
------------------------------------------------------------
Python Keywords
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
------------------------------------------------------------
Python Operators
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
1.Arithmetic :-**(Exponent),//(Floor Division)
2.Assignment:-**=,//=
3.Bitwise:-&(binary and),|(binary or),^(xor),~(negation),<<(left shift),>>(right
shift)
4.member shif-:in , not in
5.Identity:-is , is not
precidence:-**,~+-,*/%//,+-,>><<,^|,<=<>>=,-=..,is,in
------------------------------------------------------------
Comments
# -single line
Python Docstrin-:It's designed to link documentation developed for Python modules,
methods, classes, and functions together.
"""this fun add"""
------------------------------------------------------------
If-else statements
if
if-else
Nested if
------------------------------------------------------------
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use
of parentheses for the block level code. In Python, indentation is used to declare
a block.
------------------------------------------------------------
Python Loops
while
for
nested
Loop control
Break
Continue
Pass
Note:statement is used when a statement is Syntactically necessary,but no code is
to be executed.
range() :-range() function, we may produce a series of numbers
syntex:-for i in range(10)
------------------------------------------------------------
Python String
Python string is the collection of the characters surrounded by single quotes,
double quotes, or triple quotes. The computer does not understand the characters;
internally, it stores manipulated character as the combination of the 0's and 1's.
Syntax:
str = "Hi Python !"
1.Strings indexing and splitting
str = "JAVATPOINT"
Print(str[0:]) start 1 to last
Print(str[0:5])
Print(str[:3]) 0 to 2nd index
2.Reassigning Strings
str = "HELLO"
print(str)
str = "hello"
print(str)
3.Deleting the String
str1 = "JAVATPOINT"
del str1
print(str1)
4.Escape Sequence
print("q\b\")-output q b
print("\\")-\
print('\'')-'
print("\"")-"
print(""hello \b world)-hello world
print("hello \n world")-hello new line world
print("\t")-tab
4.String Formatting Using % Operator
integer=10
float=1.3
string="ayush"
print("i am %d,%f,%s",integer,float,String)
5.String functions
count(string,begin,end),isalnum(),isalpha(),isdecimal(),islower(),isupper(),join(se
q),len(string),lower(),lstrip(),replace(old,new[,count]),swapcase(),upper(),
------------------------------------------------------------
Python List
A list in Python is used to store the sequence of various types of data.
list1 = [1, 2, "Python", "Program", 15.9]
1.Characteristics of Lists
Orderd
access by index
mutable
2.Splitting
list_varible(start:stop:step) - indexing
3.Updating List Values
list = [1, 2, 3, 4, 5, 6]
list[2] = 10
list[1:3] = [89, 78] //assign multiple values
print(list)
4.List Operations
Repetition
Concatenation - using + operator
Length - len(list1)
Iteration - for i in list1: print(i)
Membership
5.Adding Elements to the List
l =[]
n = int(input("Enter element"))
for i in range(0,n):
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
6. Removing Elements from the List
list.remove(2)
7.List Built-in Functions
len()
max()
min()
------------------------------------------------------------
Python Tuples
Characterstics
ordered
unchangeable(immutable),
allow duplicate
Different data type
1.Creating of Tuple:
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
2.Accessing Tuple Elements-by index
3.Slicing-like list
4.Deleting a Tuple-we are unable to get rid of or remove tuple components.
step1 convert tuple into list using list() function
step2 convert list into tuple using tuple() function
tuple1=(1,2,34,5,7,8)
print(tuple1)
listx = list(tuple1)
listx.remove(2)
tuplex = tuple(listx)
print(tuplex)
Tuple Methods
Count () Method
------------------------------------------------------------
Python Set
Sets are used to store multiple items in a single variable.
Charactristic
unordered
mutable
duplicate not allowed
It is also possible to use the set() constructor to make a set
1.Adding items to set
Python provides the add() method and update() method which can be used to add some
particular item to the set.
months=set("ayush",3)
months.add("july")
mohths.update(["sharma"])
2.Removing items from the set
Python provides the discard() method and remove() method which can be used to
remove the items from the set.
discard()-if item not exist no change
remove()-if item not exist do error
Python Set Operations
1.Union of two Sets-view of all data of two sets
set1={1,2,4,5}
set1={7}
print(set1|set2)
print(set1.union(set2))
2.Intersection of two sets
show only unmatched data
using & and intersection() function
3.intersection_update() -used to remove item from the original set that are not
present in both sets
4.Frozenset: immutable form of normal set using frozenset()method.
Frozenset=frozenset([2,3])
5.set methods
copy(),Issubset(....), pop(),update()
------------------------------------------------------------
Python Dictionary- in which can simulate the real-life data arrangement where some
specific value exists for some particular key.
mutable
Python Dictionary is used to store the data in a key-value pair format.
It is the mutable data-structure.
The elements Keys and values is employed to create the dictionary.
Keys must consist of just one element.
Value can be any type such as list, tuple, integer, etc.
1.Creating the Dictionary
Dict = {"Name": "Chris", "Age": 20}
2.Accessing the dictionary values
by key
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
3.Adding Dictionary Values
Dict = {}
Dict[0] = 'Peter'
output
{0: 'Peter'}
4.update
Dict[3] = 'JavaTpoint'
you also update using key
5.Deleting Elements using del Keyword
del Employee["Name"]
Deleting Elements using pop()
pop_key = Dict.pop(2)
6.Built-in Dictionary Functions
1.len()-Python's len() method returns the dictionary's length.
2.any()-The any() method returns True indeed if one dictionary key does have a
Boolean expression of True, much like it does for lists and tuples.
3.all()-Unlike in any() method, all() only returns True if each of the dictionary's
keys contain a True Boolean value.
4.sorted()-The sorted() method returns an ordered series of the dictionary's
keys.sorted(dict)
5.clear()-It is used to delete all the items of the dictionary.
dict.clear()
print(dict)
6.copy()-It returns a shallow copy of the dictionary.
dict_demo = dict.copy()
print(dict_demo)
7.pop()-eliminates the element using the defined key.x = dict_demo.pop(1)
8.popitem()-removes the most recent key-value pair entered,
dict_demo.popitem()
print(dict_demo)
9.keys()-It returns all the keys of the dictionary.print(dict_demo.keys())
10.items()-It returns all the key-value pairs as a tuple.print(dict_demo.items())
11.get()-It is used to get the value specified for the passed key.
print(dict_demo.get(3))
12.update()- t updates the dictionary by adding the key-value pair.
dict_demo.update({3: "TCS"})
13.values()-It returns all the values of the dictionary.print(dict_demo.values())
------------------------------------------------------------
Python Lambda Functions
Lambda Functions in Python are anonymous functions, implying they don't have a
name. The def keyword is needed to create a typical function in Python, as we
already know. We can also use the lambda keyword in Python to define an unnamed
function.
Syntax of Python Lambda Function
lambda arguments: expression
Example of Lambda Function in Python
add = lambda num: num + 4
print( add(6) )
What's the Distinction Between Lambda and Def Functions?
Let's glance at this instance to see how a conventional def defined function
differs from a function defined using the lambda keyword. This program calculates
the reciprocal of a given number:
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable
such as a list.
list_ = [34, 12, 64, 55, 75, 13, 63]
odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
print(odd_list)
Using Lambda Function with map()
------------------------------------------------------------