id
int64
0
25.6k
text
stringlengths
0
4.59k
25,500
unit-ivfile handling filestypes of filescreating and reading text datafile methods to read and write datareading and writing binary filesthe pickle modulereading and writing csv filespython os and os path modules filesa file is location on disk that stores related information and has name there are different kinds of file such as music filesvideo filestext files python gives easy ways to manipulate these files generally we divide files in two categoriestext file and binary file text files are simple text where as the binary files contain binary data which is only readable by computer file input/output operations open file close file read file write file creating and reading of text datato read and write to text file ,we must open it )opening filesyntaxfilepointer=open(filename,modefilename can be text file with extensiontxtmodes"rread opens file for readingerror if the file does not exist "aappend opens file for appending "wwrite opens file for writing/overwriting "xcreate creates the specified filereturns an error if the file exists exf=open("demo txt",' ' =open("demo txt",' ' =open("demo txt",' ' )close filesyntaxfilepointer close(exf=open('demo txt',' 'bv prasanthi,dept of cse page
25,501
print( read() close( )read text file:read(method is used for reading the content in the file #creating demo txt file gedit demo txt python is interesting programming language #write python program to read data in demo txt =open('demo txt',' 'print( read() close(#read only part of filef=open('demo txt',' 'print( read( )#returns first three characters close(#readlinesf=open('demo txt',' 'print( readline()#read only first line close(read all lines at timef=open('demo txt',' 'print( readlines() close( )write filethe write(method is used to write data to empty file or existing file it has two modes"wwrite opens file for writing data into empty file (or)overwriting the data in the existing file "aappend opens file for appending the data at end of the file syntaxfilepointer write('write the data which need to append or overwrite'exgedit empty txt creation of empty file #write program to write data into empty file =open('empty txt',' ' write(" am writing data into the empty text file" close(bv prasanthi,dept of cse page
25,502
#to view the content in the empty txt =open('empty txt',' 'print( read() close(outputi am writing data into the empty text file #write program to write data into existing file demo txt =open("demo txt",' ' write(" am overwriting the existing content" close(#to view the content in the demo txt =open("demo txt",' 'print( read()outputi am overwriting the existing content write program to append data in empty txt =open("empty txt",' ' write("python is very easy" close(#to view the content in the empty txt =open("empty txt",' 'print( read()outputi am writing data into the empty text file python is very easy methods() )tell():returns current file location syntaxfilepointer tell(egf=open('demo txt',' 'print( read()print( tell()print( read( ) close( )seek()changes the filepointer position to offset bytes syntax:filepointer seek(offset,from(optional)egfseek( #filepointer moves by position fseek( , #moving filepointer by position from begin of file fseek( , #moving filepointer by position from current position seek( , #moving filepointer by position from end of file )read( )readline(bv prasanthi,dept of cse page
25,503
reading and writing of binary filesopening filefilepointer=open(filename,modefilename with extensionbinmodes"rbread opens binary file for reading "wbwrite opens binary file for writing /overwriting egf=open('demo bin','rb'#creating demo bin file gedit demo bin #write python program to read the data in demo bin file =open('demo bin','rb'print( read() close(creating empty bin file gedit empty bin write python program to write the data into empty bin =open('empty bin','wb' =[ , , =bytearray(lf write( close(#to view the contents in empty bin =open('empty bin','rb'print( read() close(#to overwrite the content in existing file demo bin =open('demo bin','wb' =[ , , =bytearray(lf write( bv prasanthi,dept of cse page
25,504
close(#to view the contents in demo bin =open('demo bin','rb'print( read() close(csv (comma separated valuefiles csv (comma-separated valuesis file containing text that is separated with comma,it is type of plain text that uses specific structuring to arrange tabular data csv files are used to handle large amount of data eg:spreadsheets syntaxcol col col first row data first row data first row data second row data second row data second row data reading and writing of csv files#create demo csv file gedit demo csv sn,rollno,name , ,ayaan , ,riyaan #write python program to read the data in demo csv import csv with open('demo csv'' 'as filereader csv reader(filefor row in readerprint(row#output['sn','rollno','name'[' ' ','ayaan'[' ',' ','riyaan'#creating empty csv file gedit empty csv #write the data into empty csv file import csv with open ("empty csv"," "as filef=csv writer(filef writerow([' no','rollno','name']bv prasanthi,dept of cse page
25,505
writerow([ , ,'aaa'] writerow([ , ,'bbb']#write the data into demo csv file import csv with open ("demo csv"," "as filef=csv writer(filef writerow([' no','rollno','name'] writerow([ , ,'aaa'] writerow([ , ,'bbb']the pickle module python pickle module is used for serializing and de-serializing python object structure any object in python can be pickled so that it can be saved on disk what pickle does is that it "serializesthe object first before writing it to file pickling is way to convert python object (listdictetc into character stream the idea is that this character stream contains all the information necessary to reconstruct the object in another python script import pickle int(input('enter the number of data ') [for in range( ) input('enter data '+str( )+' append(afile open('demo bin''wb'pickle dump(lfilefile close(outputenter the number of data enter data python enter data is enter data interesting python pickle load to retrieve pickled data,we have to use pickle load(import pickle file open('demo bin''rb' pickle load(filefile close(print('showing the pickled data:' = bv prasanthi,dept of cse page
25,506
for in lprint('the data 'cis 'ic = outputshowing the pickled datathe data is the data is the data is note:for clear explanation refer to python os and os path modules it is possible to automatically perform many operating system tasks the os module in python provides functions for creating and removing directory (folder)fetching its contentschanging and identifying the current directoryetc we first need to import the os module to interact with the underlying operating system soimport it using the import os statement before using its functions )getting current working directory the getcwd(function used to print the current working directory control+alt+ : terminal is opened and type python import os os getcwd(output/tmp/guest-iwwxnr creating directory we can create new directory using the os mkdir(functionas shown below import os os mkdir("shanthi"output: directory named shanthi will be created on the desktop list files and sub-directories the listdir(function returns the list of all files and directories in the specified directory now create the files named file and file in the directory shanthi import os os listdir("shanthi"output:['file ','file ' removing directory the rmdir(function in the os module removes the specified directory import os bv prasanthi,dept of cse page
25,507
os rmdir("shanthi"output:shanthi directory on the desktop will be removed os path module in python this module contains some useful functions on pathnames os path basename(paththis function basically return the file name from the path given import os os path basename("shanthi/file "print(loutputfile os path dirname(pathit is used to return the directory name from the path given import os os path dirname("shanthi/file "print(loutput:shanthi os path isdir(paththis function specifies whether the path is existing directory or not import os os path isdir("shanthi/file "print(loutput:true os path isfile(paththis function specifies whether the path is existing file or not import os os path isfile("shanthi/file "print(loutput:true bv prasanthi,dept of cse page
25,508
uniti the information in main memory can be displayed through an output device inputis the process of entering data and instructions into the computer various input devices used are keyboardmousescannertrackball etc storageis the process of storing data and instructions in the computer computer has two types of storage areas the architecture or structure of computer is as shown below primary storage is also known as main memory directly accessible to the cpu at very fast speed used to store dataprogramsintermediate and final results very expensive therefore limited in capacity volatile as soon as computer is switched offthe information stored in it gets erased secondary storagealso known as secondary memory or auxiliary memory it is cheapernon-volatile and used to permanently store data and programs department of csevishnu institute of technology
25,509
uniti processingthe process of performing operations on the data as per the instructions specified by the user (programmain aim of this is to transform data into information data and instructions are taken from the primary memory and are transferred to the arithmetic and logic unitwhich performs all sorts of calculations when the processing completesthe final result is transferred to the main memory outputis the process of giving the result of data processing to the outside world various output devices are monitorprinter etc controlling the function of managingcoordinatingand controlling all the components of the computer system is handled by the control unit the control unit decides the manner in which the instructions will be executed and the operations will be performed computer hardware the essential hardware components of computer are cpu (central processing unit memory / (input/outputdevices central processing unitcoordinates all computer operations performs arithmetic and logical operations on data cpu follows the instructions contained in computer program to determine which operations should be carried out and in what order the cpu can perform arithmetic operations such as additionsubtractionmultiplication and division the cpu can also compare the contents of two memory cells and make decisions based on the results of that comparison the circuitry of modern cpu is housed in single integrated circuit or chip an ic that is full cpu is called microprocessor cpu contains special high speed memory locations called registers control unit(cu)it is responsible for controlling the transfer of data and instructions among other units of computer it manages and coordinates all the units of the computer department of csevishnu institute of technology
25,510
uniti it communicates with input/output devices for transfer of data or results from storage it does not process or store data arithmetic logical unit(alu)it performs arithmetic operations like additionsubtractionmultiplicationand division it performs logic operations such as comparingselectingmatchingand merging of data examples of logic operations are comparisons of values such as notandand or memorymemory is an essential component in any computer memory cell is an individual storage location in memory address of memory cell is the relative position of memory cell in the computers main memory the data stored in the memory cell are called contents of the cell the ability to store programs as well as data is called stored program concept program' instructions must be stored in main memory before they can be executed memory cell is actually grouping of smaller units called bytes byte is the amount of storage required to store single character byte is even composed of smaller units of storage called bit bit refers binary digit binary refers to number system based on two numbers and therefore bit is either or there are eight bits in byte main memorystores programsdata and results random access memory(ramramo offers temporary storage of programs and data while the programs are temporarily being executed by the computer ram is usually volatile memorywhich means that everything in ram will be lost when the computer is switched off accessible to the programmer department of csevishnu institute of technology
25,511
uniti secondary memory read-only memory (romromo stores information permanently in the computer its name is read-onlybecause computer can read but cannot write information in rom rom is non-volatile data stored in rom do not disappear when the computer is switched off secondary storage devices these devices are needed for the following reasons computers need permanent semi permanent storageso that information can be retained during power-loss or when the computer is turned off systems typically store more information than will fit in memory some of the most frequently used secondary storage devices compact diskmagnetic tapefloppy diskhard diskzip diskdigital video disk input output devicesinput output devices are used to communicate with the computer they allow us to enter data for computation and to observe the results of that computation department of csevishnu institute of technology
25,512
uniti principle of abstractionabstraction is the process of trying to identify the most important or inherent qualities of an object or modeland ignoring or omitting the unimportant aspects (information hidingit consists of two partsdata and operations memory hierarchy memory hierarchy is the hierarchy of memory and storage devices found in computer system it ranges from the slowest but high capacity auxiliary memory to the fastest but low capacity cache memory needthere is trade-off among the three key characteristics of memory namely department of csevishnu institute of technology
25,513
uniti cost capacity access time level- at level- registers are present which are contained inside the cpu since they are present inside the cputhey have least access time they are most expensive and therefore smallest in size (in kbregisters are implemented using flip-flops level- at level- cache memory is present it stores the segments of program that are frequently accessed by the processor it is expensive and therefore smaller in size (in mbcache memory is implemented using static ram level- at level- main memory is present it can communicate directly with the cpu and with auxiliary memory devices through an / processor it is less expensive than cache memory and therefore larger in size (in few gbmain memory is implemented using dynamic ram level- at level- secondary storage devices like magnetic disk are present they are used as back up storage they are cheaper than main memory and therefore much larger in size (in few tblevel- at level- tertiary storage devices like magnetic tape are present they are used to store removable files they are cheapest and largest in size ( - tbobservationsthe following observations can be made when going down in the memory hierarchy department of csevishnu institute of technology
25,514
uniti cost bit decreases frequency of access decreases capacity increases access time increases units of storage in computer computers are electronic machines which operate using binary logic these devices use two different values ( and to represent data this corresponding number system is referred as binary number system differences between binary and decimal number systems decimal binary base digits to bit is the smallest unit of information that can be stored or manipulated on computerit consists of either zero or one we can also call bit binary digit single bit can store two different values (either or nibble is group of four bits byte is group of eight bits byte is simply fixed-length sequence of bits modern computers organize data into bytes to increase the data processing efficiency of network equipmentdisks and memory computers by convention set one byte to equal eight ( bits byte can store or different values word is group of bits department of csevishnu institute of technology
25,515
uniti besides bytesdata is also specified using the units shown in the table circuits and logicthe basic digital electronic circuit that has one or more inputs and single output is known as logic gate logic gates are divided into three types they are basic gates:not,and,or universal gates :nand,nor arithmetic gates:exor,exnor not gatethe simplest gate is the not gatealso known as an inverter it accepts single input and outputs the opposite value if the input is the output is if the input is the output is department of csevishnu institute of technology
25,516
uniti truth table for not and gateif both inputs are ' 'then only the outputy is ' for remaining combinations of inputsthe outputy is ' it is optional to represent the logical and with the symbol the following figure shows the symbol of an and gatewhich is having two inputs ab and one outputy the following table shows the truth table of -input and gate = or gatethis logical or is represented with the symbol '+if both inputs are ' 'then only the outputy is ' for remaining combinations of inputsthe outputy is ' department of csevishnu institute of technology
25,517
uniti the following figure shows the symbol of an or gatewhich is having two inputs ab and one outputy the following table shows the truth table of -input or gate = + universal gates nand nor gates are called as universal gates because we can implement any boolean functionwhich is in sum of products form by using nand gates alone similarlywe can implement any boolean functionwhich is in product of sums form by using nor gates alone nand gate nand gate is digital circuit that has two or more inputs and produces an outputwhich is the inversion of logical and of all those inputs the following image shows the symbol of nand gatewhich is having two inputs ab and one outputy the following table shows the truth table of -input nand gate department of csevishnu institute of technology
25,518
uniti = ( ) nor gatenor gate is digital circuit that has two or more inputs and produces an outputwhich is the inversion of logical or of all those inputs the following figure shows the symbol of nor gatewhich is having two inputs ab and one outputy the following table shows the truth table of -input nor gate = + yi department of csevishnu institute of technology
25,519
uniti arithmetic gates:exor,exnor ex-or ex-nor gates are called as arithmetic gates becausethese two gates are special cases of or nor gates ex-or gate the full form of ex-or gate is exclusive-or gate if both the inputs are or both the inputs are ,then obtained output is and for the remaining cases the output is taken as below figure shows the symbol of ex-or gatewhich is having two inputs ab and one outputy the following table shows the truth table of -input ex-or gate ab ex-northe full form of ex-nor gate is exclusive-nor gate it is inversion of ex-or the following figure shows the symbol of ex-nor gatewhich is having two inputs ab and one outputy department of csevishnu institute of technology
25,520
uniti the following table shows the truth table of -input ex-nor gate ab advantages of logic gates logic gates are quick yet use low energy logic gates don' get overworked logic gates can lessen the prescribed number of / ports needed by microcontroller logic gates can bring about straightforward data encryption and decryption applications of logic gates nand gates are used in burglar alarms and buzzers they are basically used in circuits involving computation and processing they are also used in push button switches door bell they are used in the functioning of street lights operating systemthe collection of computer programs that control the interaction of the user and computer hardware is called the operating system its responsibilities are communicating with the userreceiving commands and carrying them out department of csevishnu institute of technology
25,521
uniti managing allocation of memoryprocessor timeother resources for various tasks collecting input from the keyboardmouse and other input device sand providing this data to the currently running program conveying program output to the screenprinter or other output device accessing data from secondary storage writing data to secondary storage widely used os are windowslinux the relationship between hardwaresystem software and application software is as shown in the below diagram department of csevishnu institute of technology
25,522
uniti representation of data in memory (integer (including negative)floating points etc to textimagesaudio and video)computer uses fixed number of bits to represent piece of datawhich could be numbera characteror others for examplea -bit memory location can hold one of these eight binary patterns or refer to units of storage in computer page no: integer representationthe commonly-used bit-lengths for integers are -bit -bit -bit or -bit besides bit-lengthsthere are two representation schemes for integersunsigned integerswe can represent zero and positive integers signed integerswe can represent zeropositive and negative integers three representation schemes had been proposed for signed integerssign-magnitude representation ' complement representation ' complement representation sign-magnitude representationsigned binary numbers use the msb(most significant bitas sign bit to display range of either positive numbers or negative numbers positive signed binary numbers department of csevishnu institute of technology
25,523
uniti negative signed binary numbers disadvantagesan unfortunate feature of sign-value representation is that there are two ways of representing the value zeroall bits set to zeroand all bits except the sign bit set to zero this makes the math bit confusing one' complement of signed binary number one' complement or ' complement as it is also termedis another method which we can use to represent negative binary numbers in signed binary number system in one' complementpositive numbers (also known as non-complementsremain unchanged as before with the sign-magnitude numbers negative numbers howeverare represented by taking the one' complement (inversionnegationof the unsigned positive number ' complement of department of csevishnu institute of technology
25,524
uniti disadvantagean unfortunate feature of one' complement representation is that there are two ways of representing the value zeroall bits set to zeroand all bits set to one two' complement of signed binary number two' complement or ' complement as it is also termedis another method like the previous sign-magnitude and one' complement formwhich we can use to represent negative binary numbers in signed binary number system ' complement ' complement advantagein complementthere is only one representation for zero (+ because if we add to (- )we get (+ which is the same as positive zero this is the reason why complement is generally used representing textimages and soundrepresenting data all data inside computer is transmitted as series of electrical signals that are either on or off thereforein order for computer to be able to process any kind of dataincluding textimages and soundthey must be converted into binary form if the data is not converted into binary series of and the computer will simply not understand it or be able to process it department of csevishnu institute of technology
25,525
uniti representing text when any key on keyboard is pressedit needs to be converted into binary number so that it can be processed by the computer and the typed character can appear on the screen department of csevishnu institute of technology
25,526
uniti code where each number represents character can be used to convert text into binary one code we can use for this is called ascii the ascii code takes each character on the keyboard and assigns it binary number for examplethe letter 'ahas the binary number (this is the denary number the letter 'bhas the binary number (this is the denary number the letter 'chas the binary number (this is the denary number text characters start at denary number in the ascii codebut this covers special characters including punctuationthe return key and control characters as well as the number keyscapital letters and lower case letters ascii code can only store characterswhich is enough for most words in english but not enough for other languages if you want to use accents in european languages or larger alphabets such as cyrillic (the russian alphabetand chinese mandarin then more characters are needed therefore another codecalled unicodewas created this meant that computers could be used by people using different languages representing images images also need to be converted into binary in order for computer to process them so that they can be seen on our screen digital images are made up of pixels each pixel in an image is made up of binary numbers if we say that is black (or onand is white (or off)then simple black and white picture can be created using binary to create the picturea grid can be set out and the squares coloured ( black and whitebut before the grid can be createdthe size of the grid needs be known this data is called metadata and computers need metadata to know the size of an image if the metadata for the image to be created is this means the picture will be pixels across and pixels down this example shows an image created in this way department of csevishnu institute of technology
25,527
uniti adding colour the system described so far is fine for black and white imagesbut most images need to use colours as well instead of using just and using four possible numbers will allow an image to use four colours in binary this can be represented using two bits per pixel white blue green red while this is still not very large range of coloursadding another binary digit will double the number of colours that are available bit per pixel ( or )two possible colours bits per pixel ( to )four possible colours bits per pixel ( to )eight possible colours bits per pixel ( ) possible colours bits per pixel ( )over possible colours the number of bits used to store each pixel is called the colour depth images with more colours need more pixels to store each available colour this means that images that use lots of colours are stored in larger files representing sound sound needs to be converted into binary for computers to be able to process it to do thissound is captured usually by microphone and then converted into digital signal an analogue to digital converter will sample sound wave at regular time intervals for examplea sound wave like this can be sampled at each time sample point department of csevishnu institute of technology
25,528
uniti the samples can then be converted to binary they will be recorded to the nearest whole number time sample denary binary language hierarchythere are generally three types of computer languages they are machine language assembly language and high-level languages machine language( 'sit is the lowest-level programming language the fundamental/native language of the computer' processoralso called low level language each computer has its own machine language all programs are converted into machine language before they can be executed department of csevishnu institute of technology
25,529
uniti it consists of combination of ' and ' that represent high and low electrical voltage machine language is sequence of instructions written in the form of binary number to which computer responds directly it is considered as first generation language machine language instruction generally has three parts as shown below operation code mode operand part command or operation codeit conveys the computer what function has to be performed by the instruction part it either specifies the operand contains data on which the operation has to be performed or it specifies that the operand contains locationthe contents of which have to be subject to the operation advantagesthough it is not human friendly languageit offers following advantages translation freetranslation is not required as the cpu directly understands machine instructions as conversion is not neededprograms developed using these languages takes less execution time more control on hardware disadvantages difficult to useit is difficult to understand and develop program using machine language as it is very complex to write using binary numbers machine dependentcomputer architectures differ from one another the programmer has to remember machine characteristics while preparing program error pronesince the programmer has to remember all the opcodes and the memory locationsmachine language is bound to be error prone difficult to debug and modify assembly language ( ' ) department of csevishnu institute of technology
25,530
uniti the next evolution in programming came with the idea of replacing binary code for instruction and addresses with symbols or mnemonics because they used symbolsthese languages were first known as symbolic languages the set of these mnemonic languages were later referred to as assembly languages this language is also referred as low-level language every computer has its own assembly language that is dependent upon the internal architecture of the processor an assembler is translator that takes input in the form of the assembly language program and produces machine language code as its input assembler an assembler is translator that takes input in the form of the assembly language program and produces machine language code as its input an assembler is system software which converts an assembly language program to its equivalent object code the input to the assembler is source code written in assembly language and the output is an object code basic assembler functions are translating mnemonic language to its equivalent object code assigning machine address to symbolic labels advantagesit is easy to write and maintain programs in assembly language than in machine languages department of csevishnu institute of technology
25,531
uniti improved readability than machine language less error prone when compared with machine language assembly programs can run can run much faster and use less memory and other resources more control on hardware disadvantagesmachine dependentit is specific to particular machine architecture hard to learn assembly language program is less efficient than machine language program programming is difficult and time consuming high-level languagesalthough assembly languages greatly improved programming efficiencythey still required programmers to concentrate on the hardware they were using working with symbolic languages was also very tediousbecause each machine instruction had to be individually coded the desire to improve programmer efficiency and to change the focus from the computer to the problem being solved led to the development of high-level languages these languages have instructions that are similar to human languages and have set grammar that makes it easy for programmer to write programs and identify correct errors in them advantagesreadability programs written in these languages are more readable than those written in assembly and machine languages portabilityhigh level programming languages can be run on different machines with little or no change easy debuggingerrors can be easily detected and removed development of software is easy disadvantagespoor control on hardware less efficient compiler vs interpreter translation programs today are normally written in one of the high-level languages to run the program on computerthe program needs to be translated into the machine language of the computer on which it will run department of csevishnu institute of technology
25,532
uniti the program in high-level language is called the source program the translated program in machine language is called the object program two methods are used for translationcompilation and interpretation compilera compiler is translator which converts the program written in high-level language into assembly code or into another form of intermediate code or directly into machine code compiler converts the whole source code at once into object code and then executes it socompiler is faster than interpreter interpreteran interpreter is translator which converts the source program into object or machine code the interpreter converts the source code line -by-line and executes it immediatelywhich results in less performance thusan interpreter is slower than compiler difference between compiler and interpreter comparison compiler interpreter input it takes an entire program at time it takes single line of code speed comparatively fast slower memory memory requirement is more due to the creation of object code it requires less memory as it does not create intermediate object code errors displays all errors after compilation ,all at the same time displays error of each line one by one department of csevishnu institute of technology
25,533
uniti error detection difficuilt easy examples , ++,java,scala,etc python,perl,php,ruby,etc command line interface the command line is text interface for your computer it' program that takes in commandswhich it passes on to the computer' operating system to run from the command lineyou can navigate through files and folders on your computerjust as you would with windows explorer on windows or finder on mac os the difference is that the command line is fully text-based todaywith graphical user interfaces (gui)most users never use command-line interfaces (clihowevercli is still used by software developers and system administrators to configure computersinstall softwareand access features that are not available in the graphical interface basic linux cli commands department of csevishnu institute of technology
25,534
uniti basic windows cli commands linux commands pwd -when you first open the terminalyou are in the home directory of your user to know which directory you are inyou can use the "pwdcommand it gives us the absolute pathwhich means the path that starts from the root the root is the base of the linux file system it is denoted by forward slashthe user directory is usually something like "/home/username ls -use the "lscommand to know what files are in the directory you are in you can see all the hidden files by using the command "ls - department of csevishnu institute of technology
25,535
fixed part that is space required to store certain data and variables ( simple variables and constantsprogram size etc )that are not dependent of the size of the problem variable part is space required by variableswhose size is totally dependent on the size of the problem for examplerecursion stack spacedynamic memory allocation etc space complexity (pof any algorithm is (pa sp(iwhere is treated as the fixed part and (iis treated as the variable part of the algorithm which depends on instance characteristic following is simple example that tries to explain the concept algorithm sum(pqstep start step step stop here we have three variables pq and and one constant hence ( + now space is dependent on data types of given constant types and variables and it will be multiplied accordingly time complexity time complexity of an algorithm is the representation of the amount of time required by the algorithm to execute to completion time requirements can be denoted or defined as numerical function ( )where (ncan be measured as the number of stepsprovided each step takes constant time for examplein case of addition of two -bit integersn steps are taken consequentlythe total computational time is (nc*nwhere is the time consumed for addition of two bits herewe observe that (ngrows linearly as input size increases asymptotic notations asymptotic notations are used to represent the complexities of algorithms for asymptotic analysis these notations are mathematical tools to represent the complexities there are three notations that are commonly used big oh notation big-oh (onotation gives an upper bound for function (nto within constant factor we write (no( ( ))if there are positive constants and such thatto the right of the (nalways lies on or below * (no( ( ) (nthere exist positive constant and such that < ( < ( )for all <
25,536
conditional and repetition blocks:check the flowcharts in the topic "control structures in python conditionals and loopscomputational thinkingit follows steps decompositiondivide the problem into smaller problemsusually problems that we have solved before pattern recognitionfind similar repeated patternsidentify the differences note patterns may come from other domains that you have dealt with abstractiondefine the bigger problem as combination of solution of smaller problemseach of which is solved the same way hide all the details and focus on the bigger picture algorithm designwrite step by step procedure algorithmalgorithm is step-by-step procedurewhich defines set of instructions to be executed in certain order to get the desired output algorithms are generally created independent of underlying languagesi an algorithm can be implemented in more than one programming language characteristic or features of an algorithm inputmeans it has zero or more inputsi an algorithm can run without taking any input outputmeans it has one or more outputsi an algorithm must produce atleast one output finitenessmeans it must always terminate after finite number of steps definitenessmeans each step must be precisely defined and clear effectivenessmeans it is also generally expected to be effective an algorithm should be and unambiguous and independent of any programming codei language independent algorithm to add two numbers entered by the user step start step read values num and num step add num and num and assign the result to sum sum-num +num step display sum step stop algorithm to find greatest of three numbers
25,537
step read variables , and step if > and >= assign to the largest elif >= and >= assign to the largest else assign to the largest step display largest step stop pseudo code )pseudo code is one of the method that is used to represent an algorithm )it is not written using specific rulesso it will not execute in computer )there are lots of formats for writing pseudo code and most of them follow languages as ,fortran )pseudo code can be read ,understood by programmers who are familiar with different programming languages pseudo code for adding of two numbers begin number sum output("input number :"input output("input number :"input sum= + output sum end difference between algorithm and pseudo code algorithm pseudocode )well defined sequence of steps that provide solution for problem )one of the method that can be used to represent algorithm )it is written in natural language )it is written in informal way,closely related to programming language )any user can understand )only programmer familiar with language can understand elements of programming language pythontokentokens are the smallest unit of the program they are reserved words or keywords,identifiers,literals,operators
25,538
literal is raw data given in variable or constant in pythonthere are various types of literals they are as follows numeric literals string literals boolean literals literal collections numeric literals binary literals decimal literals octal literal hexadecimal literal float literal complex literal program to demonstrate numeric literals #binary literals #decimal literal #octal literal #hexadecimal literal print(abcd#float literal float_ float_ print(float_ float_ #complex literal + print(xx imag, realstring literals string literal is sequence of characters surrounded by quotes we can use both singledoubleor triple quotes for string ='this is pythons ="this is pythons ='''this is python''print( print( print( character literalscharacter literal is single character surrounded by single or double quotes ='ac ="ac =''' ''print(
25,539
print( boolean literalsa boolean literal can have any of the two valuestrue or false true false true false print(" is"xprint(" is"yprint(" :"aprint(" :"bliteral collections there are four different literal collections list literalstuple literalsdict literalsand set literals =[ , , =( , , ={ , , ={ :' ',' ':' 'print("list:",lprint("tuple:",tprint("set:",sprint("dictionary:",dpython identifiers an identifier is name given to entities like classfunctionsvariablesetc it helps to differentiate one entity from another rules for writing identifiers identifiers can be combination of letters in lowercase ( to zor uppercase ( to zor digits ( to or an underscore an identifier cannot start with digit keywords cannot be used as identifiers we cannot use special symbols like !@#$etc in our identifier keywords keywords are reserved words in python we cannot use keyword as variable namesfunction names and any other identifier they are used to define syntax and structure of python language keywords are case sensitive there are keywords in python
25,540
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 type conversion the process of converting the value of one data type (integerstringfloatetc to another data type is called type conversion python has two types of type conversion )implicit type conversion )explicit type conversion )implicit type conversion in this method python automatically converts one data type(lowerto another data type(higherthis process doesn' need any user involvement let' see an example where python promotes the conversion of the lower data type (integerto the higher data type (floatto avoid data loss #program to demonstrate implicit conversion = = = + print("the sum of and is ",cprint("the datatype of is",type( ) )explicit type conversion in explicit type conversionusers convert the data type of an object to required data type we use the predefined functions like int()float()str()etc to perform explicit type conversion this type of conversion is also called typecasting because the user casts (changesthe data type of the objects in type castingloss of data may occur as we enforce the object to specific data type syntax (expressionwrite program to demonstrate explicit conversion = = = + print("before explicit conversion",cprint(type( )
25,541
print("after explicit conversion",cprint(type( )outputbefore explicit conversion after explicit conversion variables variables are just names of memory locations variables are used to store and retrieve values from memory type of the variable is based on the value we assign to the variable variables are containers for storing the data value but there are few rules to follow when choosing name of variable names must start with letter or underscore and can be followed by any number of lettersdigitsor underscores cannot start with number it contain alpha-numeric characters undescore variable names are case sensitive(age,age,age are differentnames cannot be reserved words or keywords syntax variablename value egx ='pythonz= assign value to multiple variable , , = , , print(xprint(yprint(zx, , = ,'ayaan', print(xprint(yprint(zidentify the following are valid or invalid?? = ---valid _a= ---valid = ---invalid @= ---invalid = ---valid
25,542
input():the input(function allows user to give input syntax input(promptpromptit can be empty or string ega=int(input() =float(input() =input( =int(input("enter the value of ")print('enter your name:' input(print('helloxx input('enter your name:'print('helloxmultiple input at timea, =input("enter firstname"),input("enter lastname"print(aprint(boutput():this function is used to output the data or print the result on monitor egprint('welcome'print("python"print('''hello'''print( , , , print( , , ,sep='*'print( , , , ,sep='*',end='&'output formattingsometimes we would like to format our output to make it look attractive =
25,543
print('the value of is {and is {}format( , )outputthe value of is and is basic data types(numbers also includedevery value in python has datatype python has the following data types/objects built-in by defaultin these categoriestext typestr numeric typesintfloatcomplex sequence typeslisttuplerange mapping typedict set typessetfrozenset boolean typebool type():to know the data type of any object by using the type(function = print(type( ) = print(type( ) ='helloprint(type( )python numbersthey are categorized into mainly three types they are int,float and complex intit consists of positive and negative numbers without decimals they are of unlimited length = print(xprint(type( ) = print(yprint(type( ) =- print(zprint(type( )
25,544
= print(xprint(type( ) = print(yprint(type( ) =- print(zprint(type( )complex numberscomplex numbers in python are in the form of bj = + print(xprint(type( ) = print(yprint(type( ) =- print(zprint(type( )booleanspython provides boolean datatype called bool with values true false true represents integer and false represents integer bool is sub class of integer class following are examples on booleansegprint(true+ print(false* print(true+ print(false* =true print(type( ) =false print(type( ) =true print(type( )stringsa string is sequence of characters strings are used to store textual information it is represented by single quote or double quote eg
25,545
" " ='pythonprint(aprint(type( ) =' print(bprint(type( ) =str(input("enter ")print(cprint(type( ) =input(print(dprint(type( )python operators operators are used to perform operations on variables and values python divides the operators in the following groupsarithmetic operators assignment operators comparison operators logical operators identity operators membership operators bitwise operators python arithmetic operators arithmetic operators are used with numeric values to perform common mathematical operations
25,546
#arithmetic operators =int(input("enter the value of ") =int(input("enter the values of ")print("sum=", +yprint("sub=", -yprint("product=", *yprint("division", /yprint("modulus=", %yprint("exponentiation=", **yprint("floor division=", //yguest-guh cf@slave :~gedit arithmetic py guest-guh cf@slave :~python arithmetic py enter the value of enter the values of sum sub product division modulus exponentiation floor division python comparison operators comparison operators are used to compare two values#comparison operators =int(input("enter the values of :") =int(input("enter the values of :")
25,547
print( !=yprint( >yprint( <yprint( >=yprint( <=yguest-guh cf@slave :~gedit comparison py guest-guh cf@slave :~python comparison py enter the values of : enter the values of : false true false true false true python logical operators logical operators are used to combine conditional statements#logical operators =int(input("enter the value of :")print( < and < print( < or < print(not( > )guest-guh cf@slave :~gedit logical py
25,548
enter the value of : false false true python identity operators identity operators are used to compare the objectsnot if they are equalbut if they are actually the same objectwith the same memory location#identity operators =int(input("enter the value of :") =int(input("enter the value of :") = print( is yprint( is not yprint( is zguest-guh cf@slave :~gedit identity py guest-guh cf@slave :~python identity py enter the value of : enter the value of : false true true python membership operators membership operators are used to test if sequence is presented in an object#membership operators
25,549
=int(input("enter the value of :")print( in xprint( not in xguest-guh cf@slave :~gedit membership py guest-guh cf@slave :~python membership py enter the value of : true false python bitwise operators bitwise operators are used to compare (binarynumbers
25,550
=int(input("enter the value of :") =int(input("enter the value of :")print( &yprint( yprint( yprint(~xprint( << print( >> guest-guh cf@slave :~gedit bitwise py guest-guh cf@slave :~python bitwise py enter the value of : enter the value of :
25,551
- python assignment operators assignment operators are used to assign values to variableswrite program to demonstrate assignment operators =int(input("enter the value of :") + #same as = + print(" =",xx - #same as = - print(" =",xx * #same as = * print(" =",xx / #same as = / print(" =",xx % #same as = % print(" =",xx // #same as = // print(" =",xx ** #same as = ** print(" =",xguest-guh cf@slave :~gedit assignment py
25,552
enter the value of : expressions and order of evaluations(precedenceexpressionan expression is combination of operatorsconstants and variables an expression may consist of one or more operandsand zero or more operators to produce value eg * / * + python has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators the operator precedence in python are listed in the following table it is in descending orderupper group has higher precedence than the lower ones operators meaning (parentheses *exponent
25,553
unary plusunary minusbitwise not *///multiplicationdivisionfloor divisionmodulus +additionsubtraction bitwise shift operators bitwise and bitwise xor bitwise or ==!=>>=<<=isis notinnot in comparisionsidentitymembership operators not logical not and logical and or logical or operator precedence rule in python egprint( print(( print( + - associativity of python operators we can see in the above table that more than one operator exists in the same group these operators have the same precedence when two operators have the same precedenceassociativity helps to determine which the order of operations associativity is the order in which an expression is evaluated that has multiple operator of the same precedence almost all the operators have left-to-right associativity for examplemultiplication and floor division have the same precedence henceif both of them are present in an expressionleft one is evaluates first print( / to exponent operator *has right-to-left associativity in python
25,554
output print( * * shows the right-left associativity of *output print(( * * control structures in python conditionals and loops conditionalsdecision making statements/selection/conditional statements if statement if else statements elif ladder nested if statements if statement decision making is required when we want to execute code only if certain condition is satisfied python if statement syntax if testexpressionstatement(sherethe program evaluates the test expression and will execute statement(sonly if the text expression is true if the text expression is falsethe statement(sis not executed
25,555
num int(input("enter the value of num")if num print(num"is positive number "if else statement the if else statement evaluates test expression and will execute body of if only when test condition is true if the condition is falsebody of else is executed indentation is used to separate the blocks program checks if the number is positive or negative num int(input("enter the value of num")if num > print("positive or zero"elseprint("negative number"elif ladder
25,556
if the condition for if is falseit checks the condition of the next elif block and so on if all the conditions are falsebody of else is executed #program on elif ladder num float(input("enter the value of num")if num print("positive number"elif num = print("zero"elseprint("negative number"python program to find the largest number among the three input numbers int(input("enter the value of ") int(input("enter the value of ") int(input("enter the value of ")if ( >band ( > )largest elif ( >aand ( > )largest elselargest print("the largest number is",largestnested if statement if statement in another if is called as nested if statements syntaxif cond if cond if cond statements or
25,557
if cond statements elsestatements elseif cond statements elsestatements #program on nested if num float(input("enter number")if num > if num = print("zero"elseprint("positive number"elseprint("negative number"repetition statements(loops)for loop while loop for loop the for loop in python is used to iterate over sequence (listtuplestringor other iterable objects iterating over sequence is called traversal
25,558
hereval is the variable that takes the value of the item inside the sequence on each iteration loop continues until we reach the last item in the sequence the body of for loop is separated from the rest of the code using indentation egfor in range( )print(isyntax for rangerange(end# to end- range(start,end#start to end- range(start,end,stepfew more example on for loopfor in range( , )print(ifor in range( , )print( #print odd numbers for in range( , , )print( #print even numbers for in range( , , )print(ielse in for loop for in range( )print(
25,559
print("finally finished!"looping through string for in "ayaan"print(iwhile loop the while loop in python is used to iterate over block of code as long as the test expression (conditionis true flow chart eg#print numbers from to = while print(ii + #print odd numbers , , , , = while < print(ii= + #print even numbers , , , , , = while <= print(ii= +
25,560
in pythonbreak and continue statements can alter the flow of normal loop loops iterate over block of code until test expression is falsebut sometimes we wish to terminate the current iteration or even the whole loop without checking test expression the break and continue statements are used in these cases python break statement the break statement terminates the loop containing it control of the program flows to the statement immediately after the body of the loop if break statement is inside nested loop (loop inside another loop)break will terminate the innermost loop #using of break in for loop(output for in range( , )if == break print(
25,561
branch "csedef read_student_details(selfrnon)#regdno and name are instance variables self __regdno rno #regdno is private variable self name def print_student_details(self)print("student regd no is"self __regdnoprint("student name is"self nameprint("student branch is"student branchs student( read_student_details(" pa ""ramesh" print_student_details(print( __regdno#this line gives error as ___regdno is private self argument the self argument is used to refer the current object (like this keyword in and javagenerallyall class methods by default should have at least one argument which should be the self argument the self variable or argument is used to access the instance variables or object variables of an object __init__(method (constructorthe __init__(is special method inside class it serves as the constructor it is automatically executed when an object of the class is created this method is used generally to initialize the instance variablesalthough any code can be written inside it syntax of __init__(method is as followsdef __init__(selfarg arg )statement statement statementn for our student classthe __init__(method will be as followsdef __init__(selfrnon)#regdno and name are instance variables self regdno rno self name __del__(method (destructorthe __del__(method is special method inside class it serves as the destructor it is executed automatically when an object is going to be destroyed we can explicitly make the __del__(method to execute by deleting an object using del keyword
25,562
def __del__(self)statement statement statementn for our student class__del__(method can be used as followsdef __del__(self)print("student object is being destroyed")other special methods method description __repr__(this method returns the string representation of an object it works on any objectnot just user class instances it can be called as repr(object__cmp__(this method can be used to override the behavior of =operator for comparing objects of class we can also write our own comparison logic __len__(this method is used to retrieve the length of an object it can be called as len(object__call__(this method allows us to make class behave like function its instance can be called as object(arg ,arg __hash__(while working with sets and dictionaries in pythonthe objects are stored based on hash value this value can be generated using this method __lt__(this method overrides the behavior of operator __le__(this method overrides the behavior of <operator __eq__(this method overrides the behavior of operator __ne__(this method overrides the behavior of !operator __gt__(this method overrides the behavior of operator __ge__(this method overrides the behavior of >operator __iter__(this method can be used to override the behavior of iterating over objects __getitem__(this method is used for indexingi for accessing value at specified index __setitem__(this method is used to assign an item at specified index private methods
25,563
implementation of classwe can mark the method as private it is not recommended to access private method outside the class but if neededwe can access private method outside the class as followsobjectname _classname__privatemethod(arg arg if neededwe can access private variables using similar syntax as above following example demonstrates private methodclass boxdef __init__(selflb)self length self breadth #private method def __printdetails(self)print("length of box is:"self lengthprint("breadth of box is:"self breadthdef display(self)self __printdetails( box( , display(#recommended _box__printdetails(#not recommended built-in functions following are some of the built-in functions to work with objectsfunction description hasattr(objnamethis function checks whether the specified attribute belongs to the object or not getattr(objname[,default]this function retrieves the value of the attribute on an object if the default value is given it returns the that if no attribute is present otherwisethis function raises an exception setattr(objvaluethis function is used to set the value of an attribute on given object namedelattr(objnamethis function deletes an attribute on the given object built-in class attributes every class in python by default has some attributes those attributes can be accessed using dot operator these attributes are as follows
25,564
description __dict__ gives the dictionary containing the namespace of class __doc__ gives the documentation string of the class if specified otherwiseit returns none __name__ gives the name of the class __module__ gives the name of the module in which the class is defined __bases__ gives the base classes in inheritance as tuple otherwiseit returns an empty tuple garbage collection python runs process in the background which frees an object from memory when it is no longer needed or if it goes out of scope this process is known as garbage collection python maintains reference count for each object in the memory the reference count increases when we create aliases or when we assign an object new name or place it in list or other data structure reference count decreases when an object goes out of scope and it becomes zero when the object is deleted using del keyword class methods class method is method which is marked with classmethod decorator and the first argument to the method is cls class method is called using the class name class methods are generally used as factory method to create instances of the class with the specified arguments example of class method is as followsclass boxdef __init__(selflb)self length self breadth def display(self)print("length of box is:"self lengthprint("breadth of box is:"self breadth@classmethod def createinstance(clslb)return cls(lbb box createinstance( , display(static methods static method is method marked with staticmethod decorator code that manipulates information or data of class is placed in static method static method does not depend on the state of the object static
25,565
and cls following example demonstrates static methodclass boxsides none def __init__(selflb)self length self breadth def display(self)print("length of box is:"self lengthprint("breadth of box is:"self breadth@staticmethod def init_sides( )sides print("sides of box ="sidesbox init_sides( box( , display(inheritance creating new class from existing class is known as inheritance the class from which features are inherited is known as base class and the class into which features are derived into is called derived class inheritance promotes reusability of code by reusing already existing classes inheritance is used to implement is- relationship between classes following hierarchy is an example representing inheritance between classessyntax for creating derived class is as followsclass derivedclass(baseclass)statement statement
25,566
following example demonstrates inheritance in pythonclass shapedef __init__(self)print("shape constructor"def area()print("area of shape"def peri()print("perimeter of shape"class circle(shape)def __init__(selfr)shape __init__(self#calling parent constructor self radius print("circle constructor"def area(self)print("area of circle is:" *self radius*self radiusc circle( area(polymorphism polymorphism means having different forms based on the contexta variablefunctionor an object can have different meaning as inheritance is related to classespolymorphism is related to methods in pythonmethod overriding is one way of implementing polymorphism method overriding in method overridinga base class and the derived class will have method with the same signature the derived class method can provide different functionality when compared to the base class method when derived class method is created and the method is invokedthe derived class method executes overriding the base class method following example demonstrates method overridingclass shapedef __init__(self)print("shape constructor"def area(self)print("area of shape"def peri(self)print("perimeter of shape"class circle(shape)def __init__(selfr)shape __init__(self#calling parent constructor self radius print("circle constructor"def area(self)print("area of circle is:" *self radius*self radiusc circle( area(#circle class area method overrides shape class area method
25,567
introduction an error is an abnormal condition that results in unexpected behavior of program common kinds of errors are syntax errors and logical errors syntax errors arise due to poor understanding of the language logical errors arise due to poor understanding of the problem and its solution anomalies that occur at runtime are known as exceptions exceptions are of two typessynchronous exceptions and asynchronous exceptions synchronous exceptions are caused due to mistakes in the logic of the program and can be controlled asynchronous exceptions are caused due to hardware failure or operating system level failures and cannot be controlled examples of synchronous exceptions aredivide by zeroarray index out of boundsetc examples of asynchronous exceptions areout of memory errormemory overflowmemory underflowdisk failureetc overview of errors and exceptions in python is as followshandling exceptions flowchart for exception handling process is as follows
25,568
exceptions are placed in try block code that handles the exception is placed in except block the code that handles an exception is known as exception handler and this process is known as exception handling try and except syntax for using try and except for exception handling is as followstrystatement(sexcept exceptionnamestatement(sfollowing is an example for handling divide by zero exception using try and except blocksnumerator int(input()denominator int(input()tryquotient numerator denominator print("quotient:"quotientexcept zerodivisionerrorprint("denominator cannot be zero"input outputdenominator cannot be zero input
25,569
outputquotient multiple except blocks oftenthere will be need to handle more than one exception raised by try block to handle multiple exceptionswe can write multiple except blocks as shown belowtrystatement(sexcept exceptionname statement(sexcept exceptionname statement(sfollowing is an example for handling multiple exceptions using multiple except blocksnumerator int(input()denominator int(input()tryquotient numerator denominator print("quotient:"quotientexcept nameerrorprint("you are using variable which is not declared"except valueerrorprint("invalid value"except zerodivisionerrorprint("denominator cannot be zero"in the previous example for input and the output displayed is "denominator cannot be zerowhen the divide by zero exception was triggered in try blockfirst two except blocks were skipped as the type of exception didn' match with either nameerror or valueerror sothird except block was executed multiple exceptions in single block we can handle multiple exceptions using single except block as followstrystatement(sexcept(exceptionname exceptionname )statement(sfollowing is an example which demonstrates handling multiple exceptions using single except block
25,570
denominator int(input()tryquotient numerator denominator print("quotient:"quotientexcept (nameerror,valueerror,zerodivisionerror)print("denominator cannot be zero"for input and the output for the above code isdenominator cannot be zero handle any exception in some caseswe might want to execute the same code (handlerfor any type of exception such common handler can be created using except as followstrystatement(sexceptstatement(sfollowing is an example which demonstrates handling any exception with single except blocknumerator int(input()denominator int(input()tryquotient numerator denominator print("quotient:"quotientexceptprint("denominator cannot be zero"for input and the output for the above code isdenominator cannot be zero else clause the try and except blocks can be followed by an optional else block the code in else block executes only when there is no exception in the try block the else block can be used to execute housekeeping code like code to free the resources that are being used raising exceptions we can raise exceptions manually even though there are no exceptions using the raise keyword syntax of raise statement is as follows
25,571
exceptionname is the type of exception we want to raise args are the exception arguments and traceback is the traceback object used for the exception following is an example for demonstrating raise keywordtryraise nameerror except nameerrorprint("name error"in the above code nameerror exception is raised by the raise statement and is handled by the except block re-raising exceptions in pythonwe can re-raise the exceptions in the except block by writing raise keyword following code demonstrates re-raising exceptionstryraise nameerror except nameerrorprint("name error"raise output is as followsname error traceback (most recent call last)file "test py"line in raise nameerror nameerror handling exceptions in functions we can use try and except blocks inside functions as we are using until now in the try blockwe can call function if this function raises an exceptionit can be handled by the except block which follows the try block following example demonstrates handling exceptions in functionsdef div(numdenom)return num/denom trydiv( except zerodivisionerrorprint("denominator cannot be zero"output for the above program is as followsdenominator cannot be zero