PYTHON PROGRAMMING
UNIT -1
computing: problems solved by computer ex: -decision, counting,
search, sorting, optimization
1 BYTE =8 BITS
Analysis-understanding, design-describing data, implementation-
code, testing
algorithm: deterministic, unambiguous instruction for solving a
problem
o practice writing algorithm for MCGW and others
easy to learn,versatile,extensive libraries and
frameworks,community support,cross-platform
representation: capture all relevant aspects
brute force: trying all possible solutions
number system: binary, octal, decimal, hexadecimal
syntax: the set of rules followed, arrangement, spelling is correct
semantics: spelling incorrect
compiler: to code at once
interpreter: to code line by line
python is hybrid of both
paradigms: imperative, structured prog, procedural, declarative,
functional, logical, object-oriented
interactive mode, batch modes
print(x,sep='',end='')
print(f’c={x}’)# to replace print(‘c’,x)
identifiers: name for a programme
keywords: predefined meaning
variables: identifiers associated with a value(only starts with _ or
alphabet)
characters and spaces are not allowed
variable can’t be a keyword
\n means newline
id function
indentation: no. of spaces
literals: constants which they don't change forever
o numeric, string
data types: int, float, string, etc…
o scalar,reference
input(): originally takes string so mention int,float etc…
concatenation: adding but not mathematical
eval(input()): it is to not use int, float and all
expression: combination of operators and operands
single line comment: # ; multiline comment: ‘’’ ‘’’/””” ”””
arity/rank:
o unary: -5,~6
o binary: 5+6, 7(operand1)-5(op2)
operators:
o arithmetic:
+, -, * , /, //(truncated division gives int), %
(reminder),**(exponent)
o Relational:
<, <= , > , >= ,== ,!=(not equal) Boolean
answer(True/False(starts with a capital))
Cascading means 3 operands with relational op
o Logical: works on Boolean values
Lazy eval: whatever is first operand gives that
expression is that
Lazy eval for false is for AND
Lazy eval for true is for OR
And, or , not
o Bitwise :
& - and
| - or
^ - excusive or (only one of the bit is 1)
<< ([Link] bits shifted) - left shift
>> - right shift
~ - one’s complement(~x=-(x+1))
o Membership :
in , not in
o identity:
is , is not
o assignment:
=
o Shorthand:
+= , -= , *= ,/= ,//= ,%= ,**=
a+=b means a=a+b
operator polymorphism: behaves diff based on operands
o + addition for integrals, concatenation for strings
o * multiplication, repetition
o True 1 , non empty things
o False 0, empty set/lists/tuples
Precedence :
o **, unary , *, / ,//, %, binary
o If more than one have same precedence then we take
associative of op
o ** is taken from right to left
o Others are left to right
o Parentheses is best to take a order
help(): to know about the details
type(): to know which data type
control structures:
o sequential
o selection/branching/conditional: if-elif-else
o iterative/repetitive: for , while loops(definite,indefinite)
leader:
<suite>
example of if-elif-else:
Example of for:
o Iterables (in , not in )
Example for while:
o in , not in, relational operators
range(start, stop(not included),step)
o lazy function , returns iterables(that can be looped)
UNIT-2
Data structures:
o Plotting graphs, statistics , media players etc…
o Collection based:
Generic: list,tuple
Specific data: stack , queue
o Data based:
Sequence
in , not in
index
rational operators
len(),max(),min(),count(),index()
Non sequence
Except index
LISTS[]:
o Non-permitive linear data structure
o Indexable
o Mutable
o Iterable
o Index are 0, 1,2/-3,-2,-1
o len(),max(),min(),sum()
o +,*,in, not in ,slicing[start:stop:index step],index[]
dir(): for displaying all built in functions
Built in functions: list() to change it to a list
o [Link]()inserting 1 element at the end
o [Link]()inserting more than one by iterating
Ex: ‘pes’ is appended as ‘p’,’e’,’s’
o [Link](index,object)
o [Link](index): removes and returns the value
If index not given it will remove last one
Raises index error
o [Link](value):removes first occurrence of the value
Gives valueerror
o [Link](value): returns the index of the value
o [Link](value): returns [Link] occurrence
o [Link](): sorts it in ascending order according to ASSKEY value
It changes the original list
It doesn’t work for different datatypes
o [Link](): reverse order
o [Link](): returns copy with different id()
o [Link](): removes everything
Where as ASSIGNMENT gives the same id()
o sorted(L)=will just show and doesn’t change the original list
TUPLE(): tuple() to change something to a tuple
o Non permitive linear d.s
o Collection of values (UNMODIFIED)
o Empty tuple=()
o Singlet=(1,)
o Immutable
o Indexable
o Iterable
o len(),max(),min(),sum()
o operators same as list
o [Link](): occurrence
o *t for unpacking
o For swapping: (a,b)=(b,a)
DICTIONARIES{}:dict()dictionary constuctor
o Non-permitive, non linear(unordered for old version)
o Ordered for new version
o d={keys:values}
o d[keys]=values(to add)
o non indexable
o can extract using keys
o mutable but keys are not
o keys are unique,if not LAST occurrence is taken
o iterable
HASHABLE: never changing it’s value (data types,immutables)
UN HASHABLE: (mutables)
o len(),max()keys,min(),sum(),sorted()doesn’t change the og
o [Link]()=gives list of keys
o [Link]()=list of values
o [Link]()=list tuple of keys and values(items)
o [Link]({key:value})=updates the current
o d,pop(key)=returns value and removes the item
o [Link]():removes last item and returns tuple of item
o [Link](key)=>value
o [Link]()=creats new dictionary
o [Link](key,value)=if key is present value won’t change if
not it updates it
o [Link]()=clears everything
SETS-set()(for null set):{1,2}
o Non indexable,unique elements
o Immutable
o Non indexable
o Mutable
o Iterable
o len(),max(),min(),sum()
o bit wise , rational ,membership
o [Link]()=to add 1 element
o [Link]()=add more than 1 element(iterables)
o [Link]()=removes and if not present gives’error’
o [Link]()=removes and if not present DOESN’T give error
o [Link]()=removes random elements
o [Link]()=clears all
o all(s) it will iterate trough everything and gives boolean
o [Link](s2)=does’t update it just shows in the terminal=all
o [Link](s2)=both
o [Link](s2)=only s1
o s1.symmetric_difference(s2)=only s1 or only s2
o s1.intersection_update(s2)=now it updats set s1
o except for union we can use update for others
o CONCATINATION: |=
STRINGS=str():
o Indexable
o Immutable
o Iterable
o ‘’ ,””,’’’ ‘’’,””” “””
o +, * , in , not in , relational , slicing
o These functions don’t change the original str unless you
assign it
o [Link]() = only 1 st letter
o [Link]() = all first letters of each word
o [Link]() = all letters are turned to upper case
o [Link]() = all letters are turned to lower case
o [Link]() = cases are swaped
o [Link]() /[Link]() = returns boolean answer
o [Link]() = checks if all are digits
o [Link]() = checks if all are alphabets
o [Link]() = if both exist
o [Link](any char) = remove that character if it is out side the
string
[Link]() = strip on left side
[Link]() = strip on right side
o [Link]() = removes that character in side, split there and
returns a list
o [Link]() = splits at enter
o [Link](any str,until index): it will adjust the string on the left
and adds on the right
[Link]()
[Link]()
o [Link](a,b,count)
o [Link]() like rjust
o [Link](str,start,end)first occurence
o [Link]() last occurence
o [Link](any list and all) = its like a sep for that
S1={‘1’,’2’}
‘abc’.join(S1) = ‘1abc2’
o [Link](start index: stop : step) : T/F
o [Link](): T/F
FILES:
Interactive mode
Command line arguments
Usage of files
o First file should be saved in the same path
o r = read: w= write
o f= open(‘file_name’,’r’(if not given it is read) )
[Link]() prints everything from the file
[Link]() prints line by line
[Link]() list of every line with \n at the end
use strip to remove the \n
o f=open(‘file_name’,’w’)
writes things in a non-existing file
[Link](str)= writs the string in the file and doen’t return
anything
o at last [Link]()
OR
o with open(‘file’,’r’):
for this no need to close
CSV(comma-separated values) FILES:
o Import csv
o With open(‘[Link]’) as file:
[Link](file) = reads line by line and separated by ,
(list)
[Link](file)= writes line by line
[Link]()
[Link]()
FUNCTIONS:
o def function_name():
o function_name() #to call ,it prints it
value returning funtions
non-value returning functions
global variables: if it is outside all the functions
local variables: if it is accessible only for one function
ARGUMENTS:
o Positional arguments:
o Keyword arguments