Programming In Python 3 - Ase

1y ago
11 Views
2 Downloads
7.21 MB
113 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Aydin Oneil
Transcription

PROGRAMMING IN PYTHON 3.XCATALIN BOJACATALIN.BOJA@IE.ASE.ROBOGDAN IANCUBOGDAN.IANCU@IE.ASE.RO

SCOPE Understand the language fundamental concepts Understand how to use and what’s the development cycle Being able to read and understand Python source code Prerequisite for starting to modify and write Python source code2018 CATALIN BOJA

OTHER RESOURCES https://docs.python.org/3/library/ https://docs.python.org/3/tutorial/ https://www.learnpython.org/en https://www.tutorialspoint.com/python/ https://automatetheboringstuff.com/ Paul Barry David Griffiths, Head First Programming Python, O’Reilly2018 CATALIN BOJA

UNDERSTANDING PYTHONSection I – Python fundamentals basic concepts: interpreter, scripts Prerequisites, using an IDE – IDLE Basic Python Concepts: syntax and coding styles, data types, variables,operators, control structures, strings, some collections, functions, lambdaexpressions, exceptions, files2018 CATALIN BOJA

UNDERSTANDING PYTHONSection II – Python advanced topics Modules Classes and objects Regular expressions Iterators and Generators2018 CATALIN BOJA Database Networking UI Standard Library Multithreading

PREREQUISITES Almost none Some knowledge about some programming languages (any) To know what is a variable or a function Ability to abstract problems Ability to follow logic flows2018 CATALIN BOJA

WHAT IS PYTHON? an interpreted programming language easy to learn, powerful high-level programming language object-oriented ranked 5th in TIOBE index (August 2017) - http://www.tiobe.com/tiobe-index/ used for rapid application development created by Guido van Rossum during 1985-1990 at the National ResearchInstitute for Mathematics and Computer Science in the Netherlands2018 CATALIN BOJA

WHY USING PYTHON ? easy to learn, to read and maintain is portable and extendable supports functional, structured programming methods and OOP provides very high-level dynamic data types supports dynamic type checking supports automatic garbage collection it can be integrated with C, C and Java2018 CATALIN BOJA

THE TOOLS Windows and Linux/Unix distributions on https://www.python.org/downloads The Python interpreter, python, is in the installed folder /usr/local/bin/python for Linux C:\Python - the path of the Python directory (or any other path) A free IDE for Linux and Unix is IDLE - https://www.python.org/downloads/ A editor: Notepad , Sublime, JEdit2018 CATALIN BOJA

PYTHON BASICS Python Application Structure Python Development Steps Hello World application Command line development with Python 3 Using an IDE - IDLE \Python\Section1\Hello.py2018 CATALIN BOJA

PYTHON FUNDAMENTALSPython source code - module.py file Interpret and execute – python.exe source.pyExecuted by CPython interpreterCPython compiles your python code into bytecode (transparently) andinterprets that bytecode in a evaluation loop. It is implemented in C.2018 CATALIN thon-vs-cpython

PYTHON FUNDAMENTALS Start the python interpreter with optional arguments -d – provides debug output-O – generates optimized bytecode (resulting in .pyo files)-v - verbose outputC cmd - run Python script sent in as cmd stringfile - run Python script from given fileMore available with python.exe -h2018 CATALIN BOJA

PYTHON FUNDAMENTALS1. Needed software and tools a simple ASCII editor (Notepad , Sublime, JEdit, or other) for writing sourcefiles; Python interpreter, python.exe for Windows to compile and run source codescripts, .py; Python libraries2018 CATALIN BOJA

INSTALLING PYTHON ON WINDOWS python.exe (for Windows) is obtained by installing the Python SDK (SoftwareDevelopment Kit), obtained from the https://www.python.org/downloads/site; the executable is available in your installation folder (eg. D:\PythonInstall); If you use Sublime (https://www.sublimetext.com/) you can set it up with thefollowing add-ons: imetext-3-for-full-stack-python-development/2018 CATALIN BOJA

INSTALLING PYTHON ON LINUX/UBUNTU Python can be build by downloading the source code n-352/ site; For Ubuntu: sudo apt-get install python3-minimal If you use Sublime (https://www.sublimetext.com/) you can set it up with thefollowing add-ons: imetext-3-for-full-stack-python-development/2018 CATALIN BOJA

PYTHON FUNDAMENTALS1.Edit the source code with your chosen editor;2.Open the command prompt; select Windows Start, type cmd.exe and press Enter;3.Check if the system knows where to find the two executables, python.exe4.Set environment variables (if needed)set PYTHONPATH D:\PythonInstallset PATH %PYTHONPATH%\binset PYTHONHOME %PYTHONPATH%\Lib;2018 CATALIN BOJA

PYTHON FUNDAMENTALS5. Compile, interpret and run the source coded:\PythonExamples python.exe HelloWorld.py6. Run the Python applicationAn alternative is to use an IDE: IDLE (https://www.python.org/downloads/) Environments PyCharm from JertBrains2018 CATALIN BOJA

DEVELOPMENT CYCLE Use the interpreter in an interactive mode Write Python scripts (files with .py extension) and run themwith the interpreter2018 CATALIN BOJA

DEVELOPMENT CYCLEPython interactive interpreterPython IDLE editor2018 CATALIN BOJA

PYTHON 3.X VS 2.X 3.x introduces some significant changesNew features can be imported via the in-built future module in Python 2from future import division https://wiki.python.org/moin/Python2orPython3 https://www.tutorialspoint.com/python3/python3 whatisnew.htm2018 CATALIN BOJA

PYTHON FUNDAMENTALS The language is developed continuously and the official documents are calledPython Enhancement Proposals (PEPs) available onhttps://www.python.org/dev/peps/ The official documentation is available on https://www.python.org/doc/ andthere are 2 major versions 2.x (2.7 being the latest) and 3.x (3.6 at thismoment)2018 CATALIN BOJA

PYTHON FUNDAMENTALS one line comments defined by # Python language is case sensitive, vb as variable is different than Vb or VBmultiple lines comments – each line must be commented individuallythe end delimiter for a instruction is Enter (CRLF);commented instructions are ignored;instructions can be associated in blocks of code that are defined by the same level ofindentation; there is no { } like in Java or C/C Imports should usually be on separate lines2018 CATALIN BOJA

PYTHON CODING STYLE “code is read much more often than it is written” (Guido van Rossum) Readability is the source code quality that measures the easiness/difficulty ofreading it If a source is easy to read then it is easy to understand, test and change Coding styles rules are part of the Clean Code principles For Python the coding rules are defined in PEP 8(https://www.python.org/dev/peps/pep-0008/)2018 CATALIN BOJA

PYTHON CODING STYLE Indentation: use 4 spaces per indentation level and avoid TAB (despite it istempting) Maximum Line Length: maximum of 79 characters (and docstrings/commentsto 72). Imports are always put at the top of the file on separate lines Single-quoted strings and double-quoted strings are the same but a singlerule should be used2018 CATALIN BOJA

PYTHON CODING STYLE Avoid extraneous whitespace Avoid trailing whitespace anywhere always surround binary operators ( , -, , , etc.) with a single space oneither side Avoid comments at all cost – the code should explain itself2018 CATALIN BOJA

PYTHON CODING STYLE Package and Module Names: short, all-lowercase names Class Names: should normally use the CapWords convention Exception Names: CapWords convention with the suffix "Error" Function Names: lowercase, with words separated by underscores Constants: all capital letters with underscores separating words2018 CATALIN BOJA

PYTHON CODING STYLEThe Zen of Python (by Tim Peters) rulesPEP 20 - https://www.python.org/dev/peps/pep-0020/And some exampleshttp://artifex.org/ hblanks/talks/2011/pep20 by example.pdf2018 CATALIN BOJA

PYTHON - VARIABLESOther languages have "variables“,Python has "names"http://python.net/ #other-languages-have-variables2018 CATALIN BOJA

PYTHON - VARIABLESBuilt in types:1.2.Numeric: integer, bool, float, complexSequences, mappings, classes, instances and exceptions3. Mutable Objects: integer, float, complex, str (string), bytes, tuple, frozen set4. Immutable Objects: byte array, list, set, dictionary2018 CATALIN BOJA

PYTHON - VARIABLESValue datatypeintfloatSizeRange for signed valuesCategory 8 bytes equivalent to C longs in Python 2.x, non-limited integerlength in Python 3.x8 bytes7 significant digitsreal double precisioncomplexa complex number with thevalue real imag*1jcomplex valuebooleanTrue, 1 or any value different from 0False, 0, 0.0, '', (), [], {}Logic/truth value2018 CATALIN BOJA

PYTHON - VARIABLES variable name must begin with a letter or underscore symbol ( ); variable names can not begin with a digit; after first character, you can use digits in the variable name; variable name can not be a word reserved for Python language, a keyword; several variables can be defined simultaneously using , ; can’t use @, , and % within variables names2018 CATALIN BOJA

PYTHON - VARIABLES variable names are chosen by the programmer, but for efficiency, there aresome naming conventions about variable names: Hungarian notation ,CamelCase;iBooksNumber#Hungarian NotationBooksNumber#CamelCase or CapsWordsbooksNumber#Java mixed case2018 CATALIN BOJA

PYTHON - VARIABLES class names should normally use the CapWords convention you should use the suffix "Error" on your exception names function names should be lowercase, with words separated by underscores ormixedCase use one leading underscore only for non-public methods and instance variables constants are usually defined in all capital letters with underscores separating ing-conventions2018 CATALIN BOJA

PYTHON - VARIABLES Python is a dynamically typed language – the variable name is bound to theobject, at executionvb2 23.5#variable vb2 is assign to a floatvb2 34#variable is reassign to an integervb2 True#variable is reassign to a bool value Java is statically typed language;2018 CATALIN BOJA

PYTHON - VARIABLES Python is a strongly typed language - variables can NOT be implicitly converted tounrelated types without an explicit conversionvb3 "test"vb4 vb3 56#generates TypeError: Can't convert#'int' object to str implicitlyvb4 vb3 str(56)2018 CATALIN BOJA# works

PYTHON - VARIABLES several variables can be initialized at the same timevb4 , vb5, vb6 1, 23, "test" string symbols are defined between ‘ ‘ (apostrophe) or between " " (quotationmarks); integer values in base 16 (hexadecimal representation) are prefixed with 0x,for example 0 11 is 17 in base 10;2018 CATALIN BOJA

PYTHON - VARIABLESIn Python local variables are not initializedby default, because they are justnames/symbolsYou can’t use them without giving them a value2018 CATALIN BOJA

PYTHON - VARIABLESvalue1value2 value1 1002018 CATALIN BOJA#generates NameError: name#'value1' is not defined

PYTHON – SEQUENCE TYPES str – strings or arrays of Unicode characters bytes – array of bytes bytearray – array of bytes list – list of values tuple – read-only list of values range – generator for a list2018 CATALIN BOJA

PYTHON – STRINGS String string values (equivalent of string in Java or String in C#) used as primitives a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python wascompiled) Immutable entities that DO NOT change their value almost all values in Python2018 CATALIN BOJA

PYTHON – STRINGS every char is Unicode value; are written in single or double quotes: 'abc', "abc"; the syntax allows you to use Strings as primitive data types (you can use operator to initialize them); Strings variables are immutable, meaning that once are created, they can’tchange their value2018 CATALIN BOJA

PYTHON – STRINGS you can use to compare 2 strings value you can use (plus) to concatenate 2 strings you can use * (asterisk) to repeat strings in and not in operators can be used to check for substrings strings are different than byte literals (defined using the b prefix) as latterare arrays of small integers (0 to 255)2018 CATALIN BOJA

PYTHON – STRINGS (plus) does NOT convert numbers or other types to string; you need to usestr() methodname ’Alice’value 23name valuename str(value)2018 CATALIN BOJA#error

PYTHON – STRINGS using [] (slice) operator you can access a single or more charsstring[index] the index starts at 0 and should not exceed the string length you can use negative numbers for an index string[start : end] - using a start index and an end index in [] – slice in a slice you can omit the start index, the end index or gs2018 CATALIN BOJA

PYTHON – STRINGSname ame[-2:]#'lo‘name[:3]#'Hel‘name[5]#IndexError: string index out of range2018 CATALIN BOJA

PYTHON – STRINGSMethodDescriptionreplace()replace occurrences of a substring with a given onesplit()returns a list of the words in the string, using a given delimiter stringlower()converts all chars to lowercaseupper()converts all chars to uppercasestrip()removes leading and trailing whitespacefind()returns the lowest index in the string where a given substring is foundThese methods will create a copy of the StringMore on string-methods2018 CATALIN BOJA

PYTHON – STRINGS several variables can be initialized at the same time using split()names 'John Alice Bob Bianca‘father, mother, son, daughter names.split()2018 CATALIN BOJA

PYTHON – STRINGSchar variables can have as values a series of special characters, escape sequences:Escape sequencesValue\bbackspace\ttab\nline feed\fform feed\rcarriage return\”double quotes\’apostrophe\\backslash2018 CATALIN BOJA

PYTHON – STRINGS Strings can be formatted using % specifier; similar to sprint() and printf() in Cvb1 ‘John’vb2 3text ('Hello %s, you have %i messages' % (vb1,vb2)) you can use the r specifier to use a raw string2018 CATALIN BOJA

PYTHON – STRINGSFormat SymbolConversion%ccharacter%sstring conversion via str() prior to formatting%isigned decimal integer%dsigned decimal integer%uunsigned decimal integer%ooctal integer%ffloating point real n strings.htm2018 CATALIN BOJA

PYTHON – STRINGS triple quotes """ can be used to define a string that spans over multiple linesname """Testing a very longmessage that requires morethan 2 lines"""2018 CATALIN BOJA

PYTHON – LISTS/ARRAYSarray name []#empty list/arrayarray name [value1,value2, ] defined using [] (square brackets)different than C/C arrays – is in fact a listhas methods: count(), extend(), index(), insert(), pop(),remove(), reverse(), sort()2018 CATALIN BOJA

PYTHON – LISTS/ARRAYS array values are mutable; using you can define multiple variables that willreference the same array an array is initialized in 2 steps: define the array; append values access to array elements is done using operator [] and in index that starts at 02018 CATALIN BOJA

PYTHON – LISTS/ARRAYS A list can contain values with different typeslist [23,'test',123.4] you can use to compare 2 list values you can use (plus) to concatenate 2 lists you can use * (asterisk) to repeat a list2018 CATALIN BOJA

PYTHON – LISTS/ARRAYSvector1 []empty arrayvector2 [1,2,3,4]vector3 [5,6,7,8]vector21,2,3,4vector35,6,7,8vector3 vector2vector3vector3[0] 10vector2vector32018 CATALIN BOJA10,2,3,4

PYTHON – TUPLEStuple name ()#empty tupletuple name (value1,value2, ) is similar to the list but is read-only tuples are enclosed within () parentheses it has less methods: index(), count()2018 CATALIN BOJA

PYTHON – TUPLES when defining a tuple with 1 element, the , (comma) is mandatorytuple (34,) Because they are read-only you can’t change their valuestuple2 (34,35,36)tuple2[1] 78item assignment2018 CATALIN BOJA#TypeError: 'tuple' object does not support

PYTHON – RANGE range() is a built-in function used to generate a list of numbersrange([start], stop[, step]) start is by default 0 step is by default 1 all parameters are integer values can be positive or negative values2018 CATALIN BOJA

PYTHON – DICTIONARYdictionary name {} defined using {} (curly braces) similar to maps collections in Java is a list of key-value pairs2018 CATALIN BOJA#empty dictionary

PYTHON – DICTIONARY a key-value pair is added/used using square braces []dictionary name[key value] value the key or the value can have any type2018 CATALIN BOJA

PYTHON FUNDAMENTALS - GARBAGE COLLECTOR solve some problems regarding memory management – memory leaks inC ; it is an efficient CPython routine that will not interfere with your Python appperformance; it will not save any out of memory situation you can request garbage collector to make a memory clean explicitly byinvoking the gc.collect() methodof the gc module2018 CATALIN BOJA

PYTHON FUNDAMENTALSIn Python INDENTATION is very, very,very important. It makes the difference.It’s a “white space” language2018 CATALIN BOJA

PYTHON FUNDAMENTALS Python doesn't use braces({}) to indicate blocks of code for class and functiondefinitions or flow control. Blocks of code are denoted by line indentation,which is rigidly enforced. The number of spaces in the indentation is variable, but all statements withinthe block must be indented the same on basic syntax.htm2018 CATALIN BOJA

PYTHON FUNDAMENTALS - BLOCKS Blocks begin when current line indentation increases. The statements inside a block must have the same indentation level Blocks can contain other blocks. Blocks end when the indentation decreases to zero or to a containing f.com/chapter2/2018 CATALIN BOJA

PYTHON FUNDAMENTALS - BLOCKSname "Alice"name "Alice"password "12345678"password "12345678"if (name "Alice"):if (name "Alice"):print("Hello " name)print("Hello " name)if (password "12345678"):if (password "12345678"):print("Access granted.")print("Access granted.")print("You can access your files")else:print("You can access your files")else:print("Wrong password.")print("Wrong password.")else:else:print("Wrong user.")print("Wrong user.")2018 CATALIN BOJAGood vs EvilSyntax error

PYTHON FUNDAMENTALS Use 4 spaces per indentation level Spaces are the preferred indentation method Tabs should be used solely to remain consistent with code that is already indentedwith tabs Python 3 disallows mixing the use of tabs and spaces for indentation Continuation lines should align wrapped elements either vertically using Python'simplicit line joining inside parentheses, brackets and braces, or using a hanging ming-conventions2018 CATALIN BOJA

PYTHON FUNDAMENTALS – OPERATORS Assignment operator: Compound assignment operators: , - , * , / Relational operators: , , , , , ! The result is a Bool value (True or False) The equality ( ) operator is doing value check (in C/C or Java you must avoidreference check) For if control structure you can use only relational operators2018 CATALIN BOJA

PYTHON FUNDAMENTALS – OPERATORS Boolean/Logical operators: and, or, not Arithmetic operators: , -, *, /, ** (exponent) Reminder operator: % String concatenation operator: Bit-string operations: , , &, , , Increment and Decrement operators: , - Have 2 forms: prefix and postfix2018 CATALIN BOJA

PYTHON FUNDAMENTALS – OPERATORS Comma operator: , Does not work like the one in C/C Defines a tuple a 3 b 4 a, b b, a b a#prints 4 b#prints 72018 CATALIN BOJA#(x , y) – a pair of values like (a, b) (b, a b)

PYTHON FUNDAMENTALS – OPERATORSThe or statement (x or y): Evaluate x. If x is True return x. Else return yThe and statement (a and y): Evaluate x. If x is False return x. Else return yEmpty string (‘’) and 0 are considered False2018 CATALIN BOJA

PYTHON – CONTROL STRUCTURESFlow control structures: if-then if-then-else while-do for2018 CATALIN BOJA

PYTHON – CONTROL STRUCTURESIF-THENif (condition):-- statement 1 -- statement 2 same indentation level2018 CATALIN BOJA- condition is a Boolean expression orvariable that has the value True orFalse. For example 30 10 or 10 30- are expressions or variables thathave numeric values- the condition parentheses areoptional- the statements must have the sameindentation level

PYTHON – CONTROL STRUCTURESIF-THEN-ELSEif (condition):-- statement-- statementelse:-- statement-- statementsame indentation level2018 CATALIN BOJA1 2 3 4 - the colon (:) is mandatory- condition parenthesis () are optionaland is recommended not to use them

PYTHON – CONTROL STRUCTURESIF-THEN-ELSE-IFif (condition1):-- statement 1-- statement 2elif (condition2):-- statement 3-- statement 4same indentation level2018 CATALIN BOJA - the colon (:) is mandatory- the else-if block will execute ifcondition1 is evaluated to False andthe condition2 is evaluated to True

PYTHON – CONTROL STRUCTURESWHILE-DOwhile condition: statement 1 statement 2 2018 CATALIN BOJA- the condition for exitingfrom/staying in the loop ischecked before the firststatement in the loop block isexecuted

PYTHON – CONTROL STRUCTURESFORfor item in collection: statement 1 statement 2 2018 CATALIN BOJA- like do-while- item iterates through each value- the collection must be a sequence(list, tuples and strings)- is efficient, simply because theiteration and the initializationstatements are included in thestructure and not in the block;

PYTHON – CONTROL STRUCTURESBREAK and CONTINUE statements: break statement stops the current loop block implemented by for, while-do; continue instruction will suspend the current iteration of a loop block, for, whiledo and will execute the next iteration2018 CATALIN BOJA

PYTHON - FUNCTIONSdef function name(arguments list):["function description"] statement1 statement2 return [value] are code sequences that can be reused allow functional programming2018 CATALIN BOJA

PYTHON - FUNCTIONS a function is called by its name, passing the required argumentsfunction name(arguments value)value function name(arguments value) the first statement in the function body can be a description string used for help(similar to JavaDoc) a function can return a value2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTSYou can call a function by using following types of arguments: Required arguments Keyword arguments Default arguments Variable-length arguments2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTS methods receive input parameters by references ATTENTION most data types are immutable so changing their value inside themethod will redefine the variable; collections values are mutable2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTS transfer parameters by their value changing the value inside the function will modify only the local copydef changeValues (value1, value2):value1 "New value"value2 100returnvb1,vb2 10,20changeValues(vb1,vb2)2018 CATALIN BOJA#calling methodCheck Functions.py

PYTHON – FUNCTIONS ARGUMENTS transfer parameters by reference works for collections because their values are mutabledef doSomething2( list ):"Changing list values inside a list - #2"for i in range(0,3):list[i] 10return2018 CATALIN BOJACheck Functions.py

PYTHON – FUNCTIONS ARGUMENTS changing the list reference will create a local copy; changes are not visible outsidedef doSomething3( list ):"Changing list values inside a list - #3"list [30,40,50]return2018 CATALIN BOJACheck Functions.py

PYTHON – FUNCTIONS ARGUMENTS changing the list values using an iterator; changes are not visible outsidedef doSomething1( list ):"Changing list values inside a list - #1"for value in list:value 10return2018 CATALIN BOJACheck Functions.py

PYTHON – FUNCTIONS ARGUMENTS transfer parameters by their referenceHow to do that for a primitive variable ?1. NO way to get the address of a primitive2. Use an array3. Define your own wrapper class/structure2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTS keyword arguments are related only to the function calls; a keyword is in factthe argument name using keyword arguments in a function call, the caller identifies the argumentsby the parameter name. using keyword arguments you can skip arguments or place them out of order2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTSdef doSomething (value1, value2):print("value1 ",value1)print("value2 ",value2)return#using keywordsdoSomething(value1 10,value2 20)doSomething(value2 20, value1 10)2018 CATALIN BOJA

PYTHON – FUNCTIONS ARGUMENTS methods can have variable length inputsdef functionname([formal args,] *var args tuple ):"function description"function suitereturn [expression]2018 CATALIN BOJACheck Functions.py

PYTHON – VARIABLES SCOPE local variables – these variables are defined on the function body and theyexists as long as the method is executed; local variables are not visibleoutside the function body global variables – these variables are defined in the module global scope;global variables can be used inside functions; Shadowing – defining a local variable with the same name as a global one; itwill shadow/hide the global one2018 CATALIN BOJA

PYTHON – VARIABLES SCOPEvalue 'global‘def test1():print (value)returndef test2():value 'local for test2'#shadowing global variableprint(value) # prints 'local for test2'returnVariablesScope.py2018 CATALIN BOJA

PYTHON – USING MODULES A module is a .py script file. It can be reused using import keywordimport module name Module variables and methods are accessed using module name specifiermodule name.variable namemodule name.method name Contextual help can be obtained usingdir(module name) or help(module name)2018 CATALIN BOJA

PYTHON – EXCEPTIONS exception - the situation where processing certain input data is not managed or isnot possible (eg dividing by 0, reading outside the bounders of an array) allows management of exceptional situations that lead to immediate termination ofthe program necessary to achieve robust and reliable programs implemented through try, except, finally and raise allows the management of system exceptions2018 CATALIN BOJA

PYTHON – EXCEPTIONS1.2.Compilation error fail at COMPILE time. You need to correct it.Errors pass the compilation but fail at RUN-TIME because .(ex. Badblocks on the HDD and you get an error trying to open the file).3. Runtime exception pass the compilation but fail at RUN-TIME. You canimplement try-catch, but is better to check and avoid.2018 CATALIN BOJA

PYTHON – EXCEPTIONStry:#statementsexcept exception type 1 as e:#particular statementsexcept exception type 2:#particular statementsexcept:#general statementsfinally:#must do always statements2018 CATALIN BOJA#the name e is optional# catch *all* exceptions

PYTHON – EXCEPTIONStry: contains the sequence of code that may generate exceptions; has at least one catch block; between the try block and catch blocks there are no other instructionsexcept [exception type [as error]]: catch and manage an exception of exception type type exception type is an instance of a class derived from BaseException (more l) you can process the exception if you associate a symbol using [as symbol name]2018 CATALIN BOJA

PYTHON – EXCEPTIONSexcept: catch and manage all exceptionsfinally: contains code sequence that it is executed whether or not the try block hasgenerated exceptions and whether they were or were not managed in othercatch blocks;Exceptions.py2018 CATALIN BOJA

PYTHON – EXCEPTIONScatch blocks are defined in the ascending order of the caught exceptions generality leveltry:except exception type 1:except exception type 2: except :2018 CATALIN BOJA

PYTHON – EXCEPTIONS try-except-finally blocks can be included in other try blocks; The programmer can define its own exceptions with classes derived fromBaseException; raise function generates a new exception; without arguments will rise theprevious error Attention to local variables defined in try or in except blocks and usedoutside. If the variable is not initialized you will get a name is not defined errorExceptions.py2018 CATALIN BOJA

PYTHON – EXCEPTIONS in an except block you can use a raise-else combination; you can change to a finally based logictry:do some stuff()except:rollback()raise#raise the error again if ingExceptions2018 CATALIN BOJA

PYTHON – INPUT two built-in functions to read a line of text from standard input raw input([prompt]) – reads one line from standard input and returns it as astring input([prompt]) – like raw input but assumes the input is a valid Pythonexpression and returns the evaluated result2018 CATALIN BOJA

PYTHON – FILES Files/Folders are opened for read/write using the open(file name [,access mode][, buffering]) function filename – file name for local files

programming in python 3.x catalin boja catalin.boja@ie.ase.ro bogdan iancu bogdan.iancu@ie.ase.ro

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

ASE STUDY GUIDE, Third Ed. Prepare tomorrow's automotive professionals for success on the National ASE Certification Tests with the ASE Test Preparation and Study Guide. This guide covers ASE areas A1-A8, and is designed to help service technicians and students of automotive technology prepare to take the National ASE Certification Tests.

for Sybase ASE . Developer Edition on Windows 7 box. C: \ Sybase \ C:\ sybase \ase-15_0 corresponds to actual ASE database installation C:\ Sybase \ocs-15_0 corresponds to bundled client software (called OCS in Sybase ASE parlance) development kit. It is interestin

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

Python Programming - This is a textbook in Python Programming with lots of Practical Examples and Exercises. You will learn the necessary foundation for basic programming with focus on Python. Python for Science and Engineering - This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications