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 pass by reference function with arguments function can contain any number of arguments depending on the requirement exampledef func(passargument):#function definition print passargument str "hello allfunc(str)function call in this examplethe func function accepts one argument which has data type string we create variable str with certain string statement assigned and then we call the func function and thereby pass the value of str finallythe output will behello all function with an argument and return type this type of function takes any arbitrary number of arguments and return specific data type or value from it examplerefer above program fun_max py function with default argument in this type of functionthe formal parameter assigned with some valuerepresents default parameter or default argument if the caller does not supply an actual parameterthe formal parameter value is assigned exampledef info(nameage= )print("name:"nameprint("age:"ageinfo("john"age= info("james"outputnamejohn age namejames age function with variable length argument there might be scenario where you need to pass more arguments than specified during the function definition in this casevariable length arguments can be passedsp_python programming
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", , , , , outputout-put is out-put is hari pass by reference versus pass by value in pass by reference values to the argument of the function are passed as referencethat isthe address of the variable is passed and then the operation is done on the value stored at these addresses pass by value means that the value is directly passed as the value to the argument of the function in this casethe operation is done on the value and then the value is stored at the address in python argumentsthe values are passed by reference during the function callthe called function uses the value stored at the address passed to it and any changes to it also affect the source variableexamplecall by reference def pass_ref(list ):#call by ref list extend([ , ]print ("list inside the function",list list [ , , print ("list before pass"list pass_ref(list print ("list outside the function"list outputlist before pass [ list inside the function[ list outside the function [ sp_python programming
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 different representations of the listlet' look at another exampledef func( ):#call by value function = + print ("inside the function"aa func(aprint ("outside the function"athe preceding example call by valueas the change happening inside the python function does not get reflected back in the calling function it is still pass by referenceasin this situation inside the functionwe made new assignmentthat isaa+ although you might think that is changing the number stored in abut it is actually reassigning to point to new valuereturning multiple values from function in python functionwe can return multiple values we can use return statements as return , , here , , values returned by function as tuples and we have to use three variables to receive these values in called function as shown below , , =function(example:sum_sub_mul def sum_sub_mul( , )sum= + sub= - mul= * return sum,sub,mul def main() = = , , =sum_sub_mul( ,bprint("sum of two no=",xprint("sub of two no=",yprint("mul of two no=",zprint("sumsub and mul of two no:" =sum_sub_mul( , )#retrieving multiple value using tuples for in tprint( ,end='\ 'main(output sum of two no sub of two no mul of two no sumsub and mul of two no sp_python programming
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 which are using these variables sometimes local variable and global variable have the same namein this case the function ignores global variable and uses local variable only when the programmer wants to use the global variable inside functionwe can use the keyword global before the variable in the beginning of the function body exampleb= #global variable = def myfunction() = #local variable print("global :",bprint("local :",aglobal #this is global print("global :",cc= #this is local print("local :",cmyfunction(output global local global local recursion recursive function is one that invokes itself or recursive function is function that calls itself in its definition for example the mathematical functionfactorialdefined by factorial(nn*( - )( - )* * * can be programmed as def factorial( )# here should be an integer if = return elsereturn *factorial( - any recursive function can be divided into two parts firstthere must be one or more base casesto solve the simplest casewhich is referred to as the base case or the stopping condition nextrecursive caseshere function is called with different argumentswhich are referred to as recursive call these are values that are handled by "reducingthe problem to "simplerproblem of the same form sp_python programming
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( - recursive call main()call the main outputenter nonnegative integer factorial of is profiling profiling means having the application run while keeping track of several different parameterslike the number of times function is calledthe amount of time spent inside itand so on profiling can help us find the bottlenecks in our applicationso that we can improve only what is really slowing us down python includes profiler called cprofile it breaks down your entire script and for each method in your script it tells youncallsthe number of times method was called tottimetotal time spent in the given function (excluding time made in calls to subfunctionspercalltime spent per call or the quotient of tottime divided by ncalls cumtimethe cumulative time spent in this and all subfunctions (from invocation till exitthis figure is accurate even for recursive functions percallis the quotient of cumtime divided by primitive calls filenamelineno(function)provides the respective data of each function sp_python programming
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 module can also import other modules example:gcd_lcm file name gcd_lcm_module py return the gcd of two integers def gcd( ) initial gcd is qn possible gcd while != = % = = gcd= lcm=int( * /gcdreturn gcd,lcm return gcd and lcm now we write separate program to use the above module functionas shown below file name test_module file name test_module py from gcd_lcm_module import gcd import the module prompt the user to enter two integers eval(input("enter the first integer") eval(input("enter the second integer")print("the gcd and lcm for" ,"and" "is"gcd( )outputenter the first integer enter the second integer the gcd and lcm for and is ( the import statement in order to use the functions and variables of the module py programwe will use the import statement the syntax of the import statement is shown hereimport module module module the statements and definitions of modules are executed for the first time when the interpreter encounters the module name in the import statement in preceding codein order to use the module variables and functionsuse the module_name variable and module_name function(notations in order to write module with every function of module pypython allows use the as statement as shown the syntax is given as followsimport module_name as new_name example:module def sum ( , ) + sp_python programming
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 and dictionary arrays an array is data structure that stores values of same data type in pythonthis is the main difference between arrays and lists while python lists can contain values corresponding to different data typesarrays in python can only contain values corresponding to same data type to use arrays in python languageyou need to import the standard array module this is because array is not fundamental data type like stringsinteger etc here is how you can import array module in pythonfrom array import once you have imported the array moduleyou can declare an array here is how you do itarrayidentifiername array(typecode[initializers]typecode details represents signed integer of size byte represents unsigned integer of size byte represents character of size byte represents unicode character of size bytes represents signed integer of size bytes represents unsigned integer of size bytes sp_python programming
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 containing integersfrom array import my_array array(' '[ , , , , ]for in my_arrayprint( #output: , , , , some built-in array methodsappend any value to the array using append(method my_array array(' '[ , , , , ]my_array append( array(' '[ ]note that the value was appended to the existing array values insert value in an array using insert(method my_array array(' '[ , , , , ]my_array insert( , #array(' '[ ]in the above examplethe value was inserted at index note that the first argument is the index while second argument is the value extend python array using extend(method my_array array(' '[ , , , , ]my_extnd_array array(' '[ , , , ]my_array extend(my_extnd_arrayarray(' '[ ]we see that the array my_array was extended with values from my_extnd_array remove any array element using remove(my_array array(' '[ , , , , ]my_array remove( array(' '[ ]we see that the element was removed from the array remove last array element using pop(method pop removes the last element from the array my_array array(' '[ , , , , ]sp_python programming
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(' '[ , , , , ]print(my_array index( )#output note in that second example that only one index was returnedeven though the value exists twice in the array reverse python array using reverse(method the reverse(method reverses the array my_array array(' '[ , , , , ]my_array reverse(array(' '[ ]sort python array using sort(method from array import my_array [ , , , , my_array sort(print(my_array#output: , , , , multi-dimensional array an array containing more than one row and column is called multidimensional array it is also called combination of several arrays array is also considered as matrix =array([ , , , ])create array with row =array([ , , , ],[ , , , ]create array with row example: d_array from numpy importa=array([[ , , ],[ , , ],[ , , ]]print( )#prints array as rows print(" array element wise printing"for in range(len( ))for in range(len( [ ]))print( [ ][ ],end=')#prints array element wise print(end='\ 'print(end='\ # array as matrix by using matrix fun print("matrix printing" =matrix(' 'print(asp_python programming
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 stringeg =matrix(' ; ; 'matrix additionmultiplication and division we can use arithmetic operators like +-,,to perform different operations on matrices examplematrix_operation from numpy importa=matrix(' ; ; ' =matrix(' ; ; 'print("printing matrix"print(aprint("printing matrix"print(bprint("printing addition of two matrix" = + #matrix addition print(cprint("printing multplication of two matrix" = * #matrix addition print(cprint("printing division of two matrix" = / #matrix addition print(coutput printing matrix [[ [ [ ]printing matrix [[ [ [ ]printing addition of two matrix sp_python programming
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 the string into amatrix with size * =reshape(matrix(str),( , )print("the original matrix"print(xprint("printing transpose of matrix" = transpose(print(youtput enter rows,col enter matrix elements: the original matrix [[ [ ]printing transpose of matrix [[ [ ]lists list is an object that holds collection of objectsit represents sequence of data list can hold any python object list need not be homogeneousthat isthe elements of list do not all have to be of the same type like any other variablea list variable can be local or globaland it must be defined (assignedbefore its use the following are the characteristics of python listvalues are ordered mutable list can hold any number of values list can addremoveand alter the values creating list let' see how we can create an empty listsp_python programming
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( [ append an element of different typeas list elements do not need to have the same type my_string "hello worlda append(my_stringa[ [ ]"hello world"note that the append(method only appends one new element to the end of the list if you append list to another listthe list that you append becomes single element at the end of the first list appending list to another list [ [ append(ba[ [ ] [ returns[ extend(enumerableextends the list by appending elements from another enumerable [ [ extend list by appending all elements from extend(ba[ extend list with elements from non-list enumerablea extend(range( ) [ lists can also be concatenated with the operator note that this does not modify any of the original listsa [ [ [ index(value[startindex]gets the index of the first occurrence of the input value if the input value is not in the list valueerror exception is raised if second argument is providedthe search is started at that specified index index( sp_python programming
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([index]removes and returns the item at index with no argument it removes and returns the last element of the list pop( returns [ pop( returns [ with no argumenta pop(returns [ remove(valueremoves the first occurrence of the specified value if the provided value cannot be founda valueerror is raised remove( remove( [ remove( valueerrorbecause is not in reverse(reverses the list in-place and returns none reverse( [ count(valuecounts the number of occurrences of some value in the list count( returns sort(sorts the list in numerical and lexicographical order and returns none sort( [ sorts the list in numerical order the slicing of list syntax[startstopstepa [ print( [ : ]#output[ example:#to demonstrate lists number_of_elements create an empty list numbers=[sum for in range(number_of_elements)value eval(input("enter new number")numbers append(valuesp_python programming
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 two-dimensional list twodimensional list is list that contains other lists as its elements value in two-dimensional list can be accessed through row and column index you can think of two-dimensional list as list that consists of rows each row is list that contains the values the rows can be accessed using the indexconveniently called row index the values in each row can be accessed through another indexcalled column index two-dimensional list named matrix is illustrated in figure exampleinitializing lists with input values#the following loop initializes the matrix with user input valuesmatrix [create an empty list numberofrows eval(input("enter the number of rows")numberofcolumns eval(input("enter the number of columns")for row in range(numberofrows)matrix append([]add an empty new row for column in range(numberofcolumns)value eval(input("enter an element and press enter")matrix[rowappend(valueprint("printing matrix "for row in range(len(matrix))for column in range(len(matrix[row]))print(matrix[row][column]end "print(print new line outputenter the number of rows enter the number of columns enter an element and press enter enter an element and press enter enter an element and press enter enter an element and press enter printing matrix sp_python programming
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 inside pair of curly braces (}the elements are non-duplicateseparated by commas you can create an empty setor you can create set from list or tupleas shown in the following exampless setcreate an empty set { create set with three elements set([ ]create set from tuple exampleprogram to convert tuple into set#we can make set out of list functionl [ =set(lprint(lprint( { using the set conversion exampleoperations on setss { add( print( )#prints { print(len( )#prints print(max( )#prints print(min( )#prints print(sum( )sp_python programming
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 symmetric difference operations examples { { print( union( )print( print( intersection( )print( print( difference( )print( print( symmetric_difference( )print( output{ { { { { { { { sp_python programming
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 dictionary cannot contain duplicate keys each key maps to one value key and its corresponding value form an item (or entrystored in dictionaryas shown in figure the data structure is called "dictionarybecause it resembles word dictionarywhere the words are the keys and the wordsdefinitions is the values dictionary is also known as mapwhich maps each key to value the syntax of dictionary is as followsdictionary_name {keyvalueexampleport { "ssh" "telnet "dns" httpthe port variable refers to dictionary that contains port numbers as keys and its protocol names as values consider the following examplecompanies {"ibm""international business machines"" & :"larsen toubro"characteristics of dictionarythe keys in dictionary may have different types(stringintor floatthe values in dictionary may have different types the values in dictionary may be mutable objects the key of the dictionary cannot be changed keys are unique values can be anythingfor exampleliststringintand so on values can be repeated values can be changed dictionary is an unordered collectionwhich means that the order in which you have entered the items in dictionary may not be retained and you may get the items in different order the order of keyvalue pairs in dictionary are independent of the order of their insertion into the dictionary operations on the dictionary dictionary is mutablewe can add new valuesand delete and update old values accessing the values of dictionary the dictionary' values are accessed by using key consider dictionary of networking portsin order to access the dictionary' valuesthe key is considered port { "http" "telnet" "https"print(port[ ]>>'httpprint(port[ ]>>'httpsif the key is not foundthen the interpreter shows the preceding error deleting an item from the dictionary sp_python programming
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 following exampleport { "http" "telnet" "https"del port print(porttraceback (most recent call last)file ""line in port nameerrorname 'portis not defined the preceding error shows that the port dictionary has been deleted updating the values of the dictionary to update the dictionaryjust specify the key in the square bracket along with the dictionary name and assigning new value the syntax is as followsdict[keynew_value exampleport { "http" "smtp" "https"in the preceding dictionarythe value of port is "smtp"but in realityport number is for telnet protocol let' update the preceding dictionary with the following codeport { "http" "smtp" "https"printport{ 'http' 'https' 'smtp'port[ "telnetprint(port{ 'http' 'https' 'telnet'adding an item to the dictionary item can be added to the dictionary just by specifying new key in the square brackets along with the dictionary the syntax is as followsdict[new_keyvalue exampleport { "http" "telnet"port[ ]="popprint(port{ 'http' 'pop' 'telnet'sp_python programming
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"(" "," "):"game""hj": max(dict (' '' 'min()it returns the dictionary' key with the lowest worth the syntax of the method is as followsexampledict ={ 'abc'( )'kl' 'hj' 'dhoni''hj' min(dict files files are used to store data permanently data used in program is temporaryunless the data is specifically savedit is lost when the program terminates to permanently store the data created in programyou need to save it in file on disk or some other permanent storage device the file can be transported and can be read later by other programs python' standard library has file class that makes it easy for programmers to make objects that can store data toand retrieves data fromdisk in order to read and write into filewe will use the open(built-in function to open the file the open(function creates an file_object object the syntax isfile_object open(file_name ,access_modethe first argument,file_namespecifies the filename that is to be opened the second argumentaccess_modedetermines in which mode the file has to be openedthat isreadwrite and append sp_python programming
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 " +opens file for reading and writing if the file doesn' existthen new file is created examplesf open('myfile txt'' 'creates file object named capable of reading the contents of the text file named myfile txt in current directory open('myfile txt'' 'creates and returns file object named capable of writing data to the text file named myfile txt we can also use the absolute path to filename to open the file in windowsas followsf open(" :\\pybook\\myfile txt"" "creates and returns file object named capable of reading data to the text file named myfile txt in folder name python in drive open('myfile txt'' 'new data will be appended after the pre-existing data in that file writing text to file the 'wmode creates new file if the file already existsthen the file would be overwritten we will use the write(function examplefile_input open("motivation txt",' 'file_input write("never give up\ "file_input write("rise above hate\ "file_input write("no body remember second place"file_input close(sp_python programming
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 the file and return them as stringthe readline(method to read the next lineand the readlines(method to read all the lines into list of strings example to read data def main()#open file for input infile open("motivation txt"" "print("( using read():"print(infile read())#read all data infile close(close the input file open file for input infile open("motivation txt"" "print("\ ( using read(number)" =infile read( )#reads character print( infile close(close the input file #open file for input infile open("motivation txt"" "print("\ ( using readline()"line =infile readline()#reads line print(repr(line )infile close(close the input file sp_python programming
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 exceptions and continue its normal execution the run-time exceptions immediately terminate running program rather than terminating the program' executionan executing program can detect the problem when it arises and possibly execute code to correct the issue or soften it in some way this explores handling exceptions in python an error that occurs at runtime is also called an exception the run-time exceptions immediately terminate running program python provides standard mechanism called exception handling that allows the program to catch the error and prompt the user to correct the issue or soften it in some way this can be done using python' exception handling syntax the syntax for exception handling is to wrap the code that might raise (or throwan exception in try clauseas followstryexcept herecontains the code that may raise an exception when an exception occursthe rest of the code in is skipped if the exception matches an exception typethe corresponding handler is executed is the code that processes the exception exampledef divide( , )tryc / return except print ("error in divide function"print(divide( , ))#function call output error in divide function none sp_python programming
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 dictionary nameerror specified local or global name does not exist typeerror operation or function applied to an inappropriate type valueerror operation or function applied to correct type but inappropriate value zerodivisionerror second operand of divison or modulus operation is zero try with multiple except clause try statement can have more than one except clause to handle different exceptions the statement can also have an optional else and/or finally statementin syntax like thistryexcept except exceptelsefinallythe multiple excepts are similar to elifs when an exception occursit is checked to match an exception in an except clause after the try clause sequentially if match is foundthe handler for the matching case is executed and the rest of the except clauses are skipped note that the in the last except clause may be omitted if the exception does not match any of the exception types before the last except clausethe for the last except clause is executed try statement may have an optional else clausewhich is executed if no exception is raised in the try body sp_python programming
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 zerodivisionerrorprint("division by zero!"except syntaxerrorprint(" comma may be missing in the input"exceptprint("something wrong in the input"elseprint("no exceptions"finallyprint("the finally clause is executed"main(call the main function output sp_python programming
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 this action first exceptrun if exception occurs finally #always run this code the order of the statement should betry -except -else -finally exampleto demonstrate finally def main()trynum int(input("enter the number ")re /num exceptprint ("something is wrong"elseprint ("result is ",refinally print ("finally program ends"main(output enter the number result is finally program ends multithreaded programming computer programs are purely executablebinary (or otherwise)which reside on disk they do not take on life of their own until loaded into memory and invoked by the operating system process (sometimes called heavyweight processis program in execution each process has its own address spacememorya data stackand other auxiliary data to keep track of execution process switching needs interaction with operating system the operating system manages the execution of all processes on the systemdividing the time fairly between all processes processes can also fork or spawn(give birthnew processes to perform other tasksbut each new process has its own memorydata stacketc and cannot generally share information unless inter process communication (ipcis employed sp_python programming
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 sequenceand conclusion it has an instruction pointer that keeps track of where within its context it is currently running it can be pre-empted (interruptedand temporarily put on hold (also known as sleepingwhile other threads are running--this is called yielding multiple threads within process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes threads are generally executed in concurrent fashionand it is this parallelism and data sharing that enable the coordination of multiple tasks naturallythreads are scheduled in such way that they run for little bitthen yield to other threads throughout the execution of the entire processeach thread performs its ownseparate tasksand communicates the results with other threads as necessary if two or more threads access the same piece of datainconsistent results may arise because of the ordering of data access this is commonly known as race condition the thread libraries come with synchronization functions which allow the thread manager to control execution and access some threads may not be given equal and fair execution time this is because some functions block until they have completed multithreadingis the ability of cpu to manage the use of operating system by executing multiple threads concurrently the main idea of multithreading is to achieve parallelism by dividing process into multiple threads states of thread to understand the functionality of threads in depthwe need to learn about the lifecycle of the threads or the different thread states typicallya thread can exist in five distinct states the different states are shown belownew thread new thread begins its life cycle in the new state butat this stageit has not yet started and it has not been allocated any resources we can say that it is just an instance of an object runnable as the newly born thread is startedthe thread becomes runnable waiting to run in this stateit has all the resources but still task scheduler have not scheduled it to run sp_python programming
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 / request or waiting for the completion of the execution of other thread dead runnable thread enters the terminated state when it completes its task or otherwise terminates there are two different kinds of threadskernel threads user-space threads or user threads kernel threads are part of the operating systemwhile user-space threads are not implemented in the kernelcan be seen as an extension of the function concept of programming language advantages of threadingmultithreading improve the speed of computation on multiprocessor or multi-core systems because each processor or core handles separate thread concurrently multithreading allows program to remain responsive while one thread waits for input and another runs gui at the same time this statement holds true for both multiprocessor or single processor systems all the threads of process have access to its global variables if global variable changes in one threadit is visible to other threads as well thread can also have its own local variables disadvantages of threadingon single processor systemmultithreading wouldn' impact the speed of computation in factthe system' performance may downgrade due to the overhead of managing threads synchronization is required to avoid mutual exclusion while accessing shared resources of the process it directly leads to more memory and cpu utilization sp_python programming
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 "threadclass of threading module to create threads we can create threads in the following different ways creating threads without using class creating thread by creating sub class to thread class creating thread without creating sub class to thread class creating threads without using class in this method, function is created and its name is passed as target for the thread as =thread(target=function_name,[args=(arg ,arg here is the object of thread classthe target represents the function on which the thread will act the args represents tuple of arguments which are passed to the function the tread is started by calling the start(method as start(the thread will execute the function exampleimport time from threading import thread def sleepme( )print("\nthread % going to sleep for seconds itime sleep( print("\nthread % is awake now ifor in range( )th thread(target=sleepmeargs=( )th start(outputthread going to sleep for seconds thread going to sleep for seconds thread going to sleep for seconds thread going to sleep for seconds thread going to sleep for seconds thread is awake now thread is awake now thread is awake now thread is awake now thread is awake now creating thread by creating sub class to thread class by using thread class from threading modulewe can create our own class as sub class to thread classso that we can inherit the functionality of thread class by inheriting thread class we can make use all methods of thread class into sub class the thread class has sp_python programming
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 seconds itime sleep( print("\nthread % is awake now it =mythread( start( join(outputthread 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 going to sleep for seconds thread is awake now thread going to sleep for seconds thread is awake now creating thread without creating sub class to thread class we can ceate an independent class say mythread that does not inherit from thread class then create object of mythread next step is to create thread by creating object to thread class and specifying the method of the my thread class as its target as =thread(target=obj sleep,args)examplefrom threading import thread import time class mythreaddef sleep(self)for in range( , )print("thread % going to sleep for seconds itime sleep( print("thread % is awake now iobj=mythread( =thread(target=obj sleep() start(outputthread going to sleep for seconds thread is awake now thread going to sleep for seconds sp_python programming
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 execute some particular program segment known as critical section critical section refers to the parts of the program where the shared resource is accessed when thread is already acting on an objectpreventing any other thread from acting on the same object is called is called thread synchronization it is implemented using the following techniqueslocks semaphores locks are used to lock objects on which the thread is actingafter completion of executionit will unlock the object and comes out locks is created by creating object of class lock as shown below =lock(to lock the object,we should use the acquire(as axquire(to unlock or release the object,release(method is used as release****sp_python programming
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 in the real world can communicate with another object for examplea dog object in the real world has state and behavior oops is based on four pillars they arepolymorphism inheritance abstraction encapsulation class and objects key concepts classa class defines the properties and behaviors for objects class is considered as blueprint for object creation it provides template for creating an object and specifying its behavior through means of methods and state through means of variable instance name objectsan object represents an entity in the real world that can be distinctly identified an object has unique identitystateand behavior or attributes they can be considered as an instance of class for examplea studenta deska circlea buttonand even loan can all be viewed as objects inheritancein object-oriented programmingthe child class can inherit many properties from the parent class herethe child class can use an existing method or behaviorwhich the parent class has defined and use them accordingly in their class inheritance can be single inheritance or multiple inheritance single inheritanceas the name suggestsrefers to only one parentwhile multiple inheritance refers to inheriting the property from multiple parents polymorphismin oopsan object can have many forms through means of different attributes to simplifyin our casewe can understand it by methods with the same name but having different outputs abstractionherewe hide the necessary details and are only interested in showing the relevant details to the other proposed user encapsulationthis refers to hiding the necessary methods and their relevant details from the outside world class can be treated as best examplewhich provides encapsulation to the methods and relevant instances creating class creating class in python is quite easy refer to the following syntaxclass ():#statements must be indented methods the class functions are known by common namemethods in pythonmethods are defined as part of the class definition and are invoked only by an instance to call sp_python programming
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 that references the object itself using selfyou can access object' members in class definition the self is parameter that references the object itself using selfyou can access object' members in class definition the self argumentwhich must be present in all method invocations that argumentrepresents the instance objectis passed to the method implicitly by the interpreter when you invoke method via an instance for exampleyou can use the syntax self to access the instance variable and syntax self (to invoke the instance method for the object self in class to invoke the method we have to instantiate the class and call the method as follows myobj mymethod(create the instance myobj display(now invoke the method constructor (the __init__ methodhere __init__ works as the class' constructor when user instantiates the classit runs automatically class provides special method__init__ this methodknown as an initializeris invoked to initialize new object' state when it is created an initializer can perform any actionbut initializers are designed to perform initializing actionssuch as creating an object' data fields with initial values python uses the following syntax to define classclass classnameinitializer methods you can access the object' data fields and invoke its methods by using the dot operator )also known as the object member access operator exampleconstruct py import math class circleconstruct circle object def __init__(selfradius )self radius radius def getperimeter(self)return self radius math pi def getarea(self)return self radius self radius math pi def setradius(selfradius)self radius radius circle( print( radiussp_python programming
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_name(self)"""return neatly formatted descriptive name ""name str(self yearself make self model return name my_new_car car('audi'' ' print(my_new_car get_name()output audi destructor (__del__(method like constructorthere is an equivalent destructor special method called __del__(howeverdue to the way python manages garbage collection of objectsthis function is not executed until all references to an instance object have been removed destructors in python are methods which provide special processing before instances are de_allocated and are not commonly implemented since instances are rarely de_allocated explicitly example:destructor py class myclasscount use static data for count def __init__(self)constructorincr count myclass count myclass count def __del__(self)destructordecr count myclass count myclass count def howmany(self)return count return myclass count sp_python programming
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 an attribute is data or functional element which belongs to another object and is accessed via the familiar dotted-attribute notation some python types such as complex numbers have data attributes (real and imag)while others such as lists and dictionaries have methods (functional attributesclass data attributes data attributes are simply variables of the class we are defining they can be used like any other variable in that they are set when the class is created and can be updated either by methods within the class or elsewhere in the main part of the program such attributes are better known to oo programmers as static membersclass variablesor static data they represent data that is tied to the class object they belong to and are independent of any class instances class methods attributes methodin the class is simply function defined as part of class definition (thus making methods class attributesthis means that method applies only to objects (instancesof class type note is tied to its instance because invocation requires both names in the dotted notationexample:class_var py class tumkur_org()mul_num #class variable def __init__(self,first,last,pay)self f_name first class data attributes self l_name last self pay_amt pay self full_name first+"+last def make_email(self)class method attributes return self f_name"+self l_name+"@gmail comdef increment(self)self pay_amt int(self pay_amt*self mul_numreturn self pay_amt obj tumkur_org('hari''das' sp_python programming
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 in other object oriented languages like javac+etc inheritance allows us to inherit methods and attributes of the parent class by inheritancea new child class automatically gets all of the methods and attributes of the existing parent class the syntax is given as followsclass baseclass(object)pass class derivedclass(baseclass)the baseclass is the already existing (parentclassand the derivedclass is the new (childclass that inherits (or subclassesattributes from baseclass or inheritance enables you to define general class ( superclassand later extend it to more specialized classes (subclassesexample:simple_inheritance py class rectangle()def __init__(selfwh)self self def area(self)return self self class square(rectangle)def __init__(selfl, )call parent constructor super(__init__(lbself = self = sp_python programming
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 call the __init__method of rectangle classessentially calling any overridden method of the base class when invoking method using super()don' pass self in the argument types of inheritancesingle inheritance multiple inheritances in multiple inheritance subclass inherited from more than one parent class and is able to access functionality from both of them syntaxclass avariable of class functions of class class bvariable of class functions of class class (ab)class inheriting property of both class and add more properties to class multilevel inheritance class aproperties of class class ( )class inheriting property of class properties of class class ( )class inheriting property of class class also inherits properties of class properties of class sp_python programming
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("in class " + return class ( )def sum (self, , )print("in class "ca* + * return a_obj= (print(a_obj sum ( , )b_obj (print(b_obj sum ( , )outputin class in class in the preceding exampleclasses and both have the same method sum (with different implementations namespace namespace is mapping from names to objects examples are the set of built-in names (containing functions that are always accessible for free in any python program)the global names in moduleand the local names in function even the set of attributes of an object can be considered namespace the namespaces allow defining and organizing names with claritywithout overlapping or interference for examplethe namespace associated with that book we were looking for in the library can be used to import the book itselflike thisfrom library second_floor section_x row_three import book we start from the library namespaceand by means of the dot operatorwe navigate that namespace within this namespacewe look for second_floorand again we navigate with dotoperator we then walk into section_xand finally within the last namespacerow_threewe find the name we were looking forbook regular expressions the regular expression module regular expression is compact notation for representing collection of strings what makes regular expressions so powerful is that single regular expression can represent an unlimited number of strings-sp_python programming
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 five main purposesparsingidentifying and extracting pieces of text that match certain criteria--regexes are used for creating ad hoc parsers and also by traditional parsing tools searchinglocating substrings that can have more than one formfor examplefinding any of "pet png""pet jpg""pet jpeg"or "pet svgwhile avoiding "carpet pngand similar searching and replacingreplacing everywhere the regex matches with stringfor examplefinding "bicycleor "human powered vehicleand replacing either with "bikesplitting stringssplitting string at each place the regex matchesfor examplesplitting everywhere colon-space or equals ("or "="occurs validationchecking whether piece of text meets some criteriafor examplecontains currency symbol followed by digits the python package python modules are single filewhereas python package is collection of modules package is directory that contains python modules package is module that contains other modules some or all of the modules in package may be sub packagesresulting in hierarchical tree-like structure namespace is mapping from names to objects examples are the set of built-in names (containing functions that are always accessible for free in any python program)the global names in moduleand the local names in function even the set of attributes of an object can be considered namespace the namespaces allow defining and organizing names with claritywithout overlapping or interference for examplethe namespace associated with that book we were looking for in the library can be used to import the book itselflike thisfrom library second_floor section_x row_three import book we start from the library namespaceand by means of the dot operatorwe navigate that namespace within this namespacewe look for second_floorand again we navigate with dotoperator we then walk into section_xand finally within the last namespacerow_threewe find the name we were looking forbook ****sp_python programming
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 introduced by codd in relational database modela table is collection of data elements organised in terms of rows and columns table is the simplest form of data storage rdbms is used to manage relational database relational database is collection of organized set of tables related to each otherand from which data can be accessed easily what makes up databasethe main components of an rdbms area the database server the database tables records and fields primary key schema the database serverthe databaseand table the database server the database server is the actual server process running the databases it controls the storage of the datagrants access to usersupdates and deletes recordsand communicates with other servers the database server is normally on dedicated host computerserving and managing multiple clients over networkbut can also be used as standalone server on the local host machine to serve single client ( you sp_python programming
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 program using php built-in functions to make requests to the mysql database server the database database is collection of related data elementsusually corresponding to specific application the databases are listed as "mysql,"northwind,"phpmyadmin,and "test the tables each database consists of two-dimensional tables in facta relational database stores all of its data in tables all operations are performed on the tablewhich can then produce other tablesand so on during designing database first we create tables and relate these tables to one another in some way for examplea typical database for an organization might consist of tables for customersordersand products and all these tables are related to one another the records and fields table has name and consists of set of rows and columns it resembles spread-sheet where each rowalso called record each table in database contains zero or more records the vertical columnsalso called fields or attributes and has names all rows from the same table have the same set of columns remembera relational database manipulates only tables and the result of all operations are also tables you can view the database itself as set of tables you can also perform number of other operations on tables and also between two tables by treating them as setsyou can join information from two tablesmake cartesian products of the tablesget the intersection between two tablesadd one table to anotherand so on sql allows you to "talkto database data type can be numbera charactera datea time stampand so on the terms "rowand "recordare often interchangeableas are "columnand "field the primary key and indexes primary key is unique identifier for each record these identifiers are unique in the world of database tableswe call the unique identifier primary key although it is good idea to have primary keynot every table has one the primary key is determined when the table is created the database schema database design is science and requires understanding how the relational model is implemented the term database schemawhich refers to the structure of the database it describes the design of the database similar to template or blueprintit describes all the tablesand their layoutbut does not contain the actual data in the database connecting to the database sp_python programming
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 how to use the sql language the version of sql used by mysql follows the ansi (american national standards institutestandardmeaning that it must support the major keywords ( selectupdatedeleteinsertwhereetc as defined in the standard as you can see by the names of these keywordssql is the language that makes it possible to manipulate the data in database first we have to install database server and run it there are number of client applications available to connect to the database serverthe most popular and most widely available being the mysql command-line client and also phpmyadmin in case of xamp or wamp regardless of the type of client you chooseyou will always need to specify the usernameand the host we are connecting to to connect to database using the clientwe have to enter information similar to the following line mysql userrootpassword =my_password host=localhost once you are successfully connectedyou will get the mysqlprompt this means we are connected to the mysql database server and not to local computer' operating system mysql data types when creating table in databasethe type and size of each field must be defined field is similar to php variable except that it can store only the specified type and size of data in given field mysql supports three main groups of data typesnumericdate/timeand string for full details see the mysql manual at numeric data types you can store numbers in mysql in many waysas shown by the following table choose the data type most suited for the type of numbers needed to store in table type max value (signed/unsignedtinyint smallint , to , mediumint / to if unsigned , , , , or to if unsigned int , , , , , , bigint , , , , , , to , , , , , , float float smallest non zero value+ largest value+ smallest non zero value+ sp_python programming
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 range of values date date jan to dec datetime date and time midnight jan to : : dec timestamp timestamp : : jan to : : jan utc (universal coordinated timetime time : : to : : year year to string data types mysql allows storing text or binary strings of data in many different waysas shown in the following tablestring data type description allowed lengths charn fixed length string of characters characters varcharn variable length string of up to characters characters binaryn fixed length binary string of bytes bytes varbinarynvariable length binary string of up to bytes bytes mediumtext medium sized text field characters sp_python programming
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 institutestandard computer languagedesigned to be as close to the english language as possiblemaking it an easy language to learn popular database management systems such as oraclesybaseand microsoft sql serverall use sql to actually work with databases and tableswe sql statements commonly used statements includethese sql commands are mainly categorized into three categories as discussed belowdata definition language (ddl)ddl or data definition language actually consists of the sql commands that can be used to define the database schema it simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in database examples of ddl commandscreateis used to create the database or its objects (like tableindexfunctionviewsstore procedure and triggersdropis used to delete objects from the database alteris used to alter the structure of the database truncateis used to remove all records from tableincluding all spaces allocated for the records are removed commentis used to add comments to the data dictionary renameis used to rename an object existing in the database data manipulation language (dml)the sql commands that deals with the manipulation of data present in database belong to dml or data manipulation language and this includes most of the sql statements examples of dmlsp_python programming
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 rightspermissions and other controls of the database system examples of dcl commandsgrantgives user' access privileges to database revokewithdraw user' access privileges given by using the grant command commitcommits transaction rollbackrollbacks transaction in case of any error occurs savepointsets save point within transaction set transactionspecify characteristics for the transaction creating table tables are where we actually store your data to start withto create very simple tablefruitcontaining three fieldsid (the primary key)name (the name of the fruit)and color (the fruit' colorthe first thing to do is select the database just created once you database are selectedany database manipulation commands entered works on that database type the followinguse mydatabasepress enterand we seedatabase changed mysql now to create table type the following at the mysql promptmysql create table fruit (id smallint unsigned not null auto_incrementname varchar( not nullcolor varchar( not nullprimary key (id)after successful execution of command we get messagequery ok rows affected ( secto see list of tables in the databaseuse the show tables commandmysql show tablessp_python programming
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 inserts values into each of the fields of the tablein the order that the fields were created to insert row of partial datauseinsert into table field field values value value )so you can add three rows to the fruit table by inserting data into just the name and color fields (the id field will be filled automatically)mysql >insert into fruit(namecolorvalues('banana''yellow')query ok row affected ( secmysql >insert into fruit (namecolorvalues('tangerine''orange)query ok row affected ( secmysql insert into fruit (namecolor values ('plum','purple)query ok row affected ( secmysql reading data from table to read data in sqlwe create query using the select statement to retrieve list of all the data in your fruit tableyou can usetypical form of mysql select statementwhich retrieves records from table operations performed with select are known as queries (hence the name "structured query language")select field field fieldn from table where condition to retrieve list of all the data in fruit tablewe can usemysql select from fruitsp_python programming
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 python using pip use the mysql connector connect(method of mysql connector python with required parameters to connect mysql use the connection object returned by connect(method to create cursor object to perform database operations the cursor execute(to execute sql queries from python close the cursor object using cursor close(and mysql database connection using connection close(after your work completes catch exception if any that may occur during this process creating connection object nowwe are ready to issue commands interacting with the database many sql commands can be issued using single function ascursor execute(closing the database after all changes have been committedwe can then close the databasemydb close(python mysql database connection program import mysql connector this line imports the mysql connector python module in to program and we can use this module' api to connect mysql from mysql connector import error mysql connector error object is used to show us an error when we failed to connect databases or if any other database error occurred while working with the database example er_access_denied_error when username or password is wrong mysql connector connect(using this function we can connect the mysql databasethis function accepts four required parametershostdatabaseuser and password that we already discussed sp_python programming
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 (function can throw an exceptioni database error if one of the required parameters are wrong for exampleif you provide database name that is not present in mysqlthen python application throws an exception so check the arguments that you are passing to this function the syntax for calling the connect(function and assigning the results to variable is as follows[variablemysqldb connect([hostname][username][password][database name]we can assign values these variables as shown but it is not requiredbut it is good practice until you get used to the format of the function call so we can use the following format to call the connect(function[variablemysqldb connect(host="[hostname]"user="[username]"passwd="[password]"db="[database name]"or (in case of mysql db[variablemysql connector connect (host="[hostname]"user="[username]"passwd="[password]"db="[database name]"conn is_connected(is_connected(is the function of the mysqlconnection class through which we can verify is our python application connected to mysql creating cursor objectusing cursor objectwe can execute sql queries the mysql cursor class instantiates objects that can execute operations such as sql statements cursor objects interact with the mysql server using mysqlconnection object after the connection object is createdcursor object allows to interact with the database the point of cursor is to mark place and to allows to issue commands to the computer cursor in mysql for python serves as python-based proxy for the cursor in mysql shell sessionwhere mysql would create the real cursor for us if we logged into mysql database to create the cursorwe use the cursormethod of the mysqldb connections object we created for the connection the syntax is as follows[cursor name[connection object namecursor(examplecursor mydb cursor(cursor close(using cursor' close method we can close the cursor object once we close the cursor objectwe can not execute any sql statement connection close(at lastwe are closing the mysql database connection using close(function of mysqlconnection class sp_python programming
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 object through which queries can be executed db rollback(rolls back any pending transaction to the state that existed before the transaction begandoes nothing for databases that don' support transactions db arraysize the (readable/writablenumber of rows that fetchmany(will return if no size is specified db close(closes the cursorcthis is done automatically when the cursor goes out of scope db description( read-only sequence of -tuples (nametype_codedisplay_sizeinternal_sizeprecisionscalenull_ok)describing each successive column of cursor db execute executes the sql query in string sqlreplacing each placeholder with the corresponding parameter from the params sequence or mapping if given (sql,paramsdb executemany (sql,seq_of_paramsexecutes the sql query once for each item in the seq_of_params sequence of sequences or mappingsthis method should not be used for operations that create result sets (such as select statementsdb fetchall(returns sequence of all the rows that have not yet been fetched (which could be all of themdb fetchmany(sizereturns sequence of rows (each row itself being sp_python programming
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 applicable exampleimport mysql connector conn=mysql connector connect(host='localhost',database='test',user='ro ot',password=''cur=conn cursor(str='''create table if not exists examplesid int( not null auto_incrementdescription varchar( )primary key (id))''cur execute(strstr ='insert into examples(descriptionvalues ("hello world")cur execute(str str ='insert into examples(descriptionvalues ("tumkur")cur execute(str conn commit(cur execute("select from examples"row=cur fetchall(print("total row=",cur rowcountfor in rowprint(rcur close(conn close(outputtotal row ( 'hello world'( 'tumkur'sp_python programming
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 application by adding picturescolorsmenusanimation it is possible to simulate the real life objects using gui gui helps to create graphical components like push buttonradio buttoncheck boxtext boxmenus etc gui in pythonpython offers tkinter module to create graphical programs the tkinter represents 'toolkit interfacefor gui this is interface for python programmers that enable them to the classes of tk module of tcl/tk [tool command languagetcl language use tk[tool kitlanguage to generate graphics general steps involved in basic gui programs create root windowthe root window is the top level window that provides rectangular space on the screen where we can display textcolorimagesetc first import tkinter module from tkinter import root=tk(create root window object create canvas frame canvas and frame are child windows in the root window =canvas(rootbg='blue'height= ,width= ,cursor='pencil'cursors are circlehand hand heartpencilplusmousestarwatch etc create widgets components for canvas create linecirclerectangleany geometric objects for frame buttonstext boxlist check box etc create event handler write the function for corresponding event wap to draw lineovalpolygonrectangle and text from tkinter import root=tk(root title ("my window"#root geometry (" " =canvas(root,bg="blue",height= ,width= ,cursor='pencil'id= create_line( , , , , , ,width= ,fill="white"id= create_oval( , , , ,width= ,fill="yellowactivefill="blue"id= create_polygon( , , , , , ,width= ,fill="green",outline="red",activefill="pink"id= create_rectangle( , , , ,width= ,fill="gray",outline="yellow",activefill="green"fnt=('times', ,'bold italic underline'id= create_text( , ,text="python graphics"font=fntfill="white"activefill="red" pack(root mainloop(sp_python programming
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 ground color to be displayed and 'cursorindicates the type of the cursor to be displayed in the frame once the frame is createdit should be added to the root window using the pack(method widgetsform elementswidgets is gui component that is displayed on the screen and can perform task as designed by the user the widgets are button label text box message checkbox list box option button scroll bars menus steps to create widgets create widget object =button(ftext="submit" define the event performed by the widget def buttonclick(selfprint("you have clicked submit button" clicking event should be linked with the callback handler bind(''buttonclick call event loop root mainloop( buttona push button is component that performs some action when clicked these buttons are created as objects of button class asb=button(ftext="ok"width= ,height= bg="yellow"fg="blue"here'bis the object of button class'frepresents the frame for which the button is created as child the 'textoption represents the text to be display on the buttonwidth and height represents the size of the button'bgrepresents the background color and 'fgrepresents the fore ground color of the buttonb bind(""buttonclickwe link the mouse left button with the buttonclick)method using bind()method texta text widget is same as label but text widget has several options and can display multiple lines of text in different colors and fonts it is possible to insert text into text widgetmodify it or delete it we can also display images in the text widget text is created as an object of text class ast=text( ,width= height= font=('times', ,'italic')fg='blue'bg="yellow"wrap=wordhere'tis the object of text class'frepresents the frame for which the text is created as child the width and height represents the size of the text box'bgrepresents the background color and 'fgrepresents the fore ground color of the text'font represents tuple that contains font namesize and style the 'wraprepresents the text information can be align with in the text box labela label represents the constant text that is displayed in the frame or container label can display one or more lines of text that cannot be modified label is created as an object of label class asl=label(ftext=label fg='blue',bg='yellow'sp_python programming demo",width= ,height= font=('times', ,'bold')
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 unit end exercise objectives after reading through this you will be able to to understand and use the basic of python to understand the history and features of python programming to understand the installation of python to handle the basis errors in python to understand the difference between bracketsbraces and parenthesis introductionprogramming language the python python is an object-orientedhigh level languageinterpreteddynamic and multipurpose programming language python is not intended to work on special area such as web programming that is why it is known as multipurpose because it can be used with webenterprise cad etc
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 the national research institute for mathematics and computer sciencenetherlands though the language was introduced in the development began in the previouslyvan rossum worked on the abc language at centrumwiskunde informatica (cwiin the netherlands the abc language was capable of exception handling and interfacing with the amoeba operating system inspired by the languagevan rossum first tried out making his own version of it python is influenced by programming languages likeabc languagemodula- python is used for software development at companies and organizations such as googleyahoocernindustrial light and magicand nasa why the name pythonpython developerrossum always wanted the name of his new language to be shortuniqueand mysterious inspired by monty python' flying circusa bbc comedy serieshe named it python features there are lot of features provided by python programming language as follows easy to codepython is very developer-friendly language which means that anyone and everyone can learn to code it in couple of hours or days as compared to other object-oriented programming languages like javacc++and #python is one of the easiest to learn open source and freepython is an open-source programming language which means that anyone can create and contribute to its development python has an online forum where thousands of coders gather daily to improve this language further along with this python is free to download and use in any operating systembe it windowsmac or linux
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 developers object-oriented approachone of the key aspects of python is its object-oriented approach this basically means that python recognizes the concept of class and object encapsulation thus allowing programs to be efficient in the long run highly portablesuppose you are running python on windows and you need to shift the same to either mac or linux systemthen you can easily achieve the same in python without having to worry about changing the code this is not possible in other programming languagesthus making python one of the most portable languages available in the industry highly dynamic python is one of the most dynamic languages available in the industry today what this basically means is that the type of variable is decided at the run time and not in advance due to the presence of this featurewe do not need to specify the type of the variable during codingthus saving time and increasing efficiency large standard libraryout of the boxpython comes inbuilt with large number of libraries that can be imported at any instance and be used in specific program the presence of libraries also makes sure that you don' need to write all the code yourself and can import the same from those that already exist in the libraries installing python to install pythonfirstly download the python distribution from official website of python (www python orgdownloadhaving downloaded the python distribution now execute it setting path in python
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 python program using command promptif you want to create python file in py extension and run you can use the windows command prompt to execute the python code examplehere is the simple code of python given in the python file demo py it contains only single line code of python which prints the text "hello world!on execution sohow you can execute the python program using the command prompt to see thisyou have to first open the command prompt using the 'window+rkeyboard shortcut nowtype the word 'cmdto open the command prompt this opens the command prompt with the screen as given below change the directory location to the location where you have just saved your python py extension file we can use the cmd command 'cdto change the directory location use 'cd to come out of directory and "cdto come inside of the directory get the file location where you saved your python file to execute the python fileyou have to use the keyword 'pythonfollowed by the file name with extension py see the example given in the screen above with the output of the file
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 contains the print program of python press the enter button to execute the print code of python the output gives the text "hello world!after you press the enter button type any code of python you want to execute and run directly on interactive mode
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 with the python shell the file looks like the image given below
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 python idle debugging debugging means the complete control over the program execution developers use debugging to overcome program from any bad issues debugging is healthier process for the program and keeps the diseases bugs far away python also allows developers to debug the programs using pdb module that comes with standard python by default we just need to import pdb module in the python script using pdb modulewe can set breakpoints in the program to check the current status
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 debugging syntax error occurs when we do not use properly defined syntax in any programming language for exampleincorrect argumentsindentationuse of undefined variables etc exampleage= if age> print ("you can vote"syntax error because of not using indentation else print ("you cannot vote"#syntax error because of not using indentation runtime errorsthe second type of error is runtime errorso called because the error does not appear until after the program has started running these errors are also called exceptions because they usually indicate that something exceptional (and badhas happened some examples of python runtime errorsdivision by zero performing an operation on incompatible types using an identifier which has not been defined accessing list elementdictionary value or object attribute which doesn' exist trying to access file which doesn' exist semantic errorsthe third type of error is the semantic error if there is semantic error in your programit will run successfully in the sense that the computer will not generate any error messagesbut it will not do the right thing it will do something else the problem is that the program you wrote is not the program you wanted to write the meaning of the program (its semanticsis wrong identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing
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 for some peopleprogramming and debugging are the same thing that isprogramming is the process of gradually debugging program until it does what you want the idea is that you should start with program that does something and make small modificationsdebugging them as you goso that you always have working program formal and natural languages natural languages are the languages people speaksuch as englishspanishand french they were not designed by people (although people try to impose some order on them)they evolved naturally formal languages are languages that are designed by people for specific applications for examplethe notation that mathematicians use is formal language that is particularly good at denoting relationships among numbers and symbols chemists use formal language to represent the chemical structure of molecules programming languages are formal languages that have been designed to express computations formal languages tend to have strict rules about syntax for example is syntactically correct mathematical statement syntax rules come in two flavorspertaining to tokens and structure tokens are the basic elements of the languagesuch as wordsnumbersand chemical elements the second type of syntax rule pertains to the structure of statementthat isthe way the tokens are arranged the statement is illegal because even though and are legal tokensyou can' have one right after the other the difference between bracketsbracesand parenthesesbrackets ]brackets are used to define mutable data types such as list or list comprehensions
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'mumbaistr [ 'mexampleto slice string str [ : 'umbbraces {curly braces are used in python to define set or dictionary examplecreate set with three elements , , { , , type( examplecreate dictionary with two elements with keys'rollnoand 'named {'rollno': 'name':vivek'type( brackets can be used to access the value of dictionary element by specifying the key ['rollno'
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 function definition def mul( ,bformal parameters are specified using parentheses in the function call =mul ( , actual values are specified using parenthesis summary in this we studied introductionhistoryfeatures of python programming language 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 in this we are more focused on types of errors in python like syntax errorruntime errorsemantic error and experimental debugging execution of python program using command prompt and interactive mode to execute python program alsowe studied difference between bracketsbracesand parentheses in python references www journaldev com www edureka com www tutorialdeep com
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 ability to search the python documentation for exampleif you enter print in the search windowthe first link that appears is the documentation of the print statement at this pointnot all of it will make sense to youbut it is good to know where it is start the python interpreter and type help (to start the online help utility or you can type help ('print'to get information about the print statement ****
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 after reading through this you will be able to to understand and use the basic datatypes of python to understand the type conversion of variables in python programming to understand the operators and operands in python to understand the interactive mode and script mode in python to understand the order of operations in python introduction variables in computer program are not quite like mathematical variables they are placeholders for locations in memory memory values consists of sequence of binary digits (bitsthat can be or so all numbers are represented internally in base names of variables are chosen by the programmer
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 works withlike letter or number the values we have seen so far are and 'helloworld!these values belong to different types is an integerand 'helloworld!is stringso-called because it contains "stringof letters youcan identify strings because they are enclosed in quotation marks if you are not sure what type value hasthe interpreter can tell you type ('helloworld!'type ( not surprisinglystrings belong to the type str and integers belong to the type int less obviouslynumbers with decimal point belong to type called floatbecause these numbers are represented in format called floating-point type ( what about values like ' and ' 'they look like numbersbut they are in quotation marks like strings type (' 'type (' 'they are strings variablesone of the most powerful features of programming language is the ability to manipulate variables variable is name that refers to value an assignment statement creates new variables and gives them valuesmessage 'welcome to university of mumbain pi the above example makes three assignments the first assigns string to new variable named messagethe second gives the integer to nthe third assigns the (approximatevalue of to pi
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 they can contain both letters and numbersbut they have to begin with letter it is legal to use uppercase lettersbut it is good idea to begin variable names with lowercase letter the underscore character_can appear in name it is often used in names with multiple wordssuch as my_name or airspeed_of_unladen_swallow if you give variable an illegal nameyou get syntax error mumbai'big citysyntaxerrorinvalid syntax more syntaxerrorinvalid syntax class 'advanced pythonsyntaxerrorinvalid syntax mumbai is illegal because it does not begin with letter moreis illegal because it contains an illegal characterbut what' wrong with classit turns out that class is one of python' keywords the interpreter uses keywords to recognize the structure of the programand they cannot be used as variable names python has lot of keywords the number keeps on growing with the new features coming in python python is the current version as of writing this book there are keywords in python release we can get the complete list of keywords using python interpreter help utility python help (helpkeywords
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 if it is on this list 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 conversionin implicit type conversionpython automatically converts one data type to another data type this process doesn' need any user involvement example where python promotes the conversion of the lower data type (integerto the higher data type (floatto avoid data loss example converting integer to float num_int num_flo num_new num_int num_flo print ("datatype of num_int:"type(num_int)print ("datatype of num_flo:"type(num_flo)print ("value of num_new:"num_newprint ("datatype of num_new:"type(num_new)when we run the above programthe output will bedatatype of num_intdatatype of num_flovalue of num_new datatype of num_new
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 always converts smaller data types to larger data types to avoid the loss of data example addition of string(higherdata type and integer(lowerdatatype 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_strwhen we run the above programthe output will bedata 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 variables num_int and num_str as we can see from the outputwe got typeerror python is not able to use implicit conversion in such conditions howeverpython has solution for these types of situations which is known as explicit conversion explicit type conversionin 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 syntax(expressiontypecasting can be done by assigning the required data type function to the expression
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 we run the above programthe output will bedata 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 sumin the above programwe add num_str and num_int variable we converted num_str from string(higherto integer(lowertype using int(function to perform the addition after converting num_str to an integer valuepython is able to add these two variables we got the num_sum value and data type to be an integer operators and operandsoperators are particular symbols which operate on some values and produce an output the values are known as operands example + = here and are operands and (+)(=signs are the operators they produce the output python supports the following operatorsarithmetic operators
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 powerarithmetic operator examples + - * / % ** // relational operatorsoperators <>=!description less than greater than less than or equal to greater than or equal to equal to not equal to
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 examplesa= > and > print(atrue = > or < print(btrue =not( > print(cfalse membership operatorsoperators in not in description returns true if variable is in sequence of another variableelse false returns true if variable is not in sequence of another variableelse false
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 returns true if identity of two operands are not sameelse false identity operators examples = = if ( is )print ("ab has same identity"elseprint ("ab is different" = if ( is not )print ("ab has different identity"elseprint ("ab has same identity"ab has same identity ab has different identity
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 statementprint and assignment technically an expression is also statementbut it is probably simpler to think of them as different things the important difference is that an expression has valuea statement does not interactive mode and script modeone of the benefits of working with an interpreted language is that you can test bits of code in interactive mode before you put them in script but there are differences between interactive mode and script mode that can be confusing for exampleif you are using python as calculatoryou might type miles miles the first line assigns value to milesbut it has no visible effect the second line is an expressionso the interpreter evaluates it and displays the result so we learn that marathon is about kilometers but if you type the same code into script and run ityou get no output at all in script mode an expressionall by itselfhas no visible effect python actually evaluates the expressionbut it doesn' display the value unless you tell it tomiles print (miles this behavior can be confusing at first script usually contains sequence of statements if there is more than one statementthe results appear one at time as the statements execute for example
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 rulesparentheses have the highest precedence and can be used to force an expression to evaluate in the order you want since expressions in parentheses are evaluated first ( - is and ( + )**( - is you can also use parentheses to make an expression easier to readas in (minute even if it doesn' change the result exponentiation has the next highest precedenceso ** + is not and * ** is not multiplication and division have the same precedencewhich is higher than addition and subtractionwhich also have the same precedence so * - is not and + / is not operators with the same precedence are evaluated from left to right (except exponentiationsoin the expression degrees pithe division happens first and the result is multiplied by pi to divide by pyou can use parentheses or write degrees pi example for operator precedence / +( + = = = ( + )*( + )- ( + )* + - + **
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 like arithmeticlogicalrelational and membership operators focuses on interactive mode and script mode in python and order of operations unit end exercise assume that we execute the following assignment statementswidth height delimiter for each of the following expressionswrite the value of the expression and the type (of the value of the expression width/ width/ height/ delimiter
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 square of number write program that takes three numbers and prints their sum every number is given on separate line references think python by allen downey st edition python programming for beginners by prof rahul boratedr sunil khilariprof rahul navale www programiz com www itvoyagers in ****
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 objectives after reading through this you will be able to to understand and use the conditional statementsin python to understand the loop control in python programming to understand the control statements in python to understand the concepts of python and able to apply it for solving the complex problems introduction in order to write useful programswe almost always need the ability to check conditions and change the behavior of the program accordingly conditional statements give us this ability the simplest form is the if statementif print ' is positive
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 occasionallyit is useful to have body with no statements in that caseyou can use the pass statementwhich does nothing if pass need to handle negative values conditional statements conditional statement in python perform different computations or actions depending on whether specific boolean constraint evaluates to true or false conditional statements are handled by if statements in python story of two if'sconsider the following if statementcoded in -like languageif ( qp nowlook at the equivalent statement in the python languageif qp= = what python adds what python removes parentheses are optional if ( if end-of-line is end of statement -like languages python language = end of indentation is end of block why indentation syntaxa few special cases print (
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 body starts with an indentation and the first unindented line marks the end python interprets interpreted as false non-zero values as true none and are examplepython if statement if the number is positivewe print an appropriate message num if num print (num"is positive number "print ("this is always printed "num - if num print (num"is positive number "print ("this is also always printed "when you run the programthe output will be is positive number this is always printed this is also always printed in the above examplenum is the test expression the body of if is executed only if this evaluates to true when the variable num is equal to test expression is true and statements inside the body of if are executed if the variable num is equal to - test expression is false and statements inside the body of if are skipped the print(statement falls outside of the if block (unindentedhenceit is executed regardless of the test expression
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 positive or negative and displays an appropriate message num try these two variations as well num - num if num > print ("positive or zero"elseprint ("negative number"outputpositive or zero in the above examplewhen num is equal to the test expression is true and the body of if is executed and the body of else is skipped if num is equal to - the test expression is false and the body of else is executed and the body of if is skipped if num is equal to the test expression is true and body of if is executed and body of else is skipped if elif else statementsyntax if test expressionbody of if elif test expressionbody of elif elsebody of else
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 the if block can have only one else block but it can have multiple elif blocks example of if elif else'''in this programwe check if the number is positive or negative or zero and display an appropriate message''num try these two variations as wellnum num - if num print ("positive number"elif num = print("zero"elseprint ("negative number"when variable num is positivepositive number is printed if num is equal to zero is printed if num is negativenegative number is printed nested if -elsewe can have if elif else statement inside another if elif else statement this is called nesting in computer programming any number of these statements can be nested inside one another indentation is the only way to figure out the level of nesting they can get confusingso they must be avoided unless necessary python nested if example '''in this programwe input number check if the number is positive or negative or zero and display
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 sequentiallythe first statement in function is executed firstfollowed by the secondand so on there may be situation when you need to execute block of code several number of times programming languages provide various control structures that allow for more complicated execution paths loop statement allows us to execute statement or group of statements multiple times for loopthe for loop in python is used to iterate over sequence (listtuplestringor other iterable objects iterating over sequence is called traversal syntax of for loop for val in sequencebody of for
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 numbers numbers [ variable to store the sum sum iterate over the list for val in numberssum sum+val print ("the sum is"sumwhen you run the programthe output will bethe sum is the range (functionwe can generate sequence of numbers using range (function range ( will generate numbers from to ( numberswe can also define the startstop and step size as range (startstop,step_sizestep_size defaults to start to and stop is end of object if not provided this function does not store all the values in memoryit would be inefficient soit remembers the startstopstep size and generates the next number on the go to force this function to output all the itemswe can use the function list(exampleprint(range( )print(list(range( ))print (list (range ( ))print (list (range ( ))outputrange ( [ [ [
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))print (" like"city[ ]outputi like pune like mumbai like delhi for loop with elsea for loop can have an optional else block as well the else part is executed if the items in the sequence used in for loop exhausts the break keyword can be used to stop for loop in such casesthe else part is ignored hencea for loop' else part runs if no break occurs exampledigits [ for in digitsprint(ielseprint("no items left "when you run the programthe output will be no items left herethe for loop prints items of the list until the loop exhausts when the for-loop exhaustsit executes the block of code in the else and prints no items left this for else statement can be used with the break keyword to run the else block only when the break keyword was not executed exampleprogram to display student' marks from record student_name 'soyujmarks {'ram' 'shayam' 'sujit'
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 iterate beforehand syntax of while loop in python while test_expressionbody of while in the while looptest expression is checked first the body of the loop is entered only if the test_expression evaluates to true after one iterationthe test expression is checked again this process continues until the test_expression evaluates to false in pythonthe body of the while loop is determined through indentation the body starts with indentation and the first unindented line marks the end python interprets any non-zero value as true none and are interpreted as false examplepython while loop program to add natural numbers up to sum + + + to take input from the usern int (input ("enter ") initialize sum and counter sum = while <nsum sum + update counter
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 do so will result in an infinite loop (never-ending loopwhile loop with elsesame as with for loopswhile loops can also have an optional else block the else part is executed if the condition in the while loop evaluates to false the while loop can be terminated with break statement in such casesthe else part is ignored hencea while loop' else part runs if no break occurs and the condition is false example'''example to illustrate the use of else statement with the while loop''counter while counter print ("inside loop"counter counter elseprint ("inside else"outputinside loop inside loop inside loop inside else herewe use counter variable to print the string inside loop three times on the fourth iterationthe condition in while becomes false hencethe else part is executed nested loopsloops can be nested in python similar to nested loops in other programming languages
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 for loop inside it in above situation inside for loop will finish its execution first and the control will be returned back to outside for loop syntax for iterator in iterablefor iterator in iterable statement(sof inside for loop statement(sof outside for loop in this first for loop will initiate the iteration and later second for loop will start its first iteration and till second for loop complete its all iterations the control will not be given to first for loop and statements of inside for loop will be executed once all iterations of inside for loop are completed then statements of outside for loop will be executed and next iteration from first for loop will begin example of nested for loop in pythonfor in range ( , )for in range ( , ) = * print (mend='print ("table of "ioutput table of table of table of table of table of table of table of table of
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 outside while loop syntax while expressionwhile expression statement(sof inside while loop statement(sof outside while loop in this first while loop will initiate the iteration and later second while loop will start its first iteration and till second while loop complete its all iterations the control will not be given to first while loop and statements of inside while loop will be executed once all iterations of inside while loop are completed than statements of outside while loop will be executed and next iteration from first while loop will begin it is also possible that if first condition in while loop expression is false then second while loop will never be executed example program to show nested while loop =
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 loop as soon as the condition is fulfilled instead of doing the remaining iterations it reduces execution time whenever the controller encountered break statementit comes out of that loop immediately syntax of break statement for element in sequenceif conditionbreak examplefor num in range ( )if num print ("stop processing "break print(numoutput stop processing skipping specific conditionsthe continue statement is used to skip the current iteration and continue with the next iteration syntax of continue statementfor element in sequenceif conditioncontinue
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 nested loop studied how to control the loop using break and continue statements in order to skipping specific condition and terminating loops unit end exercise print the squares of numbers from to using loop control write python program to print the prime numbers of up to given numberaccept the number from the user write python program to print the following pattern write python program to construct the following patternusing nested for loop ****************
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 - to - using for loop print the following pattern ************ references think python by allen downey st edition python programming for beginners by prof rahul boratedr sunil khilariprof rahul navale www programiz com ****
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 valuesincremental development boolean functions more recursionleap of faithchecking types summary references unit end exercise objectives after reading through this you will be able to to understand and use the function calls to understand the type conversion functions to understand the math function to adding new function to understand the parameters and arguments to understand the fruitful functions and void functions to understand the boolean functionsrecursionchecking types etc introduction one of the core principles of any programming language is"don' repeat yourselfif you have an action that should occur many
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 group of related statements that performs specific task functions help break our program into smaller and modular chunks as our program grows larger and largerfunctions make it more organized and manageable furthermoreit avoids repetition and makes the code reusable syntax of function def function_name(parameters)"""docstring""statement(sabove shown is function definition that consists of the following components keyword def that marks the start of the function header function name to uniquely identify the function function naming follows the same rules of writing identifiers in python parameters (argumentsthrough which we pass values to function they are optional colon (:to mark the end of the function header optional documentation string (docstringto describe what the function does one or more valid python statements that make up the function body statements must have the same indentation level (usually spaces an optional return statement to return value from the function exampledef greeting(name)""this function greets to the person passed in as
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 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 conversionin implicit type conversionpython automatically converts one data type to another data type this 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 example converting integer to float num_int num_float num_new num_int num_float print ("datatype of num_int:"type(num_int)print ("datatype of num_float:type(num_float)print ("value of num_new:"num_newprint ("datatype of num_new:"type(num_new)outputdatatype of num_intdatatype of num_floatvalue of num_new datatype of num_new
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 variables num_int and num_str as we can see from the outputwe got typeerror python is not able to use implicit conversion in such conditions howeverpython has solution for these types of situations which is known as explicit conversion explicit type conversionin 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 syntax(expressionexample addition of string and integer using explicit conversion 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
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 performed by the python interpreter python avoids the loss of data in implicit type conversion explicit type conversion is also called type castingthe data types of objects are converted using predefined functions by the user in type castingloss of data may occur as we enforce the object to specific data type math functions the math module is standard module in python and is always available to use mathematical functions under this moduleyou have to import the module using import math for example square root calculation import math math sqrt( functions in python math module pi is well-known mathematical constantwhich is defined as the ratio of the circumference to the diameter of circle and its value is import math math pi another well-known mathematical constant defined in the math module is it is called euler' number and it is base of the natural logarithm its value is import math math
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 angle from degrees to radians and vice versa import math math radians( math degrees(math pi/ math log(the math log(method returns the natural logarithm of given number the natural logarithm is calculated to the base import math math log( math exp(the math exp(method returns float number after raising to the power of the given number in other wordsexp(xgives ** import math math exp( math pow(the math pow(method receives two float argumentsraises the first to the second and returns the result in other wordspow( , is equivalent to ** import math math pow( , ** math sqrt(the math sqrt(method returns the square root of given number import math math sqrt(
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 "print (" sleep all night and work all day "def is keyword that indicates that this is function definition the name of the function is print_lyrics the rules for function names are the same as for variable nameslettersnumbers and some punctuation marks are legalbut the first character can' be number you can' use keyword as the name of functionand you should avoid having variable and function with the same name the empty parentheses after the name indicate that this function doesn' take any arguments the first line of the function definition is called the headerthe rest is called the body the header has to end with colon and the body has to be indented by conventionthe indentation is always four spaces the body can contain any number of statements the strings in the print statements are enclosed in double quotes single quotes and double quotes do the same thingmost people use single quotes except in cases like this where single quote appears in the string once you have defined functionyou can use it inside another function for exampleto repeat the previous refrainwe could write function called repeat_lyricsdef repeat_lyrics()print_lyrics(print_lyrics(and then call repeat_lyricsrepeat_lyrics( ' lumberjackand ' okay sleep all night and work all day ' lumberjackand ' okay sleep all night and work all day