id
int64
0
25.6k
text
stringlengths
0
4.59k
11,100
sscasc@tumkur max( , )call the max function print("the larger number of" "and" "is"kmain(call the main function output the larger number of and is categories of user-defined functions function with arguments function with an argument and return type function with default argument function with variable length argument ...
11,101
sscasc@tumkur syntax def function_name(arg*var)code block return herearg means normal argument which is passed to the function the *var refers to the variable length argument exampledef variable_argumentarg*vari)print ("out-put is",argfor var in variprint (varvariable_argument( variable_argument("hari", , , , , outputo...
11,102
sscasc@tumkur herein the function definitionwe pass the list to the pass_ref function and then we extend the list to add two more numbers to the list and then print its value the list extends inside the functionbut the change is also reflected back in the calling function we finally get the output by printing out diffe...
11,103
sscasc@tumkur local and global variables when we declare variable inside function it becomes local variable and its scope is limited to that function where it is created and it is available in that function and not available outside the function when variable declared outside the functionit is available to all function...
11,104
sscasc@tumkur exampleto find factorial using recursion def main() =int(input("enter nonnegative integer")print("factorial of" "is",factorial( )print( "factorial( )print( "factorial( )print( "factorial( )return the factorial for the specified number def factorial( )if = base case return elsereturn *factorial( - recursiv...
11,105
sscasc@tumkur modules module is library of functions modules are code files meant to be used by other programs normally files that are used as modules contain only class and function definitions modularizing makes code easy to maintain and debugand enables the code to be reused to use modulewe use the import statement ...
11,106
sscasc@tumkur return def mul ( , ) * return filename:test_module import module #import module_name print ("sum is "module sum ( , )print ("multiple is "module mul ( , )filename:test_module py import module as md #import module_name as new_name print ("sum is "md sum ( , )print ("multiple is "md mul ( , )arraylistssets ...
11,107
sscasc@tumkur represents signed integer of size bytes represents unsigned integer of size bytes represents unicode character of size bytes represents signed integer of size bytes represents unsigned integer of size bytes represents floating point of size bytes represents floating point of size bytes example of an array...
11,108
sscasc@tumkur my_array pop(array(' '[ ]so we see that the last element ( was popped out of array fetch any element through its index using index(index(returns first index of the matching value remember that arrays are zeroindexed my_array array(' '[ , , , , ]print(my_array index( )#output my_array array(' '[ , , , , ]p...
11,109
sscasc@tumkur output [[ [ [ ] array element wise printing matrix printing [[ [ [ ]matrix in numpy in python we can show matrices as array in numpya matrix is considered as specialized array it has lot of built in operators on matrices in numpymatrix is created using the following syntax matrix_name=matrix( array or str...
11,110
sscasc@tumkur [[ [ [ ]printing multplication of two matrix [[ [ [ ]printing division of two matrix [[ [ [ ]example#prog to accept matrix from key board and display its transpose from numpy importaccept rows and column of matrix" , =[int(afor in input("enter rows,col:"split()str=input("enter matrix elements:"#convert th...
11,111
sscasc@tumkur list creating list with values list contains comma-separated values for examplea [ avengers ['hulk''iron-man''captain''thor'list methods and supported operators starting with given list aa [ append(valueappends new element to the end of the list append values and to the list append( append( append( [ appe...
11,112
sscasc@tumkur returns index( valueerrorbecause is not in index( returns index( valueerrorbecause there is no starting at index insert(indexvalueinserts value just before the specified index thus after the insertion the new element occupies position index insert( insert at position insert( insert at position [ pop([inde...
11,113
sscasc@tumkur sum +value average sum number_of_elements count the number of elements above average for in range(number_of_elements)if numbers[iaveragecount + print("average is"averageprint("number of elements above the average is"countnumbers append(valuemultidimensional lists data in table or matrix can be stored in t...
11,114
sscasc@tumkur sets sets are like lists in that you use them for storing collection of elements unlike liststhe elements in set are non-duplicates and are not placed in any particular order creating sets python provides data structure that represents mathematical set as with mathematical setselements of set are enclosed...
11,115
sscasc@tumkur #prints print( in #prints false remove( print( #prints { , , { { print( issubset( ) is subset of #prints true { { print( issuperset( ) is superset of #prints true { { print( = )#prints true print( ! )#prints false set operations python provides the methods for performing set unionintersectiondifferenceand...
11,116
sscasc@tumkur dictionaries dictionary is container object that stores collection of key/value pairs it enables fast retrievaldeletionand updating of the value by using the key dictionary is collection that stores the values along with the keys the keys are like an index operator in listthe indexes are integers dictiona...
11,117
sscasc@tumkur del keyword is used to delete the entire dictionary or the dictionary' items syntax to delete dictionary' itemdel dict[keyconsidering the following code snippet for exampleport { "http" "telnet" "https"del port[ print(port{ 'http' 'https'syntax to delete the entire dictionarydel dict_name consider the fol...
11,118
sscasc@tumkur other dictionary functionssimilar to lists and tuplesbuilt-in functions available for dictionary len()to find the number of items that are present in dictionary exampleport { "http" "https" :"telnet"print(len(port) max()-it returns the key with the maximum worth exampledict { :"abc", :"hj" :"dhoni"(" "," ...
11,119
sscasc@tumkur mode description "ropens file for reading "wopens new file for writing if the file already existsits old contents are destroyed "aopens file for appending data from the end of the file "rbopens file for reading binary data "wbopens file for writing binary data " +opens file for reading and writing " +open...
11,120
sscasc@tumkur outputexamplewith access mode 'afile_input open("motivation txt",' 'file_input write("opens file for appending data from the end of the file"file_input close(outputreading data after file is opened for reading datayou can use the read(method to read specified number of characters or all characters from th...
11,121
sscasc@tumkur infile open("motivation txt"" "open file for input infile open("motivation txt"" "print("\ ( using readlines()"print(infile readlines()#prints lines to list infile close(close the input file main(call the main functionample:read_file py exception handling exception handling enables program to deal with ex...
11,122
sscasc@tumkur common standard exception classes class meaning attributeerror object does not contain the specified instance variable or method importerror when import statement fails to find specified module or name indexerror sequence (liststringtupleindex is out of range keyerror specified key does not appear in dict...
11,123
sscasc@tumkur try statement may have an optional finally clausewhich is intended to define cleanup actions that must be performed under all circumstances ex multiple excepts def main()trynumber number eval(input("enter two numbersseparated by comma")result number number print("result is"resultexcept zerodivisionerrorpr...
11,124
sscasc@tumkur the try finally statement try statement may include an optional finally block code within finally block always executes whether the try block raises an exception or not finally block usually contains "clean-up codethat must execute due to activity initiated in the try block the syntax is as followstry#run...
11,125
sscasc@tumkur what are threadsthreads (sometimes called lightweight processesare similar to processes except that they all execute within the same processthus all share the same context they can be thought of as "mini-processesrunning in parallel within main process or "main thread thread has beginningan execution sequ...
11,126
sscasc@tumkur running in this statethe thread makes progress and executes the taskwhich has been chosen by task scheduler to run nowthe thread can go to either the dead state or the non-runnablewaiting state non-running/waiting in this statethe thread is paused because it is either waiting for the response of some / re...
11,127
sscasc@tumkur multithreading increases the complexity of the program thus also making it difficult to debug it raises the possibility of potential deadlocks it may cause starvation when thread doesn' get regular access to shared resources it would then fail to resume its work creating threads in python python provides ...
11,128
sscasc@tumkur run(method which is also available to sub class every thread will run this method when it is started by overriding this run we can make threads run our own run(method examplefrom threading import thread import time class mythread(thread)def run(self)for in range( , )print("\nthread % going to sleep for se...
11,129
sscasc@tumkur thread is awake now thread going to sleep for seconds thread is awake now thread going to sleep for seconds thread is awake now thread going to sleep for seconds thread is awake now thread synchronization it is defined as mechanism which ensures that two or more concurrent threads do not simultaneously ex...
11,130
sscasc@tumkur object oriented programming the concept of object-oriented programming was seen to solve many problemswhich procedural programming did not solve in object-oriented programmingeverything is just like real-world object in the real worldeverything is an object an object can have state and behavior an object ...
11,131
sscasc@tumkur method we have to ( define the class (and the methods)( create an instanceand finally( invoke the method from that instance here is an example class with methodclass mymethod:#define the class def display(self)define the method print ('welcometo class mymethod'obj=mymethod(obj display(self is parameter th...
11,132
sscasc@tumkur print( getperimeter()print( getarea() setradius( print( radiusprint( getperimeter()print( getarea()output exampleconstruct py class car()""" simple attempt to represent car ""def __init__(selfmakemodelyear)"""initialize attributes to describe car ""self make make self model model self year year def get_na...
11,133
sscasc@tumkur myclass( myclass(print( howmany()print( howmany()del print( howmany()#print( howmany())prints error after deletion of object output class variables class variables are the oneswhich are sharable among all the instances of the class the class variable must be the same for all the instances class attributes...
11,134
sscasc@tumkur obj tumkur_org('mahesh''span', print(obj full_name)dotted notation print(obj make_email()print(obj increment()print(obj full_nameprint(obj make_email()print(obj increment()outputhari das hari das@gmail com mahesh span mahesh span@gmail com inheritance inheritance in python is based on similar ideas used i...
11,135
sscasc@tumkur def perimeter(self)return (self self bsqr=square( , print(sqr area()print(sqr perimeter()the square class will automatically inherit all attributes of the rectangle class as well as the object class super(refers to the superclass using super(we avoid referring the superclass explicitly super(is used to ca...
11,136
sscasc@tumkur overriding methods overriding methods allows user to override the parent class method that is use the same method both in base and child class the name of the method must be the same in the parent class and the child class with different implementations example:classover pyclass ()def sum (self, , )print(...
11,137
sscasc@tumkur providing they meet the regular expression' requirements regular expressions (which we will mostly call "regexesfrom now onare defined using mini-language that is completely different from python--but python includes the re module through which we can seamlessly create and use regexes regexes are used for...
11,138
sscasc@tumkur databases talking to the database with python the rdbms rdbms stands for relational database management system rdbms is the basis for sqland for all modern database systems like ms sql serveribm db oraclemysqland microsoft access (rdbmsis database management system that is based on the relational model as...
11,139
sscasc@tumkur might be the single client using mysql on your local machineoften referred to as "local hostwithout any network connection at allthe requests to the database server can also be made from program that acts on behalf of user making requests from web page we can connect to the database server from php progra...
11,140
sscasc@tumkur to communicate with the mysql serveryou will need languageand sql (structured query languageis the language of choice for most modern multiuserrelational databases sql provides the syntax and language constructs needed to talk to relational databases in standardizedcross-platform structured way we discuss...
11,141
sscasc@tumkur largest value+ decimal same as double but fixed point rather than floating point bit or date and time data types as with numberswe can choose from range of different data types to store dates and timesdepending on whether we want to store date onlya time onlyor bothdate/time data type description allowed ...
11,142
sscasc@tumkur longtext large text field characters blob normal sized binary large object bytes mediumblob medium sized blob bytes ( mbintroduction to sql statements the standard language for communicating with relational databases is sqlthe structured query language sql is an ansi (american national standards institute...
11,143
sscasc@tumkur selectis used to retrieve data from the database insertis used to insert data into table updateis used to update existing data within table deleteis used to delete records from database table data control language (dcl)dcl includes commands such as grant and revoke which mainly deals with the rightspermis...
11,144
sscasc@tumkur to see the structure of newly created table use explain commandas followsmysql explain fruitadding data to table now try adding some data into fruit table to add new row to tableyou use the sql insert statement in its basic forman insert statement looks like thisinsert into table values value value )this ...
11,145
sscasc@tumkur to retrieve selected row or rowswe need to introduce where clause at the end of the select statement where clause filters the results according to the condition in the clause here is simple where clausesmysql select from fruit where name 'banana'connecting python with database install mysql connector pyth...
11,146
sscasc@tumkur connect(function establishes connection to the mysql database from python application and returns mysqlconnection object this process automates logging into the database and selecting database to be used then we can use mysqlconnection object to perform various operation on the mysql database connect (fun...
11,147
sscasc@tumkur some of python database functions db close(closes the connection to the database (represented by the db object which is obtained by calling connect(functiondb commit(commits any pending transaction to the databasedoes nothing for databases that don' support transactions db cursor(returns database cursor o...
11,148
sscasc@tumkur sequence)size defaults to arraysize db fetchone(returns the next row of the query result set as sequenceor none when the results are exhausted raises an exception if there is no result set db rowcount(the read-only row count for the last operation ( ,selectinsertupdateor deleteor - if not available or not...
11,149
sscasc@tumkur graphical user interface the user can interact with an application through graphics or an image is called gui [graphical user interfacehere the user need not remember any commands user can perform task just by clicking on relevant images advantages it is user friendly it adds attraction and beauty to any ...
11,150
sscasc@tumkur framea frame is similar to canvasbut it can hold components of forms to create framewe can create an object of frame class as fframe(rootheight= ,width= ,bg="yellow",cursor="crosshere'fis an object of class framethe options height and width reprsents the area of frame in pixels'bgrepresents the back groun...
11,151
python gui programming cookbook introduction to problem solving with python murach' python programming object-oriented programming in python exploring python puttini burkhard meier packt st balagurusamy tmh st joel murachmichael urban michael goldwasserdavid letscher budd spd st pearson prentice hall st tmh st
11,152
introduction unit structure objectives introductionthe python programming language history features installing python running python program debugging syntax errors runtime errors semantic errors experimental debugging formal and natural languages the difference between bracketsbracesand parentheses summary references ...
11,153
we don' need to use data types to declare variable because it is dynamically typed so we can write = to declare an integer value in variable python makes the development and debugging fast because there is no compilation step included in python development history python was first introduced by guido van rossum in at t...
11,154
gui or graphical user interface is one of the key aspects of any programming language because it has the ability to add flair to code and make the results more visual python has support for wide array of guis which can easily be imported to the interpreterthus making this one of the most favorite languages for develope...
11,155
follow the stepsright click on my computer--properties -->advanced system setting -->environment variable -->new in variable name write path and in variable value copy path up to :/python ( path where python is installedclick ok ->ok running python programthere are different ways of working in python how to execute pyt...
11,156
to execute the code directly in the interactive mode you have to open the interactive mode press the window button and type the text "pythonclick the "python ( bitdesktop appas given below to open the interactive mode of python you can type the python code directly in the python interactive mode herein the image below ...
11,157
another useful method of executing the python code use the python idle gui shell to execute the python program on windows system open the python idle shell by pressing the window button of the keyboard type "pythonand click the "idle (python bit)to open the python shell create python file with py extension and open it ...
11,158
it contains the simple python code which prints the text "hello world!in order to execute the python codeyou have to open the 'runmenu and press the 'run moduleoption new shell window will open which contains the output of the python code create your own file and execute the python code using this simple method using p...
11,159
we can change the flow of execution by using jumpcontinue statements syntax errorerrors are the mistakes or faults performed by the user which results in abnormal working of the program howeverwe cannot detect programming errors before the compilation of programs the process of removing errors from program is called de...
11,160
one of the most important skills you will acquire is debugging although it can be frustratingdebugging is one of the most intellectually richchallengingand interesting parts of programming debugging is also like an experimental science once you have an idea about what is going wrongyou modify your program and try again...
11,161
to define list with name as with three elements , and [ , , [ , , brackets can be used for indexing and lookup of elements examplel [ [ , , exampleto lookup the element of list [ brackets can be used to access the individual characters of string or to make string slicing examplelookup the first characters of string str...
11,162
parentheses can be used to create immutable sequence data type tuple examplecreate tuple named ' with elements , , ( , , type( parentheses can be used to define the parameters of function definition and function call examplemultiply two numbers using function def mul( , )returns * = = =mul ( , print( ,'*', ,'='zin the ...
11,163
www xspdf com think python by allen downey st edition python programming for beginners by prof rahul boratedr sunil khilariprof rahul navale unit end exercise use web browser to go to the python website http/python org this page contains information about python and links to pythonrelated pagesand it gives you the abil...
11,164
variables and expression unit structure objectives introduction values and types variables variable names and keywords type conversion implicit type conversion explicit type conversion operators and operands expressions interactive mode and script mode order of operations summary references unit end exercise objectives...
11,165
python is case sensitiveso myvariable is not the as myvariable which in turn is not the same as myvariable with some exceptionshoweverthe programmer should avoid assigning names that differ only by case since human readers can overlook such differences same values and types value is one of the basic things program work...
11,166
common way to represent variables on paper is to write the name with an arrow pointing to the variable' value type(messagetype(ntype(pivariable names and keywordsprogrammers generally choose names for their variables that are meaningful they document what the variable is used for variable names can be arbitrarily long ...
11,167
help false class from or none continue global pass true def if raise and del import return as elif in try assert else is while async except lambda with await finally nonlocal yield break for not you might want to keep this list handy if the interpreter complains about one of your variable names and you don' know whysee...
11,168
in the above programwe add two variables num_int and num_flostoring the value in num_new we will look at the data type of all three objects respectively in the outputwe can see the data type of num_int is an integer while the data type of num_flo is float alsowe can see the num_new has float data type because python al...
11,169
num_int num_str " print ("data type of num_int:"type(num_int)print ("data type of num_str before type casting:"type(num_str)num_str int(num_strprint ("data type of num_str after type casting:"type(num_str)num_sum num_int num_str print ("sum of num_int and num_str:"num_sumprint ("data type of the sum:"type(num_sum)when ...
11,170
logical operators membership operators identity operators arithmetic operatorsoperators description /perform floor division (gives integer value after divisionto perform addition to perform subtraction to perform multiplication to perform division to return remainder after division (modulus*perform exponent (raise to p...
11,171
relational operators examples < true > false <= true >= true == false != true logical operatorsoperators and description logical and (when both conditions are true output will be truelogical or (if any one condition is true output will be true logical not (compliment the condition reverseor not logical operators exampl...
11,172
= = list[ , , , , if ( in list)print (" is in given list"elseprint (" is not in given list"if ( not in list)print (" is not given in list"elseprint (" is given in list"outputa is in given list is given in list identity operatorsoperators is is not description returns true if identity of two operands are sameelse false ...
11,173
an expression is combination of valuesvariablesand operators value all by itself is considered an expressionand so is variableso the following are all legal expressions (assuming that the variable has been assigned value) statement is unit of code that the python interpreter can execute we have seen two kinds of statem...
11,174
= print produces the output the assignment statement produces no output order of operations when more than one operator appears in an expressionthe order of evaluation depends on the rules of precedence for mathematical operatorspython follows mathematical convention the acronym pemdas is useful way to remember the rul...
11,175
or and and > > false summary in this we studied how to declare variablesexpression and types of variables in python we are more focuses on type conversion of variables in this basically two types of conversion are implicit type conversion and explicit type conversion also studied types of operators available in python ...
11,176
type the following statements in the python interpreter to see what they do = + now put the same statements into script and run it what is the outputmodify the script by transforming each expression into print statement and then run it again write program add two numbers provided by the user write program to find the s...
11,177
conditional statementsloopingcontrol statements unit structure objectives introduction conditional statementsif statement if-elseif elif else nested if -else looping statementsfor loop while loop nested loops control statementsterminating loops skipping specific conditions summary references unit end exercise objective...
11,178
then the indented statement gets executed if notnothing happens if statements have the same structure as function definitionsa header followed by an indented body statements like this are called compound statements there is no limit on the number of statements that can appear in the bodybut there has to be at least one...
11,179
printsand function calls if statementsyntax if test expressionstatement(sherethe program evaluates the test expression and will execute statement(sonly if the test expression is true if the test expression is falsethe statement(sis not executed in pythonthe body of the if statement is indicated by the indentation the b...
11,180
syntax if test expressionbody of if elsebody of else the if else statement evaluates test expression and will execute the body of if only when the test condition is true if the condition is falsethe body of else is executed indentation is used to separate the blocks example of if else program checks if the number is po...
11,181
the elif is short for else if it allows us to check for multiple expressions if the condition for if is falseit checks the condition of the next elif block and so on if all the conditions are falsethe body of else is executed only one block among the several if elif else blocks is executed according to the condition th...
11,182
this time we use nested if statement''num float (input ("enter number")if num > if num = print("zero"elseprint ("positive number"elseprint ("negative number"output enter number positive number output enter number- negative number output enter number zero looping statements in generalstatements are executed sequentially...
11,183
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 examplepython for loop program to find the sum of all numbers stored in list list of nu...
11,184
we can use the range (function in for loops to iterate through sequence of numbers it can be combined with the len (function to iterate through sequence using indexing here is an example program to iterate through list using indexing city ['pune''mumbai''delhi'iterate over the list using index for in range(len(city))pr...
11,185
if student =student_nameprint(marks[student]break elseprint ('no entry with that name found 'outputno entry with that name found while loopthe while loop in python is used to iterate over block of code as long as the test expression (conditionis true we generally use while loop when we don' know the number of times to ...
11,186
print ("the sum is"sumwhen you run the programthe output will beenter the sum is in the above programthe test expression will be true as long as our counter variable is less than or equal to ( in our programwe need to increase the value of the counter variable in the body of the loop this is very important failing to d...
11,187
nested loop allows us to create one loop inside another loop it is similar to nested conditional statements like nested if statement nesting of loop can be implemented on both for loop and while loop we can use any loop inside loop for examplefor loop can have while loop in it nested for loopfor loop can hold another f...
11,188
table of example of nested for loop in pythonfor in range ( )for in range( )print ("*"end='print ("output************************************nested while loopwhile loop can hold another while loop inside it in above situation inside while loop will finish its execution first and the control will be returned back to out...
11,189
= while <=pprint (pend=" += += print ("output exampleb program to nested while loop = while > = while >=xprint (xend=" -= -= print("output
11,190
control statements in python are used to control the order of execution of the program based on the values and logic python provides us with three types of control statementscontinue break terminating loopsthe break statement is used inside the loop to exit out of the loop it is useful when we want to terminate the loo...
11,191
for num in range ( )if num = continue elseprint(numoutput summary in this we studied conditional statements like ifif-elseifelif-else and nested if-else statements for solving complex problems in python more focuses on loop control in python basically two types of loops available in python like while loopfor loop and n...
11,192
numbers from series of numbers sample numbersnumbers ( expected outputnumber of even numbers number of odd numbers write python program that prints all the numbers from to except and noteuse 'continuestatement expected output print first natural numbers using while loop print the following pattern display numbers from ...
11,193
functions unit structure objectives introduction function calls type conversion functions math functions adding new functions definitions and uses flow of execution parameters and arguments variables and parameters are local stack diagrams fruitful functions and void functions why functions importing with fromreturn va...
11,194
whenever you need to carry out that action we are already repeating ourselves in our codeso this is good time to introduce simple functions functions mean less work for us as programmersand effective use of functions results in code that is less error function calls what is function in pythonin pythona function is grou...
11,195
""print ("helloname good morning!"how to call function in pythononce we have defined functionwe can call it from another functionprogram or even the python prompt to call function we simply type the function name with appropriate parameters greeting('idol'helloidol good morning type conversion functions the process of ...
11,196
datatype num_int num_str " print ("data type of num_int:"type(num_int)print ("data type of num_str:"type(num_str)print(num_int+num_stroutputdata type of num_intdata type of num_strtraceback (most recent call last)file "python"line in typeerrorunsupported operand type(sfor +'intand 'strin the above programwe add two var...
11,197
print ("data type of the sum:"type(num_sum)outputdata type of num_intdata type of num_str before type castingdata type of num_str after type castingsum of num_int and num_str data type of the sumtype conversion is the conversion of object from one data type to another data type implicit type conversion is automatically...
11,198
the math module contains functions for calculating various trigonometric ratios for given angle the functions (sincostanetc need the angle in radians as an argument weon the other handare used to express the angle in degrees the math module presents two angle conversion functionsdegrees (and radians ()to convert the an...
11,199
adding new functions so farwe have only been using the functions that come with pythonbut it is also possible to add new functions function definition specifies the name of new function and the sequence of statements that execute when the function is called exampledef print_lyrics()print (" ' lumberjackand ' okay "prin...