Advanced Programming - Introduction to Programming and Programming in Python PDF

Summary

This document is an introduction to advanced programming and programming in Python. It covers course information, objectives, assessment, lecturer information, and course resources.

Full Transcript

Advanced Programming Introduction to Programming and Programming in Python Edmond Jajaga, Assoc. Prof. Dr. Course Info MSc Advanced Programming 6 ECTS Lecturer: PhD Edmond Jajaga and  Objectives  Demonstrate advanced knowledge of Object Oriented Analysis and Desig...

Advanced Programming Introduction to Programming and Programming in Python Edmond Jajaga, Assoc. Prof. Dr. Course Info MSc Advanced Programming 6 ECTS Lecturer: PhD Edmond Jajaga and  Objectives  Demonstrate advanced knowledge of Object Oriented Analysis and Design.  Design and implement software employing the principles of modularity, encapsulation, information hiding, abstraction and polymorphism.  Gives you treatment of the “core” members of any application development toolset (with Python being the focus, of course).  Network Programming,  Internet Client Programming  Concurrent and Parallel Programming,  GUI or Web, and Database Programming Assessment Activity Percentage 1. Project (exactly 3 members) 50% 2. Final Exam 50% exam threshold 40p/100p 3. Conference paper presentation 10% Lecturer’s Info  Edmond Jajaga  PhD in CS, Software Engineer, ex-Waiter and ex-Football player  Public Profiles  Google Scholar, Research Gate and Linkedin  Experience  UP  UT  SEEU  EduSoft Course Resources  Online resources:  Moodle  Recommended books:  “Python: Visual QuickStart guide” (3rd Ed), Toby Donaldson  “Python crash course”, Eric Matthes  “Core PYTHON Applications Programming” Third Edition, Wesley J. Chun  “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides How To Use The Course Resources  They are provided to support and supplement this class.  Neither the course notes nor the text books are meant as a substitute for regular class attendance. Feedback Wow I am the What is greatest speaker he talking in the world! about??? Let me know how things are going in the course: Am I covering the material too slowly or too quickly. Can you read the slides and my hand writing. Can you hear me in the class. Etc. Introduction to Core Programming Concepts Introduction to Programming  A computer program is a set of instructions that you write to tell a computer what to do  Programmers do not use machine language when creating computer programs. Instead, programmers tend to use high-level programming languages  Each high-level language has its own syntax and limited set of vocabulary that is translated into machine code by a compiler  In addition to understanding syntax, a programmer must also understand programming logic i.e. the algorithm 9 Getting started with programming 1. Computer Data Storage and Processing 2. Application Types 3. Application Life-Cycle 4. Code Compilation 5. Programming 1: Computer Data Storage and Processing  Computer Number Systems  Programming Languages  Computer Memory  CPUs and Registers Computer Number Systems Computer Language  Digital devices have two stable states, which are referred to as zero and one by convention  The binary number system has two digits, 0 and 1. A single digit (0 or 1) is called a bit, short for binary digit. A byte is made up of 8 bits.  Binary Language: Data and instructions (numbers, characters, strings, etc.) are encoded as binary numbers - a series of bits (one or more bytes made up of zeros and ones) Computer Language (cont.)  Encoding and decoding of data into binary is performed automatically by the system based on the encoding scheme  Encoding schemes 1. Numeric Data: Encoded as binary numbers 2. Non-Numeric Data: Encoded as binary numbers using representative code  ASCII – 1 byte per character  Unicode – 2 bytes per character Computers can only understand numbers, so an ASCII or Unicode code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII table and Unicode (first 128) chars (currently 143,859 characters) Data Hierarchy  Bits  Characters  Fields  Records  Files  Database  Big Data Computer Memory CPUs and Registers Abstract models of modern computer system Programming Languages Machine Languages  Any computer can directly understand only its own machine language, defined by its hardware architecture. Assembly Languages and Assemblers  Machine language was simply too slow and tedious to work with. Instead, programmers began using English-like abbreviations to represent elementary operations. These abbreviations form the basis of assembly languages. High-Level Languages, Compilers and Interpreters  To speed the programming process even further, high-level languages were developed in which single statements could be written to accomplish substantial tasks. High-level languages, such as C#, Visual Basic, C++, C, Objective-C and Java, allow you to write instructions that look almost like everyday English and contain commonly used mathematical expressions. 2: Application Types  Command-Line Applications  Windows and Other GUI Applications  Web-Based Applications Application Types Windows Apps Mobile Apps Web Apps Windows and Other GUI Applications Web-Based Applications 3: Application Life-Cycle  Envisioning and Planning  Developing and Testing  Release and Maintenance Envisioning and Planning Developing and Testing Release and Maintenance Application Lifecycle Management Requirements Maintain Design Test Development Application Lifecycle Management 1. Requirements analysis 2. Design process  Architect  User-experience designer 3. Software Development  Developers  DBAs  Technical Writers 4. Software testing  Black-box testing  White-box testing 5. Release management 4: Code Compilation  Introducing Compiling  Native Code Compiling  Intermediate Code Compiling Introducing Compiling Compilation translates the code that you write in the development environment into an appropriate format for the platform you are using. -Code Compilation  Computer programs are generally written in a high-level language  Computer can only understand machine language  Translation is also known as compilation Source code Language Machine code Compiler Compilation Source Target Code Compiler Program Input Target Program Output  Compiler translates source into target (a machine language program)  Compiler goes away at execution time  Compiler is itself a machine language program, presumably created by compiling some other high-level program  Machine language, when written in a format understood by the OS is object code Interpretation Source Code Interpreter Output Input  The interpreter stays around during execution  It reads and executes statements one at a time Scripting vs. Compiling => Interpreted vs. compiled Programs  Compiling: Converting a human- readable source code file for a program into a computer-readable file (*.exe, *.dll, etc.) that can be executed.  Interpretation: Interpreter reads one instruction at a time from the text file containing a script, converts it to machine-readable form, and then executes it. 36 Interpreting vs. Compiling Advantages of interpreted languages (scripts):  Because a script does not need to be explicitly compiled before each test run, it is faster to write.  Scripts are more likely to run on a variety of systems because they are distributed as text files and do not rely on special binary formats like a compiled program does.  Supports creation/modification of program code on the fly (e.g. Python, Lisp, Prolog, PHP etc.) Advantages of compiled languages:  Machine-readable files run much faster than a script because the work of conversion is already done.  Data in machine-readable files cannot be deciphered by others. This holds true for C and Java programs that are compiled and generate an executable file that consists of binary code. This binary code protects trade secrets and intellectual property, which prevents modifications to commercial products. 37 Mixture of C & I Source Intermediate Program Translator Program VM Output Input  The Python code is first compiled to something called a “byte code”. And it is then passed to the Python Virtual machine where it gets interpreted. So, we can think of Python as a “compiled interpreted” language. Compilation in Python  When the Python software is installed on your machine, minimally, it has:  an interpreter  a support library. Python’s view of interpreter  Interpreter is made up of two parts:  compiler  virtual machine https://indianpythonista.wordpress.com/2018/01/04/how-python-runs/ The interpreter  Interpreter is nothing but a software which can run your Python scripts.  Interestingly, it can be implemented in any programming language!  CPython is the default interpreter for Python which is written in C programming language.  Jython is another popular implementation of python interpreter written using Java programming language. Compilation in JAVA For portability: Java Compiler bytecode ML Interpreter For flexibility: Just In Time (JIT) compiler translates bytecode into ML just before execution Compilation in.NET CIL = MSIL Running Programs  Steps that the computer goes through to run a program: Memory Machine language program (executable file) Input Data Data entered CPU during execution Computed results Program Output Program Execution  Steps taken by the CPU to run a program (instructions are in machine language): 1. Fetch an instruction 2. Decode (interpret) the instruction 3. Retrieve data, if needed 4. Execute (perform) actual processing 5. Store the results, if needed 5. Programming  Programming – the creation of an ordered set of instructions to solve a problem with a computer.  Only about 100 instructions that the computer understands - Different programs will just use these instructions in different orders and combinations.  The most valuable part of learning to program is learning how to think about arranging the sequence of instructions to solve the problem or carry out the task Programming Fundamentals: Putting the Instructions Together  Sequential Processing  A List of Instructions  Conditional Execution  Ifs  Repetition  Looping / Repeating  Stepwise Refinement / Top-Down Design  Breaking Things into Smaller Pieces  Calling Methods / Functions / Procedures / Subroutines  Calling a segment of code located elsewhere  Reuse of previously coded code segment Paradigms of Programming Languages  Procedural Defining set of steps to transform inputs into outputs Translating steps into code Constructed as a set of procedures Each procedure is a set of instructions C, Pascal, and Fortran (Best 70s and 80s ☺)  Functional programming – a collection of mathematical function definitions: Scheme, ML, Haskell  Object-Oriented  Defining/utilizing objects to represent real-world entities that work together to solve problem  60s Simula, 70s Smalltalk, 80s C++ and Eiffel, 90s Java, 2000 C# and VB  Rule-Based  A set of rules which fire in case of state of world  Applies AI principles  LISP, Prolog, Datalog etc. Imperative (procedural) Programming int gcd(int u, int v) { int t; while (v != 0) { How t = u % v; u = v; v = t; } return u; } Object-Oriented Programming public class IntWithGcd { private int value; public IntWithGcd(int val) { value = val; } public int intValue() { return value; } public int gcd(int v) { int z = value; int y = v; while (y != 0) { How int t = u % v; z = y; y = t; } return z; } Functional Programming u , if v = 0; gcd(u, v) = gcd (v, u % v), otherwise. gcd u v = if v == 0 then u else gcd(v (u ‘mod’ v)) What Logic (rule-based) Programming V = 0 → gcd(U, V) = U V  0, Y = U %V, gcd(V, Y) = X → gcd(U, V) = X gcd(U, V, U) :- V = 0. gcd(U, V, X) :- not (V = 0), Y is U mod V, What gcd(V, Y, X). Object Oriented Programming  Class  Specifies the definition of a particular kind of object  Its Characteristics : Properties (or Attributes)  Its Behaviors: Methods  Used as blueprint / template to create objects of that type  Object/Instance  A specific instance of a class – an object created using the Class Definition  All specific instances of the same class share the same definition  Same Properties – can be modified  Same Methods – can be modified Class and Object Example Class (aLL DOGS) Object (one dog)  All Instances of Class Dog Have  A particular Instance Could Have  Properties  Properties  Name  Name -Spot  Weight  Weight - 10 pounds  Color  Color - Black  Methods  Methods  Walk  Walk  Bark  Bark  Jump  Jump  (these can also be modified to fit a particular dog) OOP benefits  a more intuitive transition from business-analysis models to software-implementation models  the ability to maintain and implement changes in the programs more efficiently and rapidly  the ability to create software systems more effectively using a team process, allowing specialists to work on parts of the system  the ability to reuse code components in other programs and purchase components written by third-party developers to increase the functionality of existing programs with little effort  better integration with loosely coupled distributed-computing systems  improved integration with modern operating systems  the ability to create a more intuitive graphical-user interface for the users Break  Zzzzzzzzz…… Programming in Python Python  This is the name of the programming language that will be used to illustrate different programming concepts during this course  Some advantages:  Free  Powerful  Widely used (Google, NASA,Yahoo, Electronic Arts, some UNIX scripts etc.)  Named after a British comedy “Monty Python’s Flying Circus”  Official website (Python the programming language, not the Monty Python comedy troop): http://www.python.org Installation  Get Python (get version 3.X and not version 2.X)  http://www.python.org/download/  Requires that Python is configured (the “path”) on your computer (follow these instructions carefully, missteps occur at your own peril!)  http://docs.python.org/using/windows.html  http://docs.python.org/using/unix.html  http://docs.python.org/using/mac.html  (If you have installed Python on your own computer and still can’t get ‘Python’ to run – this approach works although it’s a ‘inelegant’ solution).  Note where you installed Python (folder or directory)  Create and run your Python programs from this location. Online Help  Explanation of concepts (for beginners: along with examples to illustrate)  http://docs.python.org/py3k/tutorial/index.html  Information about Python libraries (more advanced: useful for looking up specific details of pre-created Python functions after you have a general idea of how things work e.g., what is the exact wording of the function used to open a file).  http://docs.python.org/py3k/library/index.html  General help (includes the above two help links and more):  http://docs.python.org/py3k/ An Example Python Program  Program name: small.py Filename: small.py print ("hello") Creating Programs: One Operating System  To translate/run your program type “Python ” at the command line.  The first example program would be executed by typing “python small.py”  For a program whose filename is called “output1.py” you would type “python output1.py”.  If you didn’t catch it: Make sure the exact and complete filename is entered (even the “dot-py” suffix). Creating Programs: One Operating System (2)  Working on your own computer: When you translate/run your program in the command window make sure that your command line is in the same location as your Python program (‘inelegant but works’). The Python program is in another location.  Alternatively you have set up your computer so it ‘knows’ where python has been installed (e.g., setting the ‘path’ in Windows).  See earlier slide: “…follow these instructions carefully, missteps occur at your own peril!” Displaying String Output  String output: A message appears onscreen that consists of a series of text characters.  Whatever is contained with the quotes (single or double) is what appears onscreen.  Don’t mix and match different types of quotation marks.  Format: print ("the message that you wish to appear") OR print ('the message that you wish to appear')  Example: print ("foo") print ('bar') Variables  Set aside a location in memory.  Used to store information (temporary). Picture from “Computers in your future” by Pfaffenberger B  This location can store one ‘piece’ of information.  Putting another piece of information at an existing location overwrites previous information.  At most the information will be accessible as long as the program runs.  Some of the types of information which can be stored in variables include: integer (whole), floating point (fractional), strings (text)  Format: =  Examples: Integer (e.g., num1 = 10) Floating point (e.g., num2 = 10.0) Strings (e.g., name = "james") Variable Naming Conventions  Python requirements:  Rules built into the Python language for writing a program.  Somewhat analogous to the grammar of a ‘human’ language.  If the rules are violated then the typical outcome is the program cannot be translated (nor run).  A language such as Python may allow for a partial execution.  Style requirements:  Approaches for producing a well written program.  (The real life analogy is that something written in a human language may follow the grammar but still be poorly written).  If they are not followed then the program can still be translated but there may be other problems (more on this during the term). ??? Variable Naming Conventions (2)  Style requirement: The name should be meaningful.  Style and Python requirement: Names must start with a letter (Python requirement) and should not begin with an underscore (style requirement).  Style requirement: Names are case sensitive but avoid distinguishing variable names only by case.  Style requirement: Variable names should generally be all lower case (see next point for the exception).  Style requirement: For variable names composed of multiple words separate each word by capitalizing the first letter of each word (save for the first word) or by using an underscore. (Either approach is acceptable but don’t mix and match.)  Python requirement: Can't be a keyword (see next slide). Key Words In Python1 and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 1 From “Starting out with Python” by Tony Gaddis Named Constants  They are similar to variables: a memory location that’s been given a name.  Unlike variables their contents shouldn’t change.  The naming conventions for choosing variable names generally apply to constants but the name of constants should be all UPPER CASE. (You can separate multiple words with an underscore).  Example PI = 3.14  They are capitalized so the reader of the program can distinguish them from variables.  For some programming languages the translator will enforce the unchanging nature of the constant.  For languages such as Python it is up to the programmer to recognize a constant for what it is and not to change it. Terminology: Named Constants Vs. Literals  Named constant: given an explicit name. TAX_RATE = 0.2 afterTax = income – (income * TAX_RATE)  Literal/unnamed constant/magic number: not given a name, the value that you see is literally the value that you have. afterTax = 100000 – (100000 * 0.2) Terminology: Named Constants Vs. Literals  Named constant: given an explicit name TAX_RATE = 0.2 afterTax = income – (income * TAX_RATE) Named constants  Literal/unnamed constant/magic number: not given a name, the value that you see is literally the value that you have. afterTax = 100000 – (100000 * 0.2) Literals Output: Displaying The Contents Of Variables And Constants Format: print () print () Example: Program name: output1.py aNum = 10 A_CONSTANT = 10 print (aNum) print (A_CONSTANT) Mixed Output  Mixed output: getting string output and the contents of variables (or constants) to appear together.  Format: print (“string”, , “string”, etc.)  Examples: Program name: output2.py myInteger = 10 myReal = 10.5 myString = "hello" print ("MyInteger:" , myInteger) The comma signals to the print ("MyReal:" , myReal) translator that the string and the contents of the variable should print ("MyString:" , myString) appear on the same line. Output: Problems  print command automatically adds an additional newline  Name of example: output3.py year = 1997 print ("year=") Label and variable print (year) contents on different lines print ("year=", year) Label and variable contents on the same line Arithmetic Operators Operator Description Example = Assignment num = 7 + Addition num = 2 + 2 - Subtraction num = 6 - 4 * Multiplication num = 5 * 4 / Division num = 25 / 5 % Modulo num = 8 % 3 ** Exponent num = 9 ** 2 Order Of Operation  First level of precedence: top to bottom  Second level of precedence  If there are multiple operations that are on the same level then precedence goes from left to right. () Brackets (inner before outer) ** Exponent *, /, % Multiplication, division, modulo +, - Addition, subtraction Input  The computer program getting string information from the user.  Strings cannot be used for calculations (information getting numeric input will provided shortly).  Format: = input() OR = input("")  Example: Program name: input1.py print ("What is your name: ") name = input () OR name = input ("What is your name: ") Storing Information issues  Why it is important to know that different types of information is stored differently?  Certain operations only apply to certain types of information and can produce errors or unexpected results when applied to other types of information.  Example num = input("Enter a number") numHalved = num / 2 [Errno 22] Invalid argument Converting Between Different Types Of Information  Example motivation: you may want numerical information to be stored as a string (for the formatting capabilities) but also you want that same information in numerical form (in order to perform calculations).  Some of the conversion mechanisms available in Python: Format: int () float () str () Examples: Program name: convert1.py x = 10.9 y = int (x) print (x, y) Converting Between Different Types Of Information (2) Examples: Program name: convert2.py x = '100' y = '-10.5' print (x + y) print (int(x) + float (y)) (Numeric to string: convert3.py) aNum = 123 aString = str(aNum) aNum = aNum + aNum aString = aString + aString print (aNum) print (aString) Converting Between Different Types Of Information: Getting Numeric Input  Because the ‘input’ function only returns string information it must be converted to the appropriate type as needed. Example Program name: convert4.py # Problem! HUMAN_CAT_AGE_RATIO = 7 ‘Age’ refers to a string not age = input("What is your age in years: ") a number. catAge = age * HUMAN_CAT_AGE_RATIO The ‘*’ is not mathematical print ("Age in cat years: ", catAge) multiplication # Problem solved! HUMAN_CAT_AGE_RATIO = 7 ‘Age’ converted to an age = int(input("What is your age in years: ")) integer. catAge = age * HUMAN_CAT_AGE_RATIO The ‘*’ now multiplies a print ("Age in cat years: ", catAge) numeric value. Determining The Type Of Information Stored In A Variable  It can be done by using the pre-created python function ‘type’  Example program: type.py myInteger = 10 myString = "foo!" print (type(myInteger)) print (type(10.5)) print (type(myString)) Output: Formatting  Output can be formatted in Python through the use of placeholders.  Format: print ("%" %)  Example: Program name: formatting1.py num = 123 st = "cpsc 231" print ("num=%d" %num) print ("course: %s" %st) num = 12.5 print ("%f %d" %(num, num)) Types Of Information That Can Be Displayed Descriptor code Type of Information to display %s String %d Integer (d = decimal / base 10) %f Floating point Triple Quoted Output  Used to format text output  The way in which the text is typed into the program is exactly the way in which the text will appear onscreen.  Program name: formatting3.py Another Example: print(""" Advanced Programming... """) From Python Programming (2nd Edition) by Michael Dawson Escape Codes  The back-slash character enclosed within quotes won’t be displayed but instead indicates that a formatting (escape) code will follow the slash: Escape sequence Description \a Alarm. Causes the program to beep. \n Newline. Moves the cursor to beginning of the next line. \t Tab. Moves the cursor forward one tab stop. \' Single quote. Prints a single quote. \" Double quote. Prints a double quote. \\ Backslash. Prints one backslash. Escape Codes (2)  Program name: formatting4.py print ("\a*Beep!*") print ("hi\nthere") print ('it\'s') print ("he\\y \"you\"") Extra Practice  Traces:  Modify the examples (output using descriptor and escape codes) so that they are still valid Python statements.  Alternatively you can try finding some simple ones online.  Hand trace the code (execute on paper) without running the program.  Then run the program and compare the actual vs. expected result.  Program writing:  Write a program the will right-align text into 3 columns of data.  When the program starts it will prompt the user for the maximum width of each column Program Documentation (Comments)  Program documentation: Used to provide information about a computer program to another programmer (writes or modifies the program).  This is different from a user manual which is written for people who will use the program.  Documentation is written inside the same file as the computer program (when you see the computer program you can see the documentation).  The purpose is to help other programmers understand the program: what the different parts of the program do, what are some of it’s limitations etc. Program Documentation (2)  It doesn’t contain instructions for the computer to execute.  It doesn’t get translated into machine language.  It’s information for the reader of the program:  What does the program as a while do e.g., tax program.  What are the specific features of the program e.g., it calculates personal or small business tax.  What are it’s limitations e.g., it only follows Canadian tax laws and cannot be used in the US. In Canada it doesn’t calculate taxes for organizations with yearly gross earnings over $1 billion.  What is the version of the program  If you don’t use numbers for the different versions of your program then consider using dates (tie versions with program features). Program Documentation (3)  Format: # The number sign ‘#” flags the translator that what’s on this line is documentation.  Examples:  # Tax-It v1.0: This program will electronically calculate your tax return.  # This program will only allow you to complete a Canadian tax return. Program Versioning And Back Ups  As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. Game.py Game.Sept20 # Version: Sept 20, 2012 Make backup file # Version: Sept 20, 2012 # Program features: # Program features: # (1) Load game # (1) Load game # (2) Show game world # (2) Show game world Program Versioning And Back Ups  As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. Game.Oct2 # Version: Oct 2, 2012 # Program features: # (1) Save game Game.py # Version: Sept 20, 2012 # Version: Oct 2, 2012 # Program features: # Program features: Make new # (1) Load game # (1) Save game backup file # (2) Show game world # Version: Sept 20, 2012 Game.Sept20 # Program features: # Version: Sept 20, 2012 # (1) Load game # Program features: # (2) Show game world # (1) Load game # (2) Show game world Program Versioning And Back Ups  Or use any program versioning tools available: Github, Bibucket, etc. Backing Up Your Work  Do this every time that you have completed a significant milestone in your program.  What is ‘significant’ will vary between people but make sure you do this.  Ideally the backup file should be stored in a separate directory/folder (better yet on a separate device and/or using an online method such as an email attachment).  Common student reason for not making copies: “Backing up files takes time to do!”  Compare:  Time to copy a file: ~10 seconds (generous in some cases).  Time to re-write your program to implement that feature again: 10 minutes (might be overly conservative in some cases).  Failing to backup your work is not a sufficient reason for receiving an extension. Types Of Documentation  Header documentation  Inline documentation Header Documentation  Provided at the beginning of the program.  It describes in a high-level fashion the features of the program as a whole (major features without a great deal of detail). # HEADER DOCUMENTATION # Word Processor features: print, save, spell check, insert images etc. Inline Documentation  Provided throughout the program.  It describes in greater detail the specific features of a part of the program (function, loop, branch, group of related statements). # Documentation: Saving documents # ‘save’: save document under the current name # ‘save as’ rename the document to a new name # Documentation: Spell checking # The program can spell check documents using the following English variants: # English (British), English (American), English (Canadian) -Built-in Python Functions  Python comes with many functions that are a built in part of the language e.g., ‘print’, ‘input’  (If a program needs to perform a common task e.g., finding the absolute value of a number, then you should first check if the function has already been implemented).  For a list of all prewritten Python functions.  http://docs.python.org/library/functions.html  Note: some assignments may have specific instructions on which functions you are allowed to use.  Read the requirements specific to each assignment. Program Errors 1. Syntax Errors  Errors in grammar of the language 2. Runtime error  When there are no syntax errors, but the program can’t complete execution  Divide by zero  Invalid input data 3. Logical errors  The program completes execution, but delivers incorrect results  Incorrect usage of parentheses 1. Syntax/ Translation Errors  Each language has rules about how statements are to be structured.  An English sentence is structured by the grammar of the English language:  The cat sleeps the sofa. Grammatically incorrect: missing the preposition to introduce the prepositional phrase ‘the sofa’  The translator checks for syntax errors when a computer program is translated into machine language.  Python statements are structured by the syntax of Python: 5 = num Syntactically incorrect: the left hand side of an assignment statement cannot be a literal (unnamed) constant. Some Common Syntax Errors  Miss-spelling names of keywords  e.g., ‘primt’ instead of ‘print’  Forgetting to match closing quotes or brackets to opening quotes or brackets.  Using variables before they’ve been named (allocated in memory).  Program name: error_syntax.py print (num) num = 123 print num 2. Runtime Errors  Occur as a program is executing (running).  The syntax of the language has not been violated (each statement follows the rules/syntax).  During execution a serious error is encountered that causes the execution (running) of the program to cease.  With a language like Python where translation occurs just before execution (interpreted) the timing of when runtime errors appear won’t seem different from a syntax error.  But for languages where translation occurs well before execution (compiled) the difference will be quite noticeable.  A common example of a runtime error is a division by zero error. Runtime Error1: An Example  Program name: error_runtime.py num2 = int(input("Type in a number: ")) num3 = int(input("Type in a number: ")) num1 = num2 / num3 print (num1) 1 When ‘num3’ contains zero 3. Logic Errors  The program has no syntax errors.  The program runs from beginning to end with no runtime errors.  But the logic of the program is incorrect (it doesn’t do what it’s supposed to and may produce an incorrect result).  Program name: error_logic.py print ("This program will calculate the area of a rectangle") length = int(input("Enter the length: ")) width = int(input("Enter the width: ")) area = length + width print ("Area: ", area) Some Additional Examples Of Errors  All external links (not produced by your instructor):  http://level1wiki.wikidot.com/syntax-error  http://www.cs.bu.edu/courses/cs108/guides/debug.html  http://cscircles.cemc.uwaterloo.ca/1e-errors/  http://www.greenteapress.com/thinkpython/thinkCSpy/html/app01.html Practice Exercise (This one will be an ongoing task).  As you write you programs, classify the type of errors that you face as: syntax/translation, runtime or logical. After This Section You Should Now Know  How to create, translate and run Python programs.  Variables:  What they are used for  How to access and change the value of a variable  Conventions for naming variables  How information is stored differently with different types of variables, converting between types  Named constants:  What are named constants and how they differ from regular variables  What are the benefits of using a named constant vs. a literal  What is program documentation and what are some common things that are included in program documentation  How are common mathematical operations performed After This Section You Should Now Know (2)  Output:  How to display messages that are a constant string or the value stored in a memory location (variable or constant) onscreen with print  How to format output through:  The use of descriptor codes.  Escape codes  How triple quotes can be used in the formatting of output  Input:  How to get a program to acquire and store information from the user of the program  How do the precedence rules/order of operation work in Python  About the existence of prewritten Python functions and how to find descriptions of them  What are the three programming errors, when do they occur and what is the difference between each one Thank you! Questions? [email protected] http://ubt-uni.net/

Use Quizgecko on...
Browser
Browser