id
int64
0
25.6k
text
stringlengths
0
4.59k
11,000
venture of iit bombay vjti alumni resets the time conversion rules used by the library routines the environment variable tz specifies how this is done let us go through the functions briefly there are following two important attributes available with time module sr no attribute with description time timezone attribute time timezone is the offset in seconds of the local time zone (without dstfrom utc (> in the americas<= in most of europeasiaafrica time tzname attribute time tzname is pair of locale-dependent stringswhich are the names of the local time zone without and with dstrespectively the calendar module
11,001
venture of iit bombay vjti alumni the calendar module supplies calendar-related functionsincluding functions to print text calendar for given month or year by defaultcalendar takes monday as the first day of the week and sunday as the last one to change thiscall calendar setfirstweekday(function here is list of functions available with the calendar module sr no function with description calendar calendar(year, = , = , = returns multiline string with calendar for year year formatted into three columns separated by spaces is the width in characters of each dateeach line has length * + + * is the number of lines for each week calendar firstweekdayreturns the current setting for the weekday that starts each week by defaultwhen calendar is first importedthis is meaning monday
11,002
venture of iit bombay vjti alumni calendar isleap(yearreturns true if year is leap yearotherwisefalse calendar leapdays( , returns the total number of leap days in the years within range( , calendar month(year,month, = , = returns multiline string with calendar for month month of year yearone line per week plus two header lines is the width in characters of each dateeach line has length * + is the number of lines for each week calendar monthcalendar(year,monthreturns list of lists of ints each sublist denotes week days outside month month of year year are set to days within the month are set to their day-of-month and up calendar monthrange(year,month
11,003
venture of iit bombay vjti alumni returns two integers the first one is the code of the weekday for the first day of the month month in year yearthe second one is the number of days in the month weekday codes are (mondayto (sunday)month numbers are to calendar prcal(year, = , = , = like print calendar calendar(year, , , calendar prmonth(year,month, = , = like print calendar month(year,month, , calendar setfirstweekday(weekdaysets the first day of each week to weekday code weekday weekday codes are (mondayto (sunday calendar timegm(tupletimethe inverse of time gmtimeaccepts time instant in time-tuple form and returns the same instant as floating-point number of seconds since the epoch
11,004
venture of iit bombay vjti alumni calendar weekday(year,month,dayreturns the weekday code for the given date weekday codes are (mondayto (sunday)month numbers are (januaryto (decemberother modules functions if you are interestedthen here you would find list of other important modules and functions to play with date time in python the datetime module the pytz module the dateutil module
11,005
venture of iit bombay vjti alumni python functions function is block of organizedreusable code that is used to perform singlerelated action functions provide better modularity for your application and high degree of code reusing as you already knowpython gives you many built-in functions like print()etc but you can also create your own functions these functions are called user-defined functions defining function you can define functions to provide the required functionality here are simple rules to define function in python function blocks begin with the keyword def followed by the function name and parentheses any input parameters or arguments should be placed within these parentheses you can also define parameters inside these parentheses
11,006
venture of iit bombay vjti alumni the first statement of function can be an optional statement the documentation string of the function or docstring the code block within every function starts with colon (:and is indented the statement return [expressionexits functionoptionally passing back an expression to the caller return statement with no arguments is the same as return none syntax def functionnameparameters )"function_docstringfunction_suite return [expressionby defaultparameters have positional behavior and you need to inform them in the same order that they were defined example the following function takes string as input parameter and prints it on standard screen def printmestr )"this prints passed string into this function
11,007
venture of iit bombay vjti alumni print str return calling function defining function only gives it namespecifies the parameters that are to be included in the function and structures the blocks of code once the basic structure of function is finalizedyou can execute it by calling it from another function or directly from the python prompt following is the example to call printme(function #!/usr/bin/python function definition is here def printmestr )"this prints passed string into this functionprint str return
11,008
venture of iit bombay vjti alumni now you can call printme function printme(" ' first call to user defined function!"printme("again second call to the same function"when the above code is executedit produces the following result ' first call to user defined functionagain second call to the same function pass by reference vs value all parameters (argumentsin the python language are passed by reference it means if you change what parameter refers to within functionthe change also reflects back in the calling function for example #!/usr/bin/python function definition is here
11,009
venture of iit bombay vjti alumni def changememylist )"this changes passed list into this functionmylist append([ , , , ])print "values inside the function"mylist return now you can call changeme function mylist [ , , ]changememylist )print "values outside the function"mylist herewe are maintaining reference of the passed object and appending values in the same object sothis would produce the following result values inside the function[ [ ]values outside the function[ [ ]
11,010
venture of iit bombay vjti alumni there is one more example where argument is being passed by reference and the reference is being overwritten inside the called function #!/usr/bin/python function definition is here def changememylist )"this changes passed list into this functionmylist [ , , , ]this would assig new reference in mylist print "values inside the function"mylist return now you can call changeme function mylist [ , , ]changememylist )
11,011
venture of iit bombay vjti alumni print "values outside the function"mylist the parameter mylist is local to the function changeme changing mylist within the function does not affect mylist the function accomplishes nothing and finally this would produce the following result values inside the function[ values outside the function[ function arguments you can call function by using the following types of formal arguments required arguments keyword arguments default arguments variable-length arguments required arguments required arguments are the arguments passed to function in correct positional order herethe number of arguments in the function call should match exactly with the function definition
11,012
venture of iit bombay vjti alumni to call the function printme()you definitely need to pass one argumentotherwise it gives syntax error as follows #!/usr/bin/python function definition is here def printmestr )"this prints passed string into this functionprint str returnnow you can call printme function printme(when the above code is executedit produces the following result traceback (most recent call last)
11,013
venture of iit bombay vjti alumni file "test py"line in printme()typeerrorprintme(takes exactly argument ( givenkeyword arguments keyword arguments are related to the function calls when you use keyword arguments in function callthe caller identifies the arguments by the parameter name this allows you to skip arguments or place them out of order because the python interpreter is able to use the keywords provided to match the values with parameters you can also make keyword calls to the printme(function in the following ways #!/usr/bin/python function definition is here def printmestr )"this prints passed string into this functionprint str
11,014
venture of iit bombay vjti alumni returnnow you can call printme function printmestr "my string"when the above code is executedit produces the following result my string the following example gives more clear picture note that the order of parameters does not matter #!/usr/bin/python function definition is here def printinfonameage )"this prints passed info into this functionprint "name"name
11,015
venture of iit bombay vjti alumni print "age "age returnnow you can call printinfo function printinfoage= name="mikiwhen the above code is executedit produces the following result namemiki age default arguments default argument is an argument that assumes default value if value is not provided in the function call for that argument the following example gives an idea on default argumentsit prints default age if it is not passed #!/usr/bin/python
11,016
venture of iit bombay vjti alumni function definition is here def printinfonameage )"this prints passed info into this functionprint "name"name print "age "age returnnow you can call printinfo function printinfoage= name="mikiprintinfoname="mikiwhen the above code is executedit produces the following result namemiki age namemiki age
11,017
venture of iit bombay vjti alumni variable-length arguments you may need to process function for more arguments than you specified while defining the function these arguments are called variable-lengtharguments and are not named in the function definitionunlike required and default arguments syntax for function with non-keyword variable arguments is this def functionname([formal_args,*var_args_tuple )"function_docstringfunction_suite return [expressionan asterisk (*is placed before the variable name that holds the values of all nonkeyword variable arguments this tuple remains empty if no additional arguments are specified during the function call following is simple example #!/usr/bin/python function definition is here def printinfoarg *vartuple )"this prints variable passed arguments
11,018
venture of iit bombay vjti alumni print "output isprint arg for var in vartupleprint var returnnow you can call printinfo function printinfo printinfo when the above code is executedit produces the following result output is output is
11,019
venture of iit bombay vjti alumni the anonymous functions these functions are called anonymous because they are not declared in the standard manner by using the def keyword you can use the lambda keyword to create small anonymous functions lambda forms can take any number of arguments but return just one value in the form of an expression they cannot contain commands or multiple expressions an anonymous function cannot be direct call to print because lambda requires an expression lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace although it appears that lambda' are one-line version of functionthey are not equivalent to inline statements in or ++whose purpose is by passing function stack allocation during invocation for performance reasons syntax the syntax of lambda functions contains only single statementwhich is as follows
11,020
venture of iit bombay vjti alumni lambda [arg [,arg argn]]:expression following is the example to show how lambda form of function works #!/usr/bin/python function definition is here sum lambda arg arg arg arg now you can call sum as function print "value of total "sum print "value of total "sum when the above code is executedit produces the following result value of total value of total the return statement
11,021
venture of iit bombay vjti alumni the statement return [expressionexits functionoptionally passing back an expression to the caller return statement with no arguments is the same as return none all the above examples are not returning any value you can return value from function as follows #!/usr/bin/python function definition is here def sumarg arg )add both the parameters and return them total arg arg print "inside the function "total return totalnow you can call sum function
11,022
venture of iit bombay vjti alumni total sum )print "outside the function "total when the above code is executedit produces the following result inside the function outside the function scope of variables all variables in program may not be accessible at all locations in that program this depends on where you have declared variable the scope of variable determines the portion of the program where you can access particular identifier there are two basic scopes of variables in python global variables local variables global vs local variables variables that are defined inside function body have local scopeand those defined outside have global scope
11,023
venture of iit bombay vjti alumni this means that local variables can be accessed only inside the function in which they are declaredwhereas global variables can be accessed throughout the program body by all functions when you call functionthe variables declared inside it are brought into scope following is simple example #!/usr/bin/python total this is global variable function definition is here def sumarg arg )add both the parameters and return them total arg arg here total is local variable print "inside the function local total "total return totalnow you can call sum function
11,024
venture of iit bombay vjti alumni sum )print "outside the function global total "total when the above code is executedit produces the following result inside the function local total outside the function global total
11,025
venture of iit bombay vjti alumni python modules module allows you to logically organize your python code grouping related code into module makes the code easier to understand and use module is python object with arbitrarily named attributes that you can bind and reference simplya module is file consisting of python code module can define functionsclasses and variables module can also include runnable code example the python code for module named aname normally resides named aname py here' an example of simple modulesupport py def print_funcpar )print "hello "par in file
11,026
venture of iit bombay vjti alumni return the import statement you can use any python source file as module by executing an import statement in some other python source file the import has the following syntax import module [module [modulenwhen the interpreter encounters an import statementit imports the module if the module is present in the search path search path is list of directories that the interpreter searches before importing module for exampleto import the module support pyyou need to put the following command at the top of the script #!/usr/bin/python import module support import support
11,027
venture of iit bombay vjti alumni now you can call defined function that module as follows support print_func("zara"when the above code is executedit produces the following result hello zara module is loaded only onceregardless of the number of times it is imported this prevents the module execution from happening over and over again if multiple imports occur the from import statement python' from statement lets you import specific attributes from module into the current namespace the from import has the following syntax from modname import name [name [namen]for exampleto import the function fibonacci from the module fibuse the following statement from fib import fibonacci this statement does not import the entire module fib into the current namespaceit just introduces the item fibonacci from the module fib into the global symbol table of the importing module
11,028
venture of iit bombay vjti alumni the from import statement it is also possible to import all names from module into the current namespace by using the following import statement from modname import this provides an easy way to import all the items from module into the current namespacehoweverthis statement should be used sparingly locating modules when you import modulethe python interpreter searches for the module in the following sequences the current directory if the module isn' foundpython then searches each directory in the shell variable pythonpath if all else failspython checks the default path on unixthis default path is normally /usr/local/lib/pythonthe module search path is stored in the system module sys as the sys pathvariable the sys path variable contains the current directorypythonpathand the installation-dependent default the pythonpath variable
11,029
venture of iit bombay vjti alumni the pythonpath is an environment variableconsisting of list of directories the syntax of pythonpath is the same as that of the shell variable path here is typical pythonpath from windows system set pythonpath :\python \liband here is typical pythonpath from unix system set pythonpath /usr/local/lib/python namespaces and scoping variables are names (identifiersthat map to objects namespace is dictionary of variable names (keysand their corresponding objects (valuesa python statement can access variables in local namespace and in the global namespace if local and global variable have the same namethe local variable shadows the global variable each function has its own local namespace class methods follow the same scoping rule as ordinary functions python makes educated guesses on whether variables are local or global it assumes that any variable assigned value in function is local thereforein order to assign value to global variable within functionyou must first use the global statement
11,030
venture of iit bombay vjti alumni the statement global varname tells python that varname is global variable python stops searching the local namespace for the variable for examplewe define variable money in the global namespace within the function moneywe assign money valuetherefore python assumes moneyas local variable howeverwe accessed the value of the local variable moneybefore setting itso an unboundlocalerror is the result uncommenting the global statement fixes the problem #!/usr/bin/python money def addmoney()uncomment the following line to fix the codeglobal money money money print money
11,031
venture of iit bombay vjti alumni addmoney(print money the dirfunction the dir(built-in function returns sorted list of strings containing the names defined by module the list contains the names of all the modulesvariables and functions that are defined in module following is simple example #!/usr/bin/python import built-in module math import math content dir(mathprint content when the above code is executedit produces the following result
11,032
venture of iit bombay vjti alumni ['__doc__''__file__''__name__''acos''asin''atan''atan ''ceil''cos''cosh''degrees'' ''exp''fabs''floor''fmod''frexp''hypot''ldexp''log''log ''modf''pi''pow''radians''sin''sinh''sqrt''tan''tanh'herethe special string variable __name__ is the module' nameand __file__is the filename from which the module was loaded the globals(and locals(functions the globals(and locals(functions can be used to return the names in the global and local namespaces depending on the location from where they are called if locals(is called from within functionit will return all the names that can be accessed locally from that function if globals(is called from within functionit will return all the names that can be accessed globally from that function the return type of both these functions is dictionary thereforenames can be extracted using the keys(function the reload(function when the module is imported into scriptthe code in the top-level portion of module is executed only once
11,033
venture of iit bombay vjti alumni thereforeif you want to reexecute the top-level code in moduleyou can use the reload(function the reload(function imports previously imported module again the syntax of the reload(function is this reload(module_nameheremodule_name is the name of the module you want to reload and not the string containing the module name for exampleto reload hello moduledo the following reload(hellopackages in python package is hierarchical file directory structure that defines single python application environment that consists of modules and subpackages and subsubpackagesand so on consider file pots py available in phone directory this file has following line of source code #!/usr/bin/python
11,034
venture of iit bombay vjti alumni def pots()print " ' pots phonesimilar waywe have another two files having different functions with the same name as above phone/isdn py file having function isdn(phone/ py file having function (nowcreate one more file __init__ py in phone directory phone/__init__ py to make all of your functions available when you've imported phoneyou need to put explicit import statements in __init__ py as follows from pots import pots from isdn import isdn from import after you add these lines to __init__ pyyou have all of these classes available when you import the phone package #!/usr/bin/python
11,035
venture of iit bombay vjti alumni now import your phone package import phone phone pots(phone isdn(phone (when the above code is executedit produces the following result ' pots phone ' phone ' isdn phone in the above examplewe have taken example of single functions in each filebut you can keep multiple functions in your files you can also define different python classes in those files and then you can create your packages out of those classes
11,036
venture of iit bombay vjti alumni python files / this covers all the basic / functions available in python for more functionsplease refer to standard python documentation printing to the screen the simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas this function converts the expressions you pass into string and writes the result to standard output as follows #!/usr/bin/python print "python is really great language,""isn' it?this produces the following result on your standard screen
11,037
venture of iit bombay vjti alumni python is really great languageisn' itreading keyboard input python provides two built-in functions to read line of text from standard inputwhich by default comes from the keyboard these functions are raw_input input the raw_input function the raw_input([prompt]function reads one line from standard input and returns it as string (removing the trailing newline#!/usr/bin/python str raw_input("enter your input")print "received input is "str
11,038
venture of iit bombay vjti alumni this prompts you to enter any string and it would display same string on the screen when typed "hello python!"its output is like this enter your inputhello python received input is hello python the input function the input([prompt]function is equivalent to raw_inputexcept that it assumes the input is valid python expression and returns the evaluated result to you #!/usr/bin/python str input("enter your input")print "received input is "str this would produce the following result against the entered input enter your input[ * for in range( , , )recieved input is [ opening and closing files
11,039
venture of iit bombay vjti alumni until nowyou have been reading and writing to the standard input and output nowwe will see how to use actual data files python provides basic functions and methods necessary to manipulate files by default you can do most of the file manipulation using file object the open function before you can read or write fileyou have to open it using python' builtin open(function this function creates file objectwhich would be utilized to call other support methods associated with it syntax file object open(file_name [access_mode][buffering]here are parameter details file_name the file_name argument is string value that contains the name of the file that you want to access access_mode the access_mode determines the mode in which the file has to be openedi readwriteappendetc complete list of possible values is given below in the table this is optional parameter and the default file access mode is read (rbuffering if the buffering value is set to no buffering takes place if the buffering value is line buffering is performed while accessing file if you
11,040
venture of iit bombay vjti alumni specify the buffering value as an integer greater than then buffering action is performed with the indicated buffer size if negativethe buffer size is the system default(default behaviorhere is list of the different modes of opening file sr no modes description opens file for reading only the file pointer is placed at the beginning of the file this is the default mode rb opens file for reading only in binary format the file pointer is placed at the beginning of the file this is the default mode ropens file for both reading and writing the file pointer placed at the beginning of the file
11,041
venture of iit bombay vjti alumni rbopens file for both reading and writing in binary format the file pointer placed at the beginning of the file opens file for writing only overwrites the file if the file exists if the file does not existcreates new file for writing wb opens file for writing only in binary format overwrites the file if the file exists if the file does not existcreates new file for writing wopens file for both writing and reading overwrites the existing file if the file exists if the file does not existcreates new file for reading and writing
11,042
venture of iit bombay vjti alumni wbopens file for both writing and reading in binary format overwrites the existing file if the file exists if the file does not existcreates new file for reading and writing opens file for appending the file pointer is at the end of the file if the file exists that isthe file is in the append mode if the file does not existit creates new file for writing ab opens file for appending in binary format the file pointer is at the end of the file if the file exists that isthe file is in the append mode if the file does not existit creates new file for writing aopens file for both appending and reading the file pointer is at the end of the file if the file exists the file opens in the
11,043
venture of iit bombay vjti alumni append mode if the file does not existit creates new file for reading and writing abopens file for both appending and reading in binary format the file pointer is at the end of the file if the file exists the file opens in the append mode if the file does not existit creates new file for reading and writing the file object attributes once file is opened and you have one file objectyou can get various information related to that file here is list of all attributes related to file object sr no attribute description file closed returns true if file is closedfalse otherwise
11,044
venture of iit bombay vjti alumni file mode returns access mode with which file was opened file name returns name of the file file softspace returns false if space explicitly required with printtrue otherwise example #!/usr/bin/python open file fo open("foo txt""wb"print "name of the file"fo name
11,045
venture of iit bombay vjti alumni print "closed or not "fo closed print "opening mode "fo mode print "softspace flag "fo softspace this produces the following result name of the filefoo txt closed or not false opening mode wb softspace flag the close(method the close(method of file object flushes any unwritten information and closes the file objectafter which no more writing can be done python automatically closes file when the reference object of file is reassigned to another file it is good practice to use the close(method to close file syntax fileobject close()
11,046
venture of iit bombay vjti alumni example #!/usr/bin/python open file fo open("foo txt""wb"print "name of the file"fo name close opend file fo close(this produces the following result name of the filefoo txt reading and writing files the file object provides set of access methods to make our lives easier we would see how to use read(and write(methods to read and write files
11,047
venture of iit bombay vjti alumni the write(method the write(method writes any string to an open file it is important to note that python strings can have binary data and not just text the write(method does not add newline character ('\ 'to the end of the string syntax fileobject write(string)herepassed parameter is the content to be written into the opened file example #!/usr/bin/python open file fo open("foo txt""wb"fo write"python is great language \nyeah its great!!\ ")
11,048
venture of iit bombay vjti alumni close opend file fo close(the above method would create foo txt file and would write given content in that file and finally it would close that file if you would open this fileit would have following content python is great language yeah its great!the read(method the read(method reads string from an open file it is important to note that python strings can have binary data apart from text data syntax fileobject read([count])herepassed parameter is the number of bytes to be read from the opened file this method starts reading from the beginning of the file and if count is missingthen it tries to read as much as possiblemaybe until the end of file
11,049
venture of iit bombay vjti alumni example let' take file foo txtwhich we created above #!/usr/bin/python open file fo open("foo txt"" +"str fo read( )print "read string is "str close opend file fo close(this produces the following result read string is python is file positions
11,050
venture of iit bombay vjti alumni the tell(method tells you the current position within the filein other wordsthe next read or write will occur at that many bytes from the beginning of the file the seek(offset[from]method the offsetargument indicates the changes number the current of bytes file to be position moved the from argument specifies the reference position from where the bytes are to be moved if from is set to it means use the beginning of the file as the reference position and means use the current position as the reference position and if it is set to then the end of the file would be taken as the reference position example let us take file foo txtwhich we created above #!/usr/bin/python open file fo open("foo txt"" +"str fo read( )print "read string is "str
11,051
venture of iit bombay vjti alumni check current position position fo tell()print "current file position "position reposition pointer at the beginning once again position fo seek( )str fo read( )print "again read string is "str close opend file fo close(this produces the following result read string is python is current file position
11,052
venture of iit bombay vjti alumni again read string is python is renaming and deleting files python os module provides methods that help you perform file-processing operationssuch as renaming and deleting files to use this module you need to import it first and then you can call any related functions the rename(method the rename(method takes two argumentsthe current filename and the new filename syntax os rename(current_file_namenew_file_nameexample following is the example to rename an existing file test txt #!/usr/bin/python import os
11,053
venture of iit bombay vjti alumni rename file from test txt to test txt os rename"test txt""test txtthe remove(method you can use the remove(method to delete files by supplying the name of the file to be deleted as the argument syntax os remove(file_nameexample following is the example to delete an existing file test txt #!/usr/bin/python import os delete file test txt
11,054
venture of iit bombay vjti alumni os remove("text txt"directories in python all files are contained within various directoriesand python has no problem handling these too the os module has several methods that help you createremoveand change directories the mkdir(method you can use the mkdir(method of the os module to create directories in the current directory you need to supply an argument to this method which contains the name of the directory to be created syntax os mkdir("newdir"example following is the example to create directory test in the current directory #!/usr/bin/python
11,055
venture of iit bombay vjti alumni import os create directory "testos mkdir("test"the chdir(method you can use the chdir(method to change the current directory the chdir(method takes an argumentwhich is the name of the directory that you want to make the current directory syntax os chdir("newdir"example following is the example to go into "/home/newdirdirectory #!/usr/bin/python
11,056
venture of iit bombay vjti alumni import os changing directory to "/home/newdiros chdir("/home/newdir"the getcwd(method the getcwd(method displays the current working directory syntax os getcwd(example following is the example to give current directory #!/usr/bin/python import os this would give location of the current directory
11,057
venture of iit bombay vjti alumni os getcwd(the rmdir(method the rmdir(method deletes the directorywhich is passed as an argument in the method before removing directoryall the contents in it should be removed syntax os rmdir('dirname'example following is the example to remove "/tmp/testdirectory it is required to give fully qualified name of the directoryotherwise it would search for that directory in the current directory #!/usr/bin/python import os this would remove "/tmp/testdirectory
11,058
venture of iit bombay vjti alumni os rmdir"/tmp/testfile directory related methods there are three important sourceswhich provide wide range of utility methods to handle and manipulate files directories on windows and unix operating systems they are as follows file object methodsthe file object provides functions to manipulate files os object methodsthis provides methods to process files as well as directories python exceptions handling python provides two very important features to handle any unexpected error in your python programs and to add debugging capabilities in them exception handling this would be covered in this tutorial here is list standard exceptions available in pythonstandard exceptions assertions this would be covered in assertions in pythontutorial list of standard exceptions
11,059
venture of iit bombay vjti alumni sr no exception name description exception base class for all exceptions stopiteration raised when the next(method of an iterator does not point to any object systemexit raised by the sys exit(function standarderror base class for all built-in exceptions except stopiteration and systemexit arithmeticerror base class for all errors that occur for numeric calculation
11,060
venture of iit bombay vjti alumni overflowerror raised when calculation exceeds maximum limit for numeric type floatingpointerror raised when floating point calculation fails zerodivisionerror raised when division or modulo by zero takes place for all numeric types assertionerror raised in case of failure of the assert statement attributeerror raised in case of failure of attribute reference or assignment eoferror
11,061
venture of iit bombay vjti alumni raised when there is no input from either the raw_input(or input(function and the end of file is reached importerror raised when an import statement fails keyboardinterrupt raised when the user interrupts program executionusually by pressing ctrl+ lookuperror base class for all lookup errors indexerror raised when an index is not found in sequence keyerror raised when the specified key is not found in the dictionary
11,062
venture of iit bombay vjti alumni nameerror raised when an identifier is not found in the local or global namespace unboundlocalerror raised when trying to access local variable in function or method but no value has been assigned to it environmenterror base class for all exceptions that occur outside the python environment ioerror raised when an inputoutput operation failssuch as the print statement or the open(function when trying to open file that does not exist ioerror
11,063
venture of iit bombay vjti alumni raised for operating system-related errors syntaxerror raised when there is an error in python syntax indentationerror raised when indentation is not specified properly systemerror raised when the interpreter finds an internal problembut when this error is encountered the python interpreter does not exit systemexit raised when python interpreter is quit by using the sys exit(function if not handled in the codecauses the interpreter to exit typeerror raised when an operation or function is attempted that is invalid
11,064
venture of iit bombay vjti alumni for the specified data type valueerror raised when the built-in function for data type has the valid type of argumentsbut the arguments have invalid values specified runtimeerror raised when generated error does not fall into any category notimplementederror raised when an abstract method that needs to be implemented in an inherited class is not actually implemented assertions in python an assertion is sanity-check that you can turn on or turn off when you are done with your testing of the program
11,065
venture of iit bombay vjti alumni the easiest way to think of an assertion is to liken it to raise-if statement (or to be more accuratea raise-if-not statementan expression is testedand if the result comes up falsean exception is raised assertions are carried out by the assert statementthe newest keyword to pythonintroduced in version programmers often place assertions at the start of function to check for valid inputand after function call to check for valid output the assert statement when it encounters an assert statementpython evaluates the accompanying expressionwhich is hopefully true if the expression is falsepython raises an assertionerror exception the syntax for assert is assert expression[argumentsif the assertion failspython uses argumentexpression as the argument for the assertionerror assertionerror exceptions can be caught and handled like any other exception using the try-except statementbut if not handledthey will terminate the program and produce traceback
11,066
venture of iit bombay vjti alumni example here is function that converts temperature from degrees kelvin to degrees fahrenheit since zero degrees kelvin is as cold as it getsthe function bails out if it sees negative temperature #!/usr/bin/python def kelvintofahrenheit(temperature)assert (temperature > ),"colder than absolute zero!return ((temperature- )* )+ print kelvintofahrenheit( print int(kelvintofahrenheit( )print kelvintofahrenheit(- when the above code is executedit produces the following result traceback (most recent call last)file "test py"line in
11,067
venture of iit bombay vjti alumni print kelvintofahrenheit(- file "test py"line in kelvintofahrenheit assert (temperature > ),"colder than absolute zero!assertionerrorcolder than absolute zerowhat is exceptionan exception is an eventwhich occurs during the execution of program that disrupts the normal flow of the program' instructions in generalwhen python script encounters situation that it cannot cope withit raises an exception an exception is python object that represents an error when python script raises an exceptionit must either handle the exception immediately otherwise it terminates and quits handling an exception if you have some suspicious code that may raise an exceptionyou can defend your program by placing the suspicious code in tryblock after the tryblockinclude an exceptstatementfollowed by block of code which handles the problem as elegantly as possible syntax here is simple syntax of try except else blocks
11,068
venture of iit bombay vjti alumni tryyou do your operations hereexcept exceptioniif there is exceptionithen execute this block except exceptioniiif there is exceptioniithen execute this block elseif there is no exception then execute this block here are few important points about the above-mentioned syntax single try statement can have multiple except statements this is useful when the try block contains statements that may throw different types of exceptions you can also provide generic except clausewhich handles any exception after the except clause( )you can include an else-clause the code in the else-block executes if the code in the tryblock does not raise an exception the else-block is good place for code that does not need the tryblock' protection
11,069
venture of iit bombay vjti alumni example this example opens filewrites content in thefile and comes out gracefully because there is no problem at all #!/usr/bin/python tryfh open("testfile"" "fh write("this is my test file for exception handling!!"except ioerrorprint "errorcan\' find file or read dataelseprint "written content in the file successfullyfh close(this produces the following result
11,070
venture of iit bombay vjti alumni written content in the file successfully example this example tries to open file where you do not have write permissionso it raises an exception #!/usr/bin/python tryfh open("testfile"" "fh write("this is my test file for exception handling!!"except ioerrorprint "errorcan\' find file or read dataelseprint "written content in the file successfullythis produces the following result
11,071
venture of iit bombay vjti alumni errorcan' find file or read data the except clause with no exceptions you can also use the except statement with no exceptions defined as follows tryyou do your operations hereexceptif there is any exceptionthen execute this block elseif there is no exception then execute this block this kind of try-except statement catches all the exceptions that occur using this kind of try-except statement is not considered good programming practice thoughbecause it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur the except clause with multiple exceptions you can also use the same except statement to handle multiple exceptions as follows
11,072
venture of iit bombay vjti alumni tryyou do your operations hereexcept(exception [exception [exceptionn]]])if there is any exception from the given exception listthen execute this block elseif there is no exception then execute this block the try-finally clause you can use finallyblock along with tryblock the finally block is place to put any code that must executewhether the try-block raised an exception or not the syntax of the try-finally statement is this try
11,073
venture of iit bombay vjti alumni you do your operations heredue to any exceptionthis may be skipped finallythis would always be executed you cannot use else clause as well along with finally clause example #!/usr/bin/python tryfh open("testfile"" "fh write("this is my test file for exception handling!!"finally
11,074
venture of iit bombay vjti alumni print "errorcan\' find file or read dataif you do not have permission to open the file in writing modethen this will produce the following result errorcan' find file or read data same example can be written more cleanly as follows #!/usr/bin/python tryfh open("testfile"" "tryfh write("this is my test file for exception handling!!"
11,075
venture of iit bombay vjti alumni finallyprint "going to close the filefh close(except ioerrorprint "errorcan\' find file or read datawhen an exception is thrown in the try blockthe execution immediately passes to the finally block after all the statements in the finally block are executedthe exception is raised again and is handled in the exceptstatements if present in the next higher layer of the try-except statement argument of an exception an exception can have an argumentwhich is value that gives additional information about the problem the contents of the argument vary by exception you capture an exception' argument by supplying variable in the except clause as follows tryyou do your operations here
11,076
sscasc@tumkur python has very powerful but simplistic way of doing oopespecially when compared to big languages like +or java interpretedpython converts the source code into an intermediate form called byte codes and then translates this into the native language of your computer using pvm(is interpreterand then runs it extensiblethe programs or function written in +can be integrated into python an executed using pvm there is another flavor of python where programs from other languages can be integrated into python embeddableyou can embed python within your / +programs to give scripting capabilities for your program' users extensive librariesthe python standard library is huge indeed it can help you do various things involving regular expressionsdocumentation generationunit testingthreadingdatabasesweb browserscgiftpemailxmlxml-rpchtmlwav filescryptographygui (graphical user interfaces)and other system-dependent stuff rememberall this is always available wherever python is installed this is called the batteries included philosophy of python some interesting batteries or packages areorgparse is package that represents command-line parsing library botois amazon web services library cherryphy is an object-oriented http frame work cryptography offers cryptographic techniques for the programmers fiona reads and writes big data files numpy is package for processing arrays of single or multidimensional type lib is library of web related functions mysql-connector-pythonis is driver written in python to connect to mysql data base scripting languagepython is considered as scripting language as it is interpreted and it is used on the internet to support other software database connectivitypython provides interface to connect its programs to all major databases like oraclesybase or mysql scalablepython programs are scalable since they can run on any platform and use the features of the new platform effectively comparison between and python -language procedure oriented programming language program execute faster declaration of variable is compulsory type discipline is static and weak pointer is available does not have exception handling it has whilefor and do-while loops sp_python programming python object oriented programming language program execute slower compare to type declaration is not required type discipline is dynamic and string no pointer handles exceptions it has while and for loops
11,077
it has switch-case statement the variable in for loop does not incremented automatically memory allocation and de-allocation is not automatic it does not contain garbage collection it supports single and multi dimensional arrays the array index should be positive integer indentation of statements in not necessary semicolon is used to terminate the statements and comma is used to separate expressions variables it supports in-line assignment sscasc@tumkur it does not have switch-case statement the variable in the for loop incremented automatically memory allocation and de-allocation is done automatically by pvm automatic garbage collection it supports only single dimensional array implement multi dimensional array we should use third party application like numpy array index can be positive and negative integer negative index represents location from the end of the array indentation is required to represents block of statements new line indicates end of the statements and semicolon is used as an expression separator it does not supports in-line assignment comparison between java and python java pure object-oriented programming language python both object-oriented and procedure-oriented programming language java programs are verbose python programs are concise and compact declaration of variable is compulsory type declaration is not required type discipline is static and weak type discipline is dynamic and string it has whilefor and do-while loops it has while and for loops it has switch-case statement it does not have switch-case statement the variable in for loop does not incremented the variable in the for loop incremented automatically automatically memory allocation and de-allocation is memory allocation and de-allocation is done automatically by jvm automatically by pvm it supports single and multi dimensional arrays it supports only single dimensional array implement multi dimensional array we should use third party application like numpy the array index should be positive integer array index can be positive and negative integer negative index represents location from the end of the array indentation of statements in not necessary indentation is required to represents block of statements semicolon is used to terminate the new line indicates end of the statements and statements and comma is used to separate semicolon is used as an expression separator expressions variables the collection objects like stacklinked list or the collection objects like lists and dictionaries vector but not primitive data types like intcan store objects of any type including floatchar etc numbers and lists sp_python programming
11,078
sscasc@tumkur python virtual machine (pvmor interpreter python converts the source code into byte code byte code represents the fixed set of instructions created by python developers representing all types of operations the size of each byte code instruction is byte the role of pvm is to convert the byte code instructions into machine code so that the computer can execute those machine code instruction and display the final output the pvm is also called as interpreter python shell python interpreter is program which translates your code into machine language and then executes it line by line we can use python interpreter in two modes interactive mode script mode in interactive modepython interpreter waits for you to enter command when you type the commandpython interpreter goes ahead and executes the commandthen it waits again for your next command in script modepython interpreter runs program from the source file interactive mode python interpreter in interactive mode is commonly known as python shell to start the python shell enter the following command in terminal or command promptto start the python shell enter python instead of just python @vm:~python python (defaultnov : : [gcc on linux type "help""copyright""creditsor "licensefor more information what you are seeing is called python shell is known as prompt stringit simply means that python shell is ready to accept you commands python shell allows you type python code and see the result immediately in python shellenter the following calculations one by one and hit enter to get the result script mode python shell is great for testing small chunks of code but there is one problem the statements you enter in the python shell are not saved anywhere in caseyou want to execute same set of statements multiple times you would be better off to save the entire code in file thenuse the python interpreter in script mode to execute the code from file sp_python programming
11,079
sscasc@tumkur create new file named example py and following code to itprint("welcome to python program"print("bca th sem"print("sscasc tumkur"by conventionall python programs have py extension the file example py is called source code or source file or script file or module execute by typing the following command an obtained out as followspython example py welcome to python program bca th sem sscasc tumkur indentationwhitespace is important in python actuallywhitespace at the beginning of the line is important this is called indentation leading whitespace (spaces and tabsat the beginning of the logical line is used to determine the indentation level of the logical linewhich in turn is used to determine the grouping of statements this means that statements which go together must have the same indentation each such set of statements is called block one thing you should remember is that wrong indentation can give rise to errors basic elements of python comments comments are non-executable statements it means neither compiler nor pvm will not execute them comments are any text to the right of the symbol and is mainly useful as notes for the reader of the program there are two types of comments in pythonsingle line comments and multiline comments single line commentsthis comment starts with hash symbol (#and are useful to mention that the entire line till the end should be treated as comments eg to find the sum of two number = assign to variable in the above examplefirst line starts with and hence the total line treated as comments in second line part of this line starting from to the end of the line treated as comments multi line commentsthe triple double quotes ("""or triple single quotes ('''are called multi line comments or block comments they are used to enclose block of lines as comments eg- ""this is illustrated as multi line comments to find the sum of two number using triple double quotes "" identifiersidentifier is the name given to various program elements like variablesfunctionarraysclassesstrings etc the python identifiers follow the following rulesi the name should begin with an alphabet sp_python programming
11,080
ii iii iv sscasc@tumkur only alphabetsdigits and underscores are permitted distinguish between uppercase and lowercase alphabets keywords should not be used as identifiers no blank space between the identifiers valid identifiers area area_tri num keywordsthe keywords have predefined meaning assigned by the python complier the keywords are also called as reserved word all keywords are written in lower case alphabets the python keywords areand del for lambda true as elif from not try assert else global or while break except if pass with class exec import print yield continue false in raise def finally is return variableis program elementwhose value changes during the execution of the program unlike other programming languagespython has no command for declaring variable variable is created the moment you first assign value to it eg = ="kvnvariables do not need to be declared with any particular type and can even change type after they have been set constantsconstant is program elementwhile execution of program the value does not change constant gets stored in memory location but the address of the location is not accessible to the programmer assigning value to constant in python in pythonconstants are usually declared and assigned on module herethe module means new file containing variablesfunctions etc which is imported to main file sp_python programming
11,081
sscasc@tumkur inside the moduleconstants are written in all capital letters and underscores separating the words eg create constant py pi literals literal is raw data given in variable or constant in pythonthere are various types of literals they are as followsa numeric literals numeric literals are immutable (unchangeablenumeric literals can belong to different numerical types integerfloat and complex = = = integer literal float literal complex literal string literals string literal is sequence of characters surrounded by quotes we can use both singledouble or triple quotes for string character literal is single character surrounded by single or double quotes str="sscasctc boolean literals boolean literal can have any of the two valuestrue or false =true =false special literalspython contains one special literal none we use it to specify to that field that is not created =none data typesa data type represents the type of data stored into variable or memory there are different data types arenone type numeric type sequences sets dictionary sp_python programming
11,082
sscasc@tumkur none data type the none data type represents an object that does not contain any value in java language it is called "nullobject but in python it is called as "nonein python maximum of only one 'noneobject is provided if no value is passed to the functionthen the default value will be taken as 'noneii numeric data typethe numeric type represents numbers there are sub typesint float complex int data typethe int data type represents integer number (whole numberan integer number is number without fraction integers can be of any lengthit is only limited by the memory available = =- float data typethe float data type represents floating point number floating point number is number with fraction floating point numbers can also be written in scientific notation using exponentiation format floating point number is accurate up to decimal places integer and floating points are separated by decimal points complex data typea complex number is number is written in the form of +yj or +yj here is the real part and is the imaginary part we can use the type(function to know which class variable or value belongs to and the isinstance(function to check if an object belongs to particular class = print( "is of type"type( ) print( "is of type"type( )iii sequencesa sequence represents group of items or elements there are six types of sequences in python important sequences as followsstr list tuple sp_python programming
11,083
sscasc@tumkur str data type the str represents string data type string is collection of character enclosed in single or double quotes both are valid str="kvnstr is name of string variable str='vedishstr is name of string variable triple double quote or triple single quotes are used to embed string in another string (nested stringstr="""this is 'str data typeexample""print(stroutput is this is 'str data typeexample the [operator used to retrieve specified character from the string the string index starts from hencestr[ indicates the th character in the string str=sscasc tumkurprint(strit display sscasc tumkur print(str[ ]it display list data typea list is collection which is ordered and changeable it allows duplicate members list is similar to array lists are represented by square brackets [and the elements are separated by comma the main difference between list and an array is that list can store different data type elementsbut an array can store only one type of elements list can grow dynamically in memory but the size of array is fixed and they cannot grow dynamically list=[ , ,- "sscasct",'tumkur'print(listit display all elements create list in the list , ,- "sscasct",'tumkurtuple data typea tuple is similar to list tuple contains group of elements which can be different types the elements in the tuple are separated by commas and enclosed in parentheses (the only difference is that tuples are immutable tuples once created cannot be modified the tuple cannot change dynamically that means tuple can be treated as read-only list tpl=( , ,- "sscasct",'tumkur'print(tplit display all elements create tuple in the tuple , ,- "sscasct",'tumkuriv setsset is an unordered collection of unique items and un-indexed the order of elements is not maintained in the sets set does not accept duplicate elements set is defined by values separated by comma inside braces there are two sub types in setsset data type sp_python programming
11,084
sscasc@tumkur frozen set data type set data typeto create setwe should enter the elements separated by comma inside curly brace { , , print(sit display { , , , in the above exampleit displays un-orderly and repeated elements only oncebecause set is unordered collection and unique items we can use set(to create set as =set("kvn"print(kit display "kvnfrozen set data typefrozen set is just an immutable version of python set object while elements of set can be modified at any timean element of frozen set remains the same after creation due to thisfrozen sets can be used as key in dictionary or as element of another set dictionarya dictionary is an unordered collectionchangeable and indexed in python dictionaries are written with curly bracketsand they have keys and values that means dictionary contains pair of elements such that first element represents the key and the next one becomes its value the key and value should be separated by colon(:and every pair should be separated by comma all the elements should be enclosed inside curly brackets ={ 'sscasc' :'tumkur' :'kvn' 'vedish'hered is the name of dictionary is the key and its associated value is 'sscascthe next is and its value is 'tumkurand so on print(dit display ={ 'sscasc' :'tumkur' :'kvn' 'vedish'print( [ ]it display kvn string operations extract specified character from the string get the character at position (remember that the first character has the position ) "hello,python!print( [ ]it display substringextract number of character from the specified position get the characters from position to position (not included) "hello,python!print( [ : ]it display ph the strip(method removes any whitespace from the beginning or the end of the given string ahello,pythonprint( strip()it display "hello,python! the len(method returns the length of given string sp_python programming
11,085
sscasc@tumkur aprint( len()pythonit display the lower(method returns the given string in lower case aprint( lower()it display python python the upper(method returns the given string in upper case aprint( upper()it display python python the replace(method replaces given string with another string "forprint( replace(' ' ')it display far the split(method splits the string into substrings if it finds instances of the separator "hello,python!print( split(',')it display 'hello'python'operator and operandoperators are special symbols which represents computation they are applied on operand( )which can be values or variables same operator can behave differently on different data types operators when applied on operands form an expression operators are categorized as arithmeticrelationallogical and assignment value and variables when used with operator are known as operands arithmetic operators symbol description addition subtraction multiplication division remainder modulo *exponentiation /integer division example- - * ** / example- 'sscasct'+'bcasscasctbca - 'sscasct sscasctsscasct / % ** // relational operators symbol description less than sp_python programming example- < true example- 'sscasct<'bcafalse
11,086
sscasc@tumkur greater than <less than or equal to >greater than or equal to !not equal to =equal to > false <= true >= false != true == false 'sscasct'bcatrue 'sscasct<='bcafalse 'sscasct'>='bcatrue 'sscasct'!'sscascttrue 'sscasc=='sscasctrue logical operators symbol or and not description if any one of the operand is truethen condition becomes true if both the operands are truethen the condition becomes true reverse the state of operand condition example- <= or == true false not < false assignment operatorsymbol description assigned values from right side operands to left variable example- = variations of assignment operatorscompound assignment operator combines the effect of arithmetic and assignment operatorthe original value of = symbol +-*/%**//description added and assign back the result to left operand subtracted and assign back the result to left operand multiplied and assign back the result to left operand divided and assign back the result to left operand taken modulus using two operands and assign the result to left operand performed exponential (powercalculation on operators and assign value to the left operand performed floor division on operators and assign value to sp_python programming example- += -= *= /= %= **= //=
11,087
sscasc@tumkur the left operand bitwise operatora bit is the smallest unit of data storage and it can have only one of the two values and bitwise operators works on bits and perform bit-by-bit operation symbol <>description performs binary or operation performs binary and operation performs binary xor operation performs binary one' complement operation left shift operatorthe left-hand side operand bit is moved left by the number specified on the right-hand side (multiply by left shift operatorthe left-hand side operand bit is moved left by the number specified on the right-hand side (divided by example gives gives gives ~ gives - < gives < gives membership operatorspython has membership operatorswhich test for membership in sequencesuch as stringslists or tuples there are two membership operators aresymbol in description returns true if the specified operand is found in the sequence not in returns true if the specified operand is found in the sequence example [ , , , , in false [ , , , , not in true identity operatoridentity operators compare the memory locations of two objects there are two identity operators aresymbol is description returns true if two variables point to the same object and falseotherwise is not returns false if two variables point to the same object and trueotherwise sp_python programming example = = is true = = is not false example =[ , , =[ , , is false =[ , , =[ , , is not true
11,088
sscasc@tumkur creating python program input function the print function enables python program to display textual information to the user programs may use the input function to obtain information from the user the simplest use of the input function assigns string to variablex input(the parentheses are empty because the input function does not require any information to do its job usinginput py demonstrates that the input function produces string value exapledemonstrates that the input function print('please enter some text:' input(print('text entered:'xprint('type:'type( )since user input always requires message to the user about the expected inputthe input function optionally accepts string and prints just before the program stops to wait for the user to respond the statement variable input("enter value"the value entered is string you can use the function eval to evaluate and convert it to numeric value exampleeval(" "returns eval(" "returns examplecompute area with console input prompt the user to enter radius radius eval(input("enter value for radius")compute area area radius radius #display results print("the area for the circle of radius",radius,"is",areacompute average prompt the user to enter three numbers number eval(input("enter the first number")number eval(input("enter the second number")number eval(input("enter the third number")compute average average (number number number display result print("the average of"number number number ,"is",averageprint function the print line of textand then the cursor moves down to the next line so any future printing appears on the next line print('please enter an integer value:'the print statement accepts an additional argument that allows the cursor to remain on the same line as the printed textprint('please enter an integer value:'end='sp_python programming
11,089
sscasc@tumkur the expression end=is known as keyword will cause the cursor to remain on the same line as the printed text without this keyword argumentthe cursor moves down to the next line after printing the text another way to achieve the same result is print(end='please enter an integer value'this statement means "print nothingand then terminate the line with the string 'please enter an integer value:rather than the normal \ newline code the statement print('please enter an integer value:'end='\ 'that isthe default ending for line of printed text is the string '\ 'the newline control code similarlythe statement printis shorter way to express print(end='\ 'by defaultthe print function places single space in between the items it prints print uses keyword argument named sep to specify the string to use insert between items the name sep stands for separator the default value of sep is the string ' string containing single space the program printsep py shows the sep keyword customizes print' behaviour program to illustrate sepwxyz print(wxyzprint(wxyzsep='print(wxyzsep='print(wxyzsep='print(wxyzsep=''the output , , , : : : formatting numbers and strings format function is used to return formatted string for displaying numbers in certain desirable format for examplethe following code computes interestgiven the amount and the annual interest rate amount interestrate interest amount interestrate print("interest is"format(interest ")interest is the syntax to invoke this function is format(itemformat-specifierwhere item is number or string and format-specifier is string that specifies how the item is formatted the function returns string sp_python programming
11,090
sscasc@tumkur frequently used specifiers specifier format " fformat the float item with width and precision " eformat the float item in scientific notation with width and precision " dformat the integer item in decimal with width " xformat the integer item in hexadecimal with width " oformat the integer item in octal with width " bformat the integer item in binary with width " %format the number in decimal " sformat the string item with width "< fleft-justify the formatted item "> fright-justify the formatted item placeholder substitution within formatting string print('{ { }format( ** )this expression has two main parts'{ { }'this is known as the formatting string it is python string because it is sequence of characters enclosed with quotes notice that the program at no time prints the literal string { { this formatting string serves as pattern that the second part of the expression will use { and { are placeholdersknown as positional parametersto be replaced by other objects this formatting stringthereforerepresents two objects separated by single space format( ** )this part provides arguments to be substituted into the formatting string the first argument will take the position of the { positional parameter in the formatting string the value of the second argument ** which is will replace the { positional parameter sp_python programming
11,091
sscasc@tumkur program to illustrate format specifier print(format( " ")print(format( " ")print(format( " %")print(format( " ")print(format( "< "))#left justfy print(format( " "))#converts to hexadecimal print(format("welcome to python"" ")print(format("welcome to python""< ")print(format("welcome to python""> "))#right justify print('{ { }format( , ** )print('sum of { and { is { }format( , , + )output control statements if statements one-way if statement executes the statements if the condition is true the syntax for one-way if statement isif boolean-expressionstatement(snote that the statement(smust be indented the reserved word if begins if statement the condition is boolean expression that determines whether or not the body will be executed colon (:must follow the condition the block is block of one or more statements to be executed if the condition is true the statements within the block must all be indented the same number of spaces from the left the block within an example:to demonstrate simple if #get two integers from the user dividend int(input('please enter the number to divide')sp_python programming
11,092
sscasc@tumkur divisor int(input('please enter dividend')if possibledivide them and report the result if divisor ! quotient dividend/divisor print(dividend'/'divisor"="quotientprint('program finished'output please enter the number to divide please enter dividend program finished if-else statements two-way if-else statement decides which statements to execute based on whether the condition is true or false the syntax for two-way if-else statementif boolean-expressionstatement( #for-the-true-case ,the statement(smust be indented elsestatement( #for-the-false-case exampleto demonstrate if else percent=float(input("enter percentage")if percent > print ("congratulationsyou got an "print ("you are doing well in this class"elseprint ("you did not get an "print ("see you in class next week"nested if statements series of tests can written using nested if statements examplenestedif percent=float(input("enter percentage")if (percent > )print ('congratuationsyou got an 'elseif (percent > )print ('you got 'elseif (percent > )print ('you got 'elseprint ('your grade is less than 'sp_python programming
11,093
sscasc@tumkur if_elif_else statement in python we can define series of conditionals (multiple alternativesusing if for the first oneelif for the restup until the final (optionalelse for anything not caught by the other conditionals example:if_elif_else score=int(input("enter score")if score > grade 'aelif score > grade 'belif score > grade 'celif score > grade 'delsegrade 'fprint("grade=",gradeusing else if instead of elif will trigger syntax error and is not allowed loops it is one of the most basic functions in programmingloops are an important in every programming language loops enable is to execute statement repeatedly which are referred to as iterations ( loop is used to tell program to execute statements repeatedlythe simplest type of loop is while loop the syntax for the while loop iswhile loop-continuation-conditionloop body statement(snote that the statement(smust be indented initialvalue initialize loop-control variable while endvalueloop body + adjust loop-control variable example to demonstrate while count #program to print "programming is fun!for times while count print("programming is fun!"count count example #program to read series of values from the usercount the #number of itemsand print their countsum and average #user indicates the end of the input by typing the special value sp_python programming
11,094
sscasc@tumkur sum count num=int(input("enter your number:")while num !- sum sum num count count num =int(input("enter your number:")print ("count is :"countprint ("sum is :"sumprint ("average is :"sum countthe for loop for loop iterates through each statements in sequence for exactly know many times the loop body needs to be executedso control variable can be used to count the executions loop of this type is called counter-controlled loop in generalthe loop can be written as followsfor in range(initialvalueendvalue)loop body note that the statement(smust be indented in generalthe syntax of for loop isfor var in sequenceloop body the function range(abreturns the sequence of integers aa - and the range function has two more versions you can also use range(aor range(abkrange(ais the same as range( ak is used as step value in range(abkthe first number in the sequence is each successive number in the sequence will increase by the step value is the limit the last number in the sequence must be less than example :to demonstrate for for in range( )print (iexample str=input("enter string"for ch in strif ch in 'aeiou'print ('letter'ch'is vowel'elseprint ('letter 'ch'is not vowel'sp_python programming
11,095
sscasc@tumkur output of example we can iterate through list by using forexample for in ['one''two''three''four']print(xthis will print out the elements of the listone two three four iterating over dictionariesconsidering the following dictionaryd {" " " " " " #to iterate through its keyswe can usefor key in dprint(key)outputoutput" " "csp_python programming
11,096
sscasc@tumkur break and continue in loops break statementwhen break statement executes inside loopcontrol flow comes out of the loop immediatelyexample:to demonstrate break while print(iif = print("breaking from loop"break + the loop conditional will not be evaluated after the break statement is executed note that break statements are only allowed inside loops break statement inside function cannot be used to terminate loops that called that function executing the following prints every digit until number when the break statement is met and the loop stopsoutput breaking from loop break statements can also be used inside for loopsthe other looping construct provided by pythonexamplefor in ( )print(iif = break executing this loop now prints note that and are not printed since the loop has ended continue statement continue statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop continue can only used inside loopsexample to demonstrate continue for in ( )if = or = continue print(inote that and aren' printedthis is because continue goes to the next iteration instead of continuing on to print(iwhen = or = sp_python programming
11,097
sscasc@tumkur executing this loop now prints the pass the pass statement is used in code in places where the language requires statement to appear but we wish the program to take no action we can make the code fragment legal by adding pass statementif pass do nothing elseprint(xpass is null statementwhen statement is required by python syntax (such as within the body of for or while loop)but no action is required or desired by the programmer this can be useful as placeholder for code that is yet to be written exampleto demonstrate pass for in range( )pass #we don' want to do anythingso we'll pass in this examplenothing will happen the for loop will complete without errorbut no commands or code will be actioned pass allows us to run our code successfully without having all commands and action fully implemented similarlypass can be used in while loopsas well as in selections and function definitions etc nested loops loop can be nested inside another loop nested loops consist of an outer loop and one or more inner loops each time the outer loop is repeatedthe inner loops are reentered and started new below is classical example for nesting of loops examplemultiplcationtable print(multiplication table"display the number title print(|"end ''for in range( )print("jend 'print(jump to the new line print(""display table body for in range( )print( "|"end ''display the product and align properly for in range( )print(format( " ")end ''print(jump to the new line output sp_python programming
11,098
sscasc@tumkur functions function is collection of statements grouped together that performs an operation function is way of packaging group of statements for later execution the function is given name the name then becomes short-hand to describe the process once definedthe user can use it by the nameand not by the steps involved once againwe have separated the "whatfrom the "how" abstraction functions in any programming language can fall into two broad categoriesbuilt-in functions they are predefined and customizedby programming languages and each serves specific purpose user-defined functions they are defined by users as per their programming requirement there are two sides to every python functionfunction definition the definition of function contains the code that determines the function' behaviour function call function is used within program via function invocation defining function function definition consists of the function' nameparametersand body the syntax for defining function is as followsdef functionname(list of parameters)statements note that the statement(smust be indented return function contains header and body the header begins with the def keywordfollowed by the function' name known as the identifier of the function and parametersand ends with colon the variables in the function header are known as formal parameters or simply parameters when function is invokedyou pass value to the parameter this sp_python programming
11,099
sscasc@tumkur value is referred to as an actual parameter or argument parameters are optionalthat isa function may not have any parameters statement(salso known as the function body are nonempty sequence of statements executed each time the function is called this means function body cannot be emptyjust like any indented block some functions return valuewhile other functions perform desired operations without returning value if function returns valueit is called valuereturning function calling function calling function executes the code in the function in function' definitionyou define what it is to do to use functionyou have to call or invoke it the program that calls the function is called caller there are two ways to call functiondepending on whether or not it returns value if the function returns valuea call to that function is usually treated as value for examplelarger max( calls max( and assigns the result of the function to the variable larger another example of call that is treated as value is print(max( )this prints the return value of the function call max ( examplereturn the max of two numbers function with arguments and return def max(num num )if num num result num elseresult num return result def main() sp_python programming