PYTHON Notes1
PYTHON Notes1
Python
Introduction
❖ Python is a general-purpose and high-level programming language.
❖ Python was developed by Guido Van Rossam in 1989 while working at National Research
Institute at Netherland
❖ But Officially python was made available to public in 1991. The official date of birth of the
python is: Feb 20th 1991.
Why Python?
❖ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, and more).
❖ Python has a simple syntax similar to the English language.
❖ Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
❖ Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
❖ Python can be treated in a procedural way, an object-oriented way or a functional way
❖ Application Automation
❖ Data Analytics
❖ Scientific app
❖ Web application
❖ Web scrapping
❖ GUI
❖ Gaming
❖ Business Applications
❖ Animation
❖ Machine Learning and more
G-TECH EDUCATION
All the keywords except True, False and None are in lowercase and they must be written as they
are. The list of all the keywords is given below.
Identifiers in Python
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one
entity from another.
Variables
A variable is a quantity that may change within the context of a mathematical problem or experiment.
Typically, we use a single letter to represent a variable. The letters x, y, and z are common generic
symbols used for variables.
Example: x= 5
y= 10
name = ‘python’
name = “python”
Data Types
Programming languages supports too different varieties of data types
❖ In Static data types supported languages programmer should define the data type to the
variable explicitly.
❖ In static data types supported languages one variable can store one variety of data.
❖ C, C++, JAVA, .NET languages are supporting static data types.
❖ In dynamic data types supported languages programmer should not define the data type to
variable explicitly.
❖ At the time of execution of the program based on the data which is assigned to the variable,
data type of the variable is decided.
❖ Python, java script languages are supporting dynamic date types.
❖ Every data type in python language is internally implemented as a class
Example
a = 10 → “value 10 is stored in a”
b = None
print(b)
print(type(b))
Output:
None
<class ‘None Type>
Numeric
List
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [].
Example: x = [10,15,20,25]
y = [‘python’, ‘sql’, ‘dbms’]
z = [10, ‘python’, 9.5]
Example
a = [10,20,30,40,50]
print(a)
a = [10,20,30,40,50,60,10,20,30]
print(a)
Tuple
a = (10,20,30,40,50)
a = tuple(10,20,30,40,50)
Set
❖ Sets are used to store multiple items in a single variable.
❖ A set is a collection which is both unordered and unindexed.
❖ Sets are written with curly brackets {}.
Method: 1
a={10,22,55,66,22}
Method: 2
a=set([10,22,55,66,22])
G-TECH EDUCATION
Example
a = {10,20,30,40,50,60,70}
a.add(100) # add single value in to the set
a.update([1,2,3,4]) # add multi values in to the set
a.remove(50) # remove the single value if value is not available it throws error
a.discard(100) # remove the single value even though value is not available it does
not throw error.
a.pop() # randomly value is removed from the set
del(a) # total data set is deleted.
a={1,2,3}
b={10,20,30}
c={'a','b','c'}
Method 1 (Pipeline)
Method 2 (Concatenate)
Intersection of SET: Intersection of two or more sets form a new set consisting of only the common
elements present in those sets.
a={1,2,3,4,1,2,'abc'}
b={2,3,10,20,1,2,'abc'}
c={2,20,3,'abc'}
G-TECH EDUCATION
Method 2:
Range
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.
Syntax:
range(start, stop)
range(0,10)
Syntax :
range(start, stop, step)
G-TECH EDUCATION
range(0,10,2)
a = range(1,10)
b = list(range(1,10))
c = tuple(range(1,10))
d = set(range(1,10))
Dictionary
❖ Dictionaries are used to store data values in (key : value) pairs.
❖ A dictionary is a collection which is ordered, changeable and does not allow duplicates.
❖ Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
❖ Keys in a dictionary doesn’t allows Polymorphism.
❖ While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [] or with the get() method.
❖ If we use the square brackets [], Key Error is raised in case a key is not found in the dictionary.
❖ On the other hand, the get() method returns None if the key is not found.
Get Values
It returns all values in the dictionary
a = {'name': "Raju", 'age': 26}
print(a.values())
G-TECH EDUCATION
❖ Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.
❖ If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
update value
a['age'] = 27
print(a) → Output: {'age': 27, 'name': 'Raju'}
add item
a['address'] = “Kamala Nagar”
print(a) → Output: {'address': ' Kamala Nagar ', 'age': 27, 'name': 'Raju'}
fromkeys()
It returns a dictionary from the given sequence of elements with a value provided by the user.
x = ('a','b','c')
y=1
z = dict.fromkeys(x, y)
print(z)
Out put : {'a': 1, 'b': 1, 'c': 1}
x = ('a','b','c')
z = dict.fromkeys(x)
print(z)
Output : {'a': None, 'b': None, 'c': None}
Items()
Output:
dict_items([('CSE', 60), ('ECE', 90), ('EEE', 60)])
G-TECH EDUCATION
❖ We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
❖ The popitem() method can be used to remove and return an arbitrary (key, value) item pair
from the dictionary. All the items can be removed at once, using the clear() method. The del()
keyword can also delete the dictionary completely
❖ We can also use the del keyword to remove individual items or the entire dictionary itself.
Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4)) → Output:16
print(squares) → Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares.popitem()) → Output: (5, 25)
print(squares) → Output: {1: 1, 2: 4, 3: 9}
squares.clear()
print(squares) → Output: {}
A = {1,2,3}
del(A)
String
❖ A string in Python is a sequence of characters.
❖ Strings in python are surrounded by either single quotation(‘ ‘) marks, or double quotation (“ “)
marks.
❖ Python does not have a character data type, a single character is simply a string with a length
of 1.
Example
print(“python")
print(‘python')
Multi line string
We can assign a multiline string to a variable by using three quotes (“”” “””) (‘ ‘ ‘ ‘ ‘ ‘ )
Strings are Arrays
❑ Strings in Python are arrays of bytes representing uni-code characters.
❑ Python does not support a character type these are treated as strings of length one.
❑ Square brackets can be used to access elements of the string.
Slicing a string
a='python‘
G-TECH EDUCATION
print(a[0]) p
print(a[1:]) ython
print(a[1:4]) yth
print(a[-5:-1]) ytho
print(a[-5:]) ython
Check String
Check string is used check if a certain phrase or character is present in a string, we can use the
keyword “in”.
Example
str = "python is high-level language"
print("python" in str)
Output: True
str = "python is high-level language"
print(“Java" in str)
Output: False.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword “not in”.
Example
star = "python is high-level language"
print("Java" not in star)
Output: True
String Length
To get the length of a string, use the Len() function.
a = "Python"
print(Len(a))
Output: 6
converting text in lower case
a="PYTHON"
print(a.lower())
print(a.replace("p","P"))
splits the string into substrings
a="Good Morning , Raju"
print(a.split(","))
Remove White space
a=" Good Morning Raju "
print(a.strip())
concatenate or adding
a = "Hello "
b= "Good morning"
c= a+b
print(c)
Multiply the string
a="python "
print(a*4)
Format String
format() is a function used to replace, substitute, or convert the string with placeholders with valid
values in the final string.
Concatenate the different data types by using format method
a = "I am Raju my age is {}."
age = 25
print(a.format(age))
Output : I am Raju my age is 25.
Concatenate by using index number in format method
name = 'Raju'
bankaccountnumber = '123456'
balance = 50485.8
accountbal = "My name is {2}, my account number is {1} available balance is {0}"
print(accountbal.format(balance, bankaccountnumber, name))
Output : My name is Raju, my account number is 123456 available balance is 50485.8
Methods in String
Method Description
swapcase() It swaps cases, lower case becomes upper case and vice versa
endswith() It returns true if the string ends with the specified value
startswith() It returns true if the string starts with the specified value
It searches the string for a specified value and returns the position of
find() where it was found
isalpha() It returns true if all characters in the string are in the alphabet
islower() It returns true if all characters in the string are lower case
isupper() It returns true if all characters in the string are upper case
zfill() It fills the string with a specified number of 0 values at the beginning
val1 = 10 #int
val2 = 10.9 #float
val3 = val1+val2 # float ---> Implicit
val4 = int(val3) # int --> Explicit
print(val3)
print(val4)
print(type(val3))
print(type(val4))
G-TECH EDUCATION
val1 = 5.2
val2 = str(val1)
print(type(val1))
print(type(val2))
val3 = '5'
val4 = int(val3)
val5 = float(val3)
print(type(val3))
print(type(val4))
print(type(val5))
Operators
Operators are used to perform operations on variables and values.
Types of Operators
❖ Arithmetic operators
❖ Assignment operators
❖ Relational operators
❖ Logical operators
❖ Identity operators
❖ Membership operators
❖ Bitwise operators
G-TECH EDUCATION
Arithmetic operators
These are used to perform mathematical operations like addition, subtraction, multiplication and
division.
Assignment operators
Assignment operators are used to assign values to the variables.
OPERATOR SYNTAX
= a=5
+= a+=5
-= a-=5
*= a*=5
/= a/=5
//= a//=5
%= a%=5
**= a**=5
G-TECH EDUCATION
Relational Operators
Relational operators are used to compare between two values.
Operator Syntax
Equal (==) a==b
Logical Operators
Logical operators are used for conditional statements are true or false.
Identity Operators
These are used to compare the whether two objects are same or not.
It returns True if memory location of two object are same else it returns False.
Membership Operators
These are used to check whether a value/variable exists in the sequence like string, list, tuples, sets,
dictionary or not.
Bitwise Operators