1 / 22

Functions, Modules, Exception handling , File I/O

Functions, Modules, Exception handling , File I/O. Functions, Modules, File I/O, Exception handling. Functions (Ch4) Modules (Ch4) Exception handling (Ch12) File I/O (Ch14). Functions. Functions, Modules, File I/O, Exception handling.

boyce
Download Presentation

Functions, Modules, Exception handling , File I/O

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions, Modules, Exception handling, File I/O Functions, Modules, File I/O, Exception handling • Functions (Ch4) • Modules (Ch4) • Exception handling (Ch12) • File I/O (Ch14)

  2. Functions Functions, Modules, File I/O, Exception handling • To understand how to construct programs modularly from small pieces called functions. • To create new functions. • To understand the mechanisms of exchanging information between functions. • To introduce simulation techniques using random number generation. • To understand how the visibility of identifiers is limited to specific regions of programs. • To understand how to write and use recursive functions, i.e., functions that call themselves. • To introduce default and keyword arguments.

  3. Functions Functions, Modules, File I/O, Exception handling Functions allow the programmer to modularize a program. All variables created in functiondefinitions are local variablesthey are known only to the function in which they are declared. Most functions have a list of parameters (which are also local variables) that provide the means for communicating information between functions. Whyweusefunctions? divide-and-conquerapproach software reusability toavoidrepeatingcode defname_of_function ( list of formalparameters) : body of function localvariables

  4. Functions Functions, Modules, File I/O, Exception handling Module math Functions A module contains function definitions and other elements (e.g., class definitions) that perform related tasks. The math module contains functions that allow programmers to perform certain mathematical calculations. import math print (math.sqrt( 900 )) c,d,f=(3,2,3) print (math.sqrt( c + d * f ))

  5. FunctionDefinations Functions, Modules, File I/O, Exception handling defkare( y ):return y * y for x in range( 1, 11 ): print (kare( x )) defenbuyukdeger(x, y, z): enb = x if y > enb: enb = y if z > enb: enb = z returnenb x,y,z=(4,10,8) print (enbuyukdeger(x,y,z))

  6. FunctionRondom Functions, Modules, File I/O, Exception handling import random frequency1 = 0 frequency2 = 0 frequency3 = 0 frequency4 = 0 frequency5 = 0 frequency6 = 0 for roll in range(1, 6001): # 6000 die rolls face = random.randrange(1, 7) if face == 1: frequency1 += 1 elif face == 2: frequency2 += 1 elif face == 3: frequency3 += 1 elif face == 4: frequency4 += 1 elif face == 5: frequency5 += 1 elif face == 6: frequency6 += 1 else: # simple error handlingprint ("should never get here!") print ("Face %13s" % "Frequency") print (" 1 %13d" % frequency1) print (" 2 %13d" % frequency2) print (" 3 %13d" % frequency3) print (" 4 %13d" % frequency4) print (" 5 %13d" % frequency5) print (" 6 %13d" % frequency6) import random for i in range(1, 21): # simulates 20 die rolls print ("%10d" % (random.randrange(1, 7)),)

  7. Function-Game of Chance Functions, Modules, File I/O, Exception handling A playerrollstwodice. Eachdie has sixfaces. Thesefacescontain 1, 2, 3, 4, 5 and 6 spots. Afterthedicehavecometo rest, thesum of thespots on thetwoupwardfaces is calculated. Ifthesum is 7 or 11 on thefirstthrow, theplayerwins. Ifthesum is 2, 3 or 12 on thefirstthrow (called “craps”), theplayerloses (i.e., the “house” wins). Ifthesum is 4, 5, 6, 8, 9 or 10 on thefirstthrow, thenthatsumbecomestheplayer’s “point.” Towin, youmustcontinuerollingthediceuntilyou “makeyourpoint.” Theplayerlosesbyrolling a 7 beforemaking thepoint.

  8. Function-Scope Rules Functions, Modules, File I/O, Exception handling x = 1 # global variable # alters the local variable x, shadows the global variable def a(): x = 25 print ("\nlocal x in a is", x, "after entering a") x += 1 print ("local x in a is", x, "before exiting a") # alters the global variable x def b(): global x print ( "\nglobal x is", x, "on entering b") x *= 10 print ("global x is", x, "on exiting b") print ("global x is", x) x = 7 print ("global x is", x) a() b() a() b() print ("\nglobal x is", x)

  9. KeywordImportandNamespaces Functions, Modules, File I/O, Exception handling We explore how importing a module affects a program’s namespace and discuss various ways to import modules into a program. Importing one or more modules importmath We can usemath.sqrt(9.0)

  10. KeywordimportandNamespaces Functions, Modules, File I/O, Exception handling Importing identifiers from a module Binding names for modules and module identifiers from math import sqrt as karakok print (karakok(4))

  11. Functions- Recursion Functions, Modules, File I/O, Exception handling A recursive function is a function that calls itself. deffactorial( number ):ifnumber <= 1: # basecasereturn1else:returnnumber * factorial( number - 1 ) # recursivecallfori in range( 11 ):print("%2d! = %d" % ( i, factorial( i ) ))

  12. Functions- Recursion Functions, Modules, File I/O, Exception handling The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, … begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. fibonacci( 0 ) = 0 fibonacci( 1 ) = 1 fibonacci( n ) = fibonacci( n – 1 ) + fibonacci( n – 2 )

  13. Functions- Recursion Functions, Modules, File I/O, Exception handling The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, … begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. fibonacci( 0 ) = 0 fibonacci( 1 ) = 1 fibonacci( n ) = fibonacci( n – 1 ) + fibonacci( n – 2 )

  14. Functions- Arguments Functions, Modules, File I/O, Exception handling

  15. Exception Handling (Ch12) Functions, Modules, File I/O, Exception handling An exception is an indication of a “specialevent” that occurs during a program’s execution. The name “exception” indicates that, although the event can occur, the event occurs infrequently. Often, the special event is an error (e.g., dividing by zero or adding two incompatible types); sometimes, the special eventis something else (e.g., the termination of a for loop). Exception handling enables programmers to create applications that can handle (or resolve) exceptions.

  16. Try..Exception Functions, Modules, File I/O, Exception handling try: hata verebileceğini bildiğimiz kodlar exceptHataAdı: hata durumunda yapılacak işlem number1 = input( "Enternumerator: " )number2 = input( "Enterdenominator: " )# attempttoconvertanddividevaluestry: number1 = float( number1 ) number2 = float( number2 )result = number1 / number2exceptValueError: # floatraises a ValueErrorexceptionprint("Youmustentertwonumbers")exceptZeroDivisionError: # divisionbyzeroraises a ZeroDivisionErrorexceptionprint("Attemptedtodividebyzero")else:# else clause'ssuiteexecutesiftrysuiteraisesnoexceptionsprint("%.3f / %.3f = %.3f" % ( number1, number2, result )) except (ValueError, ZeroDivisionError): print("an erroroccurred")

  17. Try..Exception as, else, finally Functions, Modules, File I/O, Exception handling ilk_sayi = input("ilk sayı: ")ikinci_sayi = input("ikinci sayı: ")try: sayi1 = int(ilk_sayi) sayi2 = int(ikinci_sayi)except ValueError as hata:print("Sadece sayı girin!")print("orijinal hata mesajı: ", hata)else:try:print(sayi1, "/", sayi2, "=", sayi1 / sayi2)except ZeroDivisionError:print("Bir sayıyı 0'a bölemezsiniz!") try: komutlar… exceptbirHata: Hata durumunda yapılacaklar finally: hata olsa da olmasa da yapılması gerekenler... try: file1 = open("filename", "r")exceptIOError:print("An erroroccured")finally: file1.close()

  18. Raise Functions, Modules, File I/O, Exception handling #Raise------------------------------------------ #Using finally clauses.def doNotRaiseException():# try block does not raise any exceptionstry:print( "In doNotRaiseException")# finally executes because corresponding try executedfinally:print( "Finally executed in doNotRaiseException")print( "End of doNotRaiseException")def raiseExceptionDoNotCatch():# raise exception, but do not catch ittry:print( "In raiseExceptionDoNotCatch")raise Exception# finally executes because corresponding try executedfinally:print( "Finally executed in raiseExceptionDoNotCatch")print( "Will never reach this point")# main programdoNotRaiseException()# Case 2: Exception occurs, but is not handled in called function, # because no except clauses exist in raiseExceptionDoNotCatchprint( "\nCalling raiseExceptionDoNotCatch")# call raiseExceptionDoNotCatchtry: raiseExceptionDoNotCatch()# catch exception from raiseExceptionDoNotCatchexcept Exception:print("Caught exception from raiseExceptionDoNotCatch in main program.")# Case 1: No exceptions occur in called function.print("Calling doNotRaiseException") #-----Raise an error -----nopasschar = ".-şçğüöıİ"password = input("Password: ")for l in password:if l in nopasschar:raise TypeError("wrong char in password")else:passprint("Password is approved!")

  19. File Processing (ch14) Functions, Modules, File I/O, Exception handling Creating a Sequential-Access File importsys# open filetry: file = open( "clients.Txt", "w" ) # open file in writemodeexceptIOError: # file openfailedprint("File could not be opened:")sys.exit( 1 )print("Entertheaccount, name andbalance.")print("Enterend-of-file toendinput.")while1:accountLine = input("? ") # getaccountentryifaccountLine=='EOF':break # userentered EOFelse:print(accountLine, file=file)file.close() print(accountLine, file=file)

  20. File Processing (ch14) Functions, Modules, File I/O, Exception handling Reading a Sequential-Access File importsys# open filefile = open( "clients.txt", "r" ) # open file in writemodetry:passexceptIOError: # file openfailedprint("File could not be opened:")sys.exit( 1 )records = file.readlines()print("Account".ljust( 10 ),"Name".ljust( 10 ),"Balance".rjust( 10 ))forrecordin records: # format eachlinefields = record.split()print(fields[ 0 ].ljust( 10 ), fields[ 1 ].ljust( 10 ), fields[ 2 ].rjust( 10 ))file.close()

  21. File Processing - seek Functions, Modules, File I/O, Exception handling importsys# retrieveoneusercommanddef getRequest():while1:request = int(input("\n? "))if1 <= request <= 4:breakreturnrequest# determineifbalanceshould be displayed, based ondef shouldDisplay(accountType, balance):ifaccountType == 2 andbalance < 0: # creditreturn1elif accountType == 3 andbalance > 0: # debitbalancereturn1elif accountType == 1 andbalance == 0: # zerobalancereturn1else:return0# printformattedbalance datadef outputLine(account, name, balance):print( account.ljust(10),name.ljust(10), balance.rjust(10))# open filetry: file = open("clients.txt", "r")exceptIOError:print("File could not be opened:")sys.exit(1) print("Enter request")print("1 - List accounts with zero balances")print("2 - List accounts with credit balances")print("3 - List accounts with debit balances")print("4 - End of run")# process user request(s)while 1: request = getRequest() # get user requestif request == 1: # zero balancesprint ("\nAccounts with zero balances:")elif request == 2: # credit balancesprint("\nAccounts with credit balances:")elif request == 3: # debit balancesprint("\nAccounts with debit balances:")elif request == 4: # exit loopbreak else: # getRequest should never let program reach hereprint("\nInvalid request.") currentRecord = file.readline() # get first record# process each linewhile (currentRecord != ""): account, name, balance = currentRecord.split() balance = float(balance)if shouldDisplay(request, balance): outputLine(account, name, str(balance)) currentRecord = file.readline() # get next recordfile.seek(0, 0) # move to beginning of fileprint ("\nEnd of run.")file.close() # close file

  22. Advanced Computer Programming Sinan AYDIN Functions, Modules, Exception handling, File I/O

More Related