PYTHON PROGRAMMING LANGAUGE
Father Of Python – Guido Van Rossum (born in 1956)
Python was created in the late 1980s
Python was available in 1991
Python 2.0, released in 2000
Latest Version of python available – 3.9.1
Features of Python
Simple and easy to learn
Platform Independent
Case sensitive
Process of Programming
1. Define and model the program
2. Obtain a logical solution to your problem also called algorithm
3. Can visualize using flowchart
4. Convert algorithm into working code
5. Syntax and semantics of language
Types of Operators
1. Arithmetic operators -> +, -, * ,/ (result in division), % , //(gives
quotient) , **(power)
2. Assignment operators -> += , -= ,* = , /= , %= ,**=
3. Comparison operators -> == , != , >, < ,>= , <=
4. Logical operators -> and ,or ,not
5. Bitwise operators
6. Identity operators -> Give result always in Boolean format(True or False)
is (return true if both variables are the same object ) , is not
(returns true if both variables are not the same object)
7. Membership Operators -> Give result always in Boolean format(True or
False)
in (True if value/variable is found in the sequence Ex: a=”apple” b =’a’
b in a =True), not in (True if value/variable is found in the sequence)
NOTE : In python if we write x=15 then x is a variable which points to
the memory location where 15 is stored…. If we write y=15 the both
x and y points to the memory location where 15 is stored (basically x
and y are pointers).
NOTE : In python, 0O means octal.
NOTE : Select the text you want to comment and press Ctrl +/ to
comment multiple lines together. ‘#’ is used to comment single line.
For multi line comment use “ “ “ “ “ “
NOTE : input() function is used to take input from keyboard and by
default it take input in string format ,if we need to take int input the
int(input()) {can be used for any data type}
Ex :a= int(input(“Enter a number : “)->a will take integer input
print(“Input number : “,a)
Output:
Enter a number : 14
Input number : 14
TYPES OF ERRORS
1. Syntax error
Arise when python parser is unable to understand a line of
code. Ex – typos(spelling mistake ), incorrect indentation, or
incorrect arguments
2. Logical Error
It occurs when there is fault in logic of problem. They do not
usually cause a program to crash. However, they can cause a
program to produce unexpected result.
3. Run Time Error
A program with runtime error is one that passed the
interpreter’s syntax checks, and started to execute. However,
during the execution of one of the statements in the program,
an error occurred that caused the interpreter to stop
executing the program and display an error message.
KEYWORDS
They are also known as reserved words or preserved words.
Total 33 keywords in python
All other keywords except True, False and None (used to
define null value) are in lower case.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
IDENTIFIERS
Name given to entities like class, function, variables helps to
differentiate one entity from another
RULES FOR IDENTIFIERS
Can’t start with digit
Can be of any length
Keywords can’t be used
Special symbols are not allowed (except underscore)
Can take only alphabets, underscore or digit(not in beginning)
DATA TYPES - which type of data is given to variables
Numeric Dictionary Boolean Set Sequence Type
Integer (int) Complex Float (float) Strings (str) List Tuple
Number
Check the Data type- use type(variable name) function to find
the type of variable
Ex : a=10
print(type(a)) -> class<int>
Types of Typecasting – conversion of one data type to another
1. Implicit Typecasting – Type of conversion in which data type is
converted to other automatically
Lowest Rank -> Highest Rank(it is done automatically)
char -> short int -> int ->unsigned int ->long int->unsigned long
int->float->double->long double
Ex – 2 + 2.4 =4.4(float)
2. Explicit Typecasting – Type of conversion in which user has to
convert data type from one to another
Syntax: required_datatype (expression)
Ex : a=”123”
b=10
a=int(a)
print(a+b)
Output : 133
String Function
1. isalnum() : to check whether string is alpha numeric or not
alpha numeric string – consists of char and
numbers not spaces(return Boolean value)
2. count() : to check how many times a character is present in
string(return integer value)
Ex – str= “I am Learning python programming”
print (str.count(“m”))-> return 3
3. endswith() : it is used to find whether string ends with word
or not (return Boolean value)
Ex – str = “I am Learning programming”
print (str.endswith(“programmings”))->return false since last
word is programming not programmings
4.capitalize() : It is used to convert first small letter of string
to capital , If in string other than the first
character other other in string is capital it will convert it ito
small letter.
Ex: str = “i am doing Python Programming”
print(str.capitalize()) -> I am doing python programming
5.find() : To find the index of the word in string i.e. it will tell
the index of the very first letter of word
Ex : str = “I am Learning python Programming”
print(str.find(‘python’) ->return 14 (tell index of p)
6.upper() : suppose all characters of string are small to
Convert them into capital letters this function is
Used.
Ex : str = “I am learning python programming”
print(str.upper())
str.upper()
print(str)
Output: I AM LEARNING PYTHON PROGRAMMING
I am learning python programming
7.lower() : to convert all letters of string to small
Ex : str = “I AM LEARNING PYTHON PROGRAMMING “
print(str.lower())
Output: i am learning python programming
8.split(): to make string separated by spaces to list
Ex: song="JINGLE Bells jingle Bells Jingle All The Way"
song.upper()
print(song)
song_words=song.split()
print(song_words)
count=0
for word in song_words:
if(word.startswith("jingle")):
count=count+1
print(count)
OUTPUT:
JINGLE Bells jingle Bells Jingle All The Way
[‘JINGLE’,’Bells’,’jingle’,’Bells’,’Jingle’,’All’,’The’,’Way’]
1
set():set() method is used to convert any of the iterable to
sequence of iterable elements with distinct elements,
commonly called Set.
Syntax : set(iterable)
Parameters : Any iterable sequence like list, tuple or
dictionary.
Returns : An empty set if no element is passed. Non-
repeating element iterable modified as passed as argument.
EX:
# Python3 code to demonstrate the
# working of set() on list and tuple
# initializing list
lis1 = [ 3, 4, 1, 4, 5 ]
# initializing tuple
tup1 = (3, 4, 1, 4, 5)
# Printing iterables before conversion
print("The list before conversion is : " + str(lis1))
print("The tuple before conversion is : " + str(tup1))
# Iterables after conversion are
# notice distinct and elements
print("The list after conversion is : " + str(set(lis1)))
print("The tuple after conversion is : " + str(set(tup1)))
Output:
The list before conversion is : [3, 4, 1, 4, 5]
The tuple before conversion is : (3, 4, 1, 4, 5)
The list after conversion is : {1, 3, 4, 5}
The tuple after conversion is : {1, 3, 4, 5}
Lists
It can store multiple data type
It is also called as Mutable(can change).
To declare a list use square brackets [ ]
Ex : a=[“A”,10.5,7,”b”]
Its indexing start from 0 (left to right)
Ex : a=["Python",32,56.2,"N",34.5,12]
print(a) -> ["Python",32,56.2,"N",34.5,12]
print(a[0]) -> Python
sort : used to write the list in ascending order used to sort
list consisting of float or integer values (not string and
float/int) or it can sort list consisting of only
strings(lowercase/uppercase : both present than lowercase
is after all uppercase string are over)
Ex: c = ["A", "Python" ,"C" ,"d"]
c.sort ()
print (c) ->['A', 'C', 'Python', 'd']
reverse : to reverse the list
Ex: b = [32.12, 12, 43, 5.9]
b.reverse()
print (b) -> [5.9,43,12,32.12]
Note : To get the list b in descending order first sort it
(convert into ascending order) then whatever operation will
be made on b will be done on sorted list so then reverse the
list (get list in descending order)
Ex : b=[32.12, 12,43, 5.9]
b.sort()
print(b) -> [5.9, 12, 32.12, 43]
b.reverse()
print(b) -> [43, 32.12, 12, 5.9]
Slicing In List
Ex : b=[5,1,6,2,7,8,3]
print(b[1:4]) -> [1,6,2]
print(b[0:6]) -> [5,1,6,2,7,8]
len() : used to find length of list
Ex : b=[5,1,6,2,7,8,3]
print(len(b)) -> 7
max : used for finding the maximum term of list
Ex : b=[5,1,6,2,7,8,3]
print(max(b)) -> 8
min : used to find minimum term of list
Ex : b=[5,1,6,2,7,8,3]
print(min(b)) -> 1
append : used to adding any number in the list
Ex : b=[5,1,6,2,7,8,3]
b.append(10)
print(b) -> [5,1,6,2,7,8,3,10]
remove : used to remove a number from your list
Ex : b=[5,1,6,2,7,8,3,10]
b.remove(8)
print(b) -> [5,1,6,2,7,3,10]
insert: add no. to given position
b.insert(2,5)->insert 5 at index 2
pop: remove from that index
b.pop(2)->remove no. from index 2
To convert lower into uppercase and uppercase into lowwr
in a string use list_name= list_name.swapcase()
sorted(l): to sort a list,tuple,set
One of the built-in functions of Python is divmod,
which takes two arguments and and returns a
tuple containing the quotient of first and then the
remainder .
Tuples
It is also a collection of data sets but you cannot
change(i.e. cannot use remove or append function)
Declaration of Tuples : use parenthesis ( )
Ex : a= (1,5.5 , 6,7, 8, “A”)
They are also called as Immutable(cannot change).
Length of tuple :
Ex : a= (3,1,6,4,8,’A’,65.2)
print(a) -> (3,1,6,4,8,’A’,65.2)
print(len(a)) -> 7
Slicing : if we start from left than indexing starts
from 0 and if we start from right indexing starts from
-1 : [start : end : step] (by default step is 1 )
Ex : a= (3,1,6,4,8,’A’,65.2)
print(a) -> (3,1,6,4,8,’A’,65.2)
print(a[0:3]) -> (3,1,6)
print(a[ :-2]) -> (3,1,6,4,8)
print(a[4:6]) -> (8,’A’)
print(a[0:3:2]) -> (3, 6)
print(a[-2:1:-1]) -> ('A', 8, 4, 6)
print(a[-2:-7:-1]) -> ('A', 8, 4, 6, 1)
DICTIONARIES
To initialize we use curly braces { }
They are mutable
Can use multiple data type
A={“Meena” : “Maggi”} -> always left side term(here
Meena) termed as key and right side(here Maggi ) is
termed as value/element.
Dictionary inside Dictionary example
dic1={"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
print(dic1)
print(dic1["Two"]) # Accessing Element using key
print(dic1["Three"]["A"])
Output
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
Tuesday
Wednesday
Adding Element or key to Dictionary
Ex : dic1[“Five”] = “Saturday”
print(dict1)
Output :
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday",”
Five”:”Saturday”}
Deleting The element and key (use del() function)
Ex:
del(dic1[“Five”])
print(dic1)
Output :
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
Update and key Function
To update the value for a particular key
Ex :
dic1.update({“One”: “Holiday”})
print(dic1)
Output :
{"One":”Holiday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
To Access keys of dictionary
Ex : print(dic1.keys())
Output: dict_keys(['One', 'Two', 'Three', 'Four'])
If else Condition
Used for displaying or performing some calculation
depending upon Condition
Syntax :
a=1
b=2
if a<b:
print(“ ”)
else :
print(“ ”)
Find greatest among two
num1 = int(input("Enter first number : "))
num2 = int(input("Enter second number : "))
if num1<num2:
print(num2,"is greater than",num1)
else:
print(num1,"is greater than",num2)
If two numbers have same value (elif ->when more
than 2 conditions)
num1 = int(input("Enter first number : "))
num2 = int(input("Enter second number : "))
if num1<num2:
print(num2,"is greater than",num1)
elif num1==num2:
print(num2,"is equal to",num1)
else:
print(num1,"is greater than",num2)
Greatest among Three
n1 = int(input("Enter first number : "))
n2 = int(input("Enter second number : "))
n3 = int(input("enter third number : "))
if n1>=n2 and n1>=n3:
print(n1,"is greatest ")
elif n2>=n1 and n2>=n3:
print(n2,"is greatest")
else:
print(n3,"is greatest")
Output: Enter first number : 1
Enter second number : 2
enter third number : 1
2 is greatest
for-Loop
Syntax :
for i in range(5) :
Ex : i=0 #not required
for i in range(2,5):
print(i)
Output :
2
3
4
for loop are used when we want to repeat
statements
Accessing Nested list using for loop
list_1 = [["A",2],["B",1],["C",3]]
print(list_1)
for item,chocolates in list_1:
print(item,chocolates)
Output :
[['A', 2], ['B', 1], ['C', 3]]
A2
B1
C3
while – loop
used when we want to print number up to a
particular position
Printing Numbers from 1 to 50 given condition to be
used is variable<50
a=0
while(a<50):
print("Number :",a+1)
a=a+1
Alternate
a=0
while(a<50):
a=a+1
print("Number :",a)
To print numbers from 5 to 30
a=5
while(a<=30 ):
print("Number :",a)
a=a+1
Functions and Docstrings
Function Types :
built-in function : Pre defined functions, which
are already defined. Ex : len, del, append, etc.
Example:
a = int(input("Enter the first number : "))
b = int(input("Enter the second number : "))
c = sum((a,b))# function calling
print(a,"+",b,"=",c)
user-defined: which are made by user
def is used to define/declare a function
Types : with parameters and without
Parameters
Without parameters
def one(): #function declaration
print("I am learning Python Programming")
one() #function calling
With Parameters
def area(r): #function declaration
print("Area of Circle =",3.14*r*r)
r=int(input("Enter the radius of Circle : "))
area(r) #function Calling
Docstrings:
Always written inside function
Give idea what the function is doing
to print docstring it should always be written
outside function
“ “ “ ” ” ”->used to represent Docstrings
Example:
def area(r): #function declaration
"""This Function computes area of circle """
a= 3.14 * r * r
print("Area of Circle =",a)
r=int(input("Enter the radius of Circle : "))
area(r) #function Calling
print(area.__doc__)# printing docstring
Output:
Enter the radius of Circle : 2
12.56
This Function computes area of a circle
f-strings /Literal strings /Interpolation
let we have a variable which stored either
char/int/string/float data and to print that thing in
output f-strings are used
Ex –
a= "Python programming"
print(f"I am learning {a}")
format()
It is used for string formatting
Ex-
Output:
# using format option in a simple string
print("{}, A computer science portal for geeks."
.format("GeeksforGeeks"))
# using format option for a
# value stored in a variable
str = "This article is written in {}"
print(str.format("Python"))
# formatting a string using a numeric constant
print("Hello, I am {} years old !".format(18))
GeeksforGeeks, A computer science portal for geeks.
This article is written in Python
Hello, I am 18 years old !
Main function
Syntax : if __main__ == '__main':
To import one file function to another file we use
import
mainfile.py
def addition(a,b):
sum=a+b
print(sum)
addition(2,4)
def multiplication(a,b):
product = a*b
print(product)
multiplication(3,5)
final.py
import mainfile
print(mainfile.addition(9,2))
Output(on running final.py file):
6
15
11
None
! Output is given for all files (mainfile.py and final.py)
but we want output for only final.py
For solving this problem we need to use main
function
mainfile.py
def addition(a,b):
sum=a+b
print(sum)
def multiplication(a,b):
product = a*b
print(product)
if __name__ == ‘__main__’:
addition(2,4)
multiplication(3,5)
#do calling from main function
final.py
import mainfile
print(mainfile.addition(9,2))
Output :
11
None
File Handling
We have a text file from c /d drive or
In particular idle we are using by using file handling
we can read ,write the text file
Modes of file
“r” - open file for reading –default mode
“w” – open file for writing
“x” – creates file if not exists
“a” – add more content to a file
“t” – text mode – default mode
“b” – binary mode
“+” – read and write
Classes and Objects
Python is a multi-paradigm programming language. It
supports different programming approaches.
One of the popular approaches to solve a
programming problem is by creating objects. This is
known as Object-Oriented Programming(OOP)
An object has 2 characteristics :
Attributes
Behavior
The concept of oops in Python Focuses on creating
reusable code/ DRY(Don’t Repeat Yourself)
A class is a blueprint for the object / user defined
data-type
Ex
class student :
pass
one = student() # one is the object to type class
two = student()
one.name = "Riya"
one.standarad = "10"
one.section = "a"
two.name = "Meera"
two.standard = "10"
two.section = "B"
two.subjects =["English","computer","science"]
print(one.name,"\n",two.subjects[0],"\
n",two.subjects)
Output :
Riya
English
['English', 'computer', 'science']
Class Variables : variables declared inside a class
can be accessed by either name of class or by objects
Example :
class Student:
no_of_subjects = 5
pass
one = Student()
two = Student()
one.name = "a"
one.standard = "11"
one.section = "C"
two.name = "B"
two.standard = "12"
two.section = "D"
print(Student.no_of_subjects) #accesssing class
Variables
print(one.no_of_subjects)
Output :
5
5
Self and init
Giving arguments to a class is known as constructor
Whenever we use init self is automatically passed into
init
Example:
class s:
no_of_subjects = 5
def __init__(self,aname,astandard,asection):
self.name = aname
self.standard = astandard
self.section = asection
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
one = s("Riya","10","A")
two = s("seema","11","B")
print(one.details())
Output:
Name of the student is Riya, standard is 10 and
section is A
classmethod can be access from any instance(object)
or any class
If we want to make a method that can be accessed by
instance as well as class and the argument which we
pass and we don’t want to take self then we used
classmethod
Example:
class s:
no_of_subjects = 5
def __init__(self,aname,astandard,asection):
self.name = aname
self.standard = astandard
self.section = asection
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
#declaring class method ,since class method so
default argument cls
@classmethod
def change_subject(cls,leaves):
cls.no_of_subjects = leaves
one = s("Riya","10","A")
two = s("seema","11","B")
s.change_subject(21)
print(one.no_of_subjects)
Output:21
Static methods, much like class methods, are
methods that are bound to a class rather than its
object. They do not require a class instance creation.
Example –
class s:
no_of_subjects = 5
def __init__(self,aname,astandard,asection):
self.name = aname
self.standard = astandard
self.section = asection
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
#declaring class method ,since class method so
default argument cls
@classmethod
def change_subject(cls,leaves):
cls.no_of_subjects = leaves
@staticmethod
def ptr_detail(string):
print("My name is "+string)
s.ptr_detail("Nikita Gupta")
one = s("Riya","10","A")
one.ptr_detail("Riya") 3staic members can be
accessed by objects but also without them
Output :
My name is Nikita Gupta
My name is Riya
Inheritance
Single Inheritance : Inheriting a class from a single
class
Example:
class One:
def func1(self):
print("this is the one class")
class Two(One):
def func2(self):
print("this is the two class")
obj=Two()
obj.func1()
obj.func2()
Output:
this is the one class
this is the two class
Multiple Inheritance: Inheriting more than one class
into a class
Example:
class plant:
def type(self):
print("t am a small plant")
def my(self):
print("I am Plant")
def m(self):
print("P")
class flower:
def kind(self):
print("i am a sunflower")
def my(self):
print("I am flower")
def m(self):
print("F")
class Purchaser(plant,flower):
def buy(self):
print("I will buy flower as well as plant")
def my(self):
print("I am Purchaser")
obj = Purchaser()
obj.type()
obj.kind()
obj.buy()
obj.my() # Purchaser actual function will be
called
obj.m() #Purchser inherited function from class
plant is called because it is inherited first
Output:
I am a small plant
i am a sunflower
I will buy flower as well as plant
I am Purchaser
P
Multilevel inheritance:
Example :
class Mother:
exercise = 2
class Daughter(Mother):
badminton = 3
def isbadminton(self):
print(f"She plays badminton {self.badminton}")
class GrandDaughter(Daughter): #containing features
of both mother class and daughter class
badminton=1
def isbadminton(self):
print(f"she plays badminton {self.badminton}")
riya = Mother()
priya = Daughter()
seema = GrandDaughter()
print(seema.isbadminton())
TOP PYTHON MACHINE LEARNING LIBRARIES
https://kandi.openweaver.com/collections/artificial-intelligence/
python-machine-learning?
landingpage=python&utm_campaign=paid_search_python&utm_m
edium=cpc&utm_source=google&utm_term=python_colmachinelea
rning&utm_content=collection&gclid=CjwKCAiAo4OQBhBBEiwA5K
Wu_8sDg8VmHzCJTzz0bckOpabZ7XJTSZ25Mty0GynvOuXzTAhkdCKA
eRoCUOMQAvD_BwE
Tinkter:
https://www.tutorialspoint.com/python/python_gui_programming.
htm#:~:text=Tkinter%20is%20the%20standard%20GUI,to%20the
%20Tk%20GUI%20toolkit.&text=Import%20the%20Tkinter
%20module.
divmod(dividend,divisor): return a tuple containg quotient and
remainder
bool(self,/): Return self !=0
floordiv(self, value, /): Return self//value.
eq(self, value, /): Return self==value.
Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length, byteorder, *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
Complex Numbers in Python
C=A+bj
c.imag():- gives imaginary part of c
the as_integer_ratio() method of float objects returns a numerator and
a denominator in the form of a tuple:
x = 0.125
x.as_integer_ratio()
Output:
(1, 8)
bit_length() method of builtins.int instance
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
Numpy Library
It is mainly used for doing mathematical calculation
Why array is preferred over list?
Similarities: Both store data, both are mutable, can be
indexed, slicing operation
Differences: they have different data types(in array we can
take elements of only one data type but not in same case for
list)
Advantages of array over list: occupy less memory than list,
Fast, convenient to use
Types of arrays : array is collection of elements of same type
2 ways to create an array : using array module, using
numpy library
1D array : [1,2,3,4,5,6]
2D array : [[1,2],[3,4]] -> 1 2
3 4
Declration of array :
Example :
import numpy as np
a =np.array([1,2,3,4,5]) #1D array
print(a)
b = np.array([[1,2],[3,4]]) #2D array
print(b)
To change array to complex form :
Example:
c = np.array([7,8,9,6],"complex")
print(c)
Output:
[7.+0.j 8.+0.j 9.+0.j 6.+0.j]
Numpy arange() is one of the array creation routines based
on numerical ranges. It creates an instance of ndarray with
evenly spaced values and returns the reference to it.
In Python, a string of text can be aligned left, right and center.
.ljust(width)
This method returns a left aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------
.center(width)
This method returns a centered string of length width.
>>> width = 20
>>> print 'HackerRank'.center(width,'-')
-----HackerRank-----
.rjust(width)
This method returns a right aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.rjust(width,'-')
----------HackerRank
Ex:
N, M = map(int, input().split())
for i in range(1, N, 2):
print(str('.|.' * i).center(M, '-'))
print('WELCOME'.center(M, '-'))
for i in range(N-2, -1, -2):
print(str('.|.' * i).center(M, '-'))
QGiven an integer, , print the following values for each integer from to :
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
Function Description
Complete the print_formatted function in the editor below.
print_formatted has the following parameters:
int number: the maximum value to print
Prints
The four values must be printed on a single line in the order specified above for
each from to . Each value should be space-padded to match the width of
the binary value of and the values should be separated by a single space.
Input Format
A single integer denoting .
Constraints
Sample Input
17
Sample Output
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001
def print_formatted(number):
# your code goes here
l1=len(bin(number)[2:])
for i in range(1,number+1):
print(str(i).rjust(l1,' '),end=" ")
print((oct(i)[2:]).rjust(l1,' '),end=" ")
print(((hex(i)[2:]).upper()).rjust(l1,' '),end=" ")
print((bin(i)[2:]).rjust(l1,' '))
if __name__ == '__main__':
Incrementing Character by 1:
temp=’c’
temp=chr(ord(temp)+1)
String to list:
Temp=s.split(“ “)
List to string:
s=” “.join(map(str,temp))
capitailze first letter of each item in list:
temp=list(s.split())
for i in range(len(temp)):
temp[i] = temp[i].capitalize()
capitalize first letter of each word in list:
temp=list(s.split())
for i in range(len(temp)):
temp[i] = temp[i].title()
add(element):- used to add elements to a set
Set Operations
symmetric_difference()
The .symmetric_difference() operator returns a set with all the elements that are
in the set and the iterable but not both.
Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it
only operates on the set of elements in set.
The set is immutable to the .symmetric_difference() operation (or ^ operation).
.intersection()
The .intersection() operator returns the intersection of a set and the set of
elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it
only operates on the set of elements in set.
The set is immutable to the .intersection() operation (or & operation).
.difference()
The tool .difference() returns a set with all the elements from the set that are not
in an iterable.
Sometimes the - operator is used in place of the .difference() tool, but it only
operates on the set of elements in set.
Set is immutable to the .difference() operation (or the - operation).
union(): The .union() operator returns the union of a set and the set of elements
in an iterable.
Sometimes, the | operator is used in place of .union() operator, but it operates
only on the set of elements in set.
Set is immutable to the .union() operation (or | operation).
Itertools.product()
This tool computes the cartesian product of input iterables. It is equivalent to
nested for-loops.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
Example: from itertools import product
>>> print list(product([1,2,3],repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>> print list(product([1,2,3],[3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>> A = [[1,2,3],[3,4,5]]
>>> print list(product(*A))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
Itertools.permutations(iterable[,r])
This tool returns successive length permutations of elements in an iterable.
If is not specified or is None, then defaults to the length of the iterable, and all possible full length permutations are
generated.
Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be
produced in a sorted order.
Ex:
from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>>
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
Itertools.combination(iterable,r)
This tool returns the length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is
sorted, the combination tuples will be produced in sorted order.
Example:
from itertools import combinations
>>> print list(combinations('12345',2))
[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4',
'5')]
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,4))
[(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)]
Itertools.combinations_with_replacement(iterable,r):
This tool returns r length subsequences of elements from the input iterable
allowing individual elements to be repeated more than once. Combinations are
emitted in lexicographic sorted order. So, if the input iterable is sorted, the
combination tuples will be produced in sorted order.
To delete the list:
List1.clear()
List1*=0
del list1=[:]
these three all have same time complexity but list1= [] this has the maximum time
complexity so don’t use it.
Python allows to create files, read from files, write content to file and append content to existing content
through inbuilt functions!
Method Description
This method is used to open the file for the specified operation. The
open(file_path,operation)
operation can either be r,w,a for read, write and append.
close() This method is used to close a file which is already open.
This method is used to write a string to a file, if file is present. If not,
write()
it creates the file and writes the string into it.
read() This method is used to read all the contents of a file into a string.
Error Handling in python
try:
flight_file=open("flight.txt","r")
text=flight_file.read()
print(text)
flight_file.write(",Good Morning")
flight_file.close()
except:
print("Error occurred")
if flight_file.closed:
print("File is closed")
else:
print("File is open")
When we want to write a code that will run in all situations, we can put it in a finally block.
Since closing a file is necessary we can do it in the finally block instead of in the try block.