Lecture 3 basic syntax and semantics


Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture 3 basic syntax and semantics

  1. 1. 1 of 34Module 3 : Basic syntax and semanticsIntroduction to       Computational ThinkingModule 3 :                                        Basic syntax and semanticsAsst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104email: cwfu[at]ntu.edu.sg
  2. 2. 2 of 34Module 3 : Basic syntax and semanticsTopics• Semantics and Syntax• Let’s learn with a simple example• More on Python Syntax
  3. 3. 3 of 34Module 3 : Basic syntax and semanticsSemantics and SyntaxWhen writing programs, you have to take care of• Semantics – Meaning of your program• Syntax – Specifying your algorithm using aprogramming languageProblem Algorithm ProgramRun onComputationalThinkingProgrammingSemanticsSyntax
  4. 4. 4 of 34Module 3 : Basic syntax and semanticsSemantics and SyntaxJust like communication with English:• The meaning (semantics) of the sentence,as well as• The grammar (syntax) of the sentence, so thatothers can understand, e.g.,√ he has X he have√ we are X we is
  5. 5. 5 of 34Module 3 : Basic syntax and semanticsSemantics and Syntax• Different languages have different syntax;this applies to both spoken languages andcomputer programming languages• To make sure the Python shell can understandyour Python program, your program has tofollow the syntax of the Python languageThis module talksabout basicPython syntax
  6. 6. 6 of 34Module 3 : Basic syntax and semanticsTopics• Semantics and Syntax• Let’s begin with a simple example• More on Python Syntax
  7. 7. 7 of 34Module 3 : Basic syntax and semanticsCode Listing 1.1• To understand Python syntax, it is better totake a working Python program as an example:
  8. 8. 8 of 34Module 3 : Basic syntax and semanticsTerminology #1) Statement• Each line of code in a Python program is called a statement• Python interprets and runs statements one by one
  9. 9. 9 of 34Module 3 : Basic syntax and semanticsStatement Continuation• Python is sensitive to end of line in text files, which marksthe end of a statement; in text editors, we press “enter”• The symbol is used to continue a statement with the nextline so that two lines can be joined as a single statement(this is good for long statements… readability)Improve readabilityin a text editor
  10. 10. 10 of 34Module 3 : Basic syntax and semanticsTerminology #2) Comments• The pound sign # in Python indicates a comment• Anything after # is ignored for interpretation (in green)• Comments provide information to improve code readabilityComment lines
  11. 11. 11 of 34Module 3 : Basic syntax and semanticsTerminology #3) Keywords• Python reserves certain words for specific purposes in theprogramming language itself, e.g., import, etc. (light blue)• You cannot use these words to define your own stuff; theyare called the reserved wordsLight blue
  12. 12. 12 of 34Module 3 : Basic syntax and semanticsTerminology #4) Modules• A module is a Python file containing elements to help workingon a certain problem, e.g., math (see above) -> math.pi• Modules are great resources provided by Python to performvarious common tasks, e.g., database, network, etc.math module and dot operator
  13. 13. 13 of 34Module 3 : Basic syntax and semanticsTerminology #5) User Input• input is a built-in function provided by Python• Prints the message string on the screen and waits till theuser types something (anything), ending with Enter• Returns a string (a sequence of characters) no matterwhat is given, even a numbera function call to get input
  14. 14. 14 of 34Module 3 : Basic syntax and semanticsTerminology #6) Computation• Using the input radius, we can compute circumferenceand area• Note: = is not equal sign! It is an “assignment operator” inmost programming languages to assign values to variablesmain computationvariables
  15. 15. 15 of 34Module 3 : Basic syntax and semanticsTerminology #7) Print results• print is another built-in function provided by Python;it displays the related message and data on the Pythonshell screen (note: use comma to separate elements)• A single print() makes an empty line -> try several empty print()
  16. 16. 16 of 34Module 3 : Basic syntax and semanticsSo altogether… this program?• There are three steps in the program…See the comments on top of the program!!!
  17. 17. 17 of 34Module 3 : Basic syntax and semanticsSo you should know…Basics…• Statements and Statement Continuation• Comments with #• Keywords / Reserved words (e.g., import)• Modules (e.g., math)• Built-in functions (e.g., input and print)• Variable and Assignment operator =(more to come in next module)
  18. 18. 18 of 34Module 3 : Basic syntax and semanticsTopics• Semantics and Syntax• Let’s learn with a simple example• More on Python Syntax
  19. 19. 19 of 34Module 3 : Basic syntax and semanticsLet’s look at more syntax stuff• Comments• Whitespace• Indentation• Tokens: Keywords, Operators, Punctuatorsand Delimiters, Literals• Expressions• Interpreter Errors
  20. 20. 20 of 34Module 3 : Basic syntax and semantics1) Comments• Basics: Anything that follows # is ignored (byinterpreter/compiler) on that statement• Though contributing nothing to the programexecution, comments are important things toimprove readability…• But… No universal rules for right style andnumber of comments
  21. 21. 21 of 34Module 3 : Basic syntax and semantics1) Comments• Useful guidelines:• Why philosophy:Good comments do not repeat the code orexplain it. They should clarify the intentionof the code and explain higher level concept• How philosophy:If your code contains a novel or noteworthysolution, add some comments to explain it
  22. 22. 22 of 34Module 3 : Basic syntax and semantics2) Whitespace• Purpose: to separate words in a statement• Python counts the following charactersas white space:• Space, tab, return, etc. (see textbook)• For the most part, you can place “white space”(spaces) anywhere in your program; use it tomake a program more readable, e.g.,a = a + 1 + c instead of a=a+1+cmath.asin( math.cos(a) + math.tan(b+c)*3 )
  23. 23. 23 of 34Module 3 : Basic syntax and semantics• Leading whitespace at the beginning of astatement defines indentation, e.g.,(will see morein module 6)3) Indentation1 level2 levelsIndentation:
  24. 24. 24 of 34Module 3 : Basic syntax and semantics3) Indentation• Purpose:- Python requires indentation for grouping, inparticular for control flow: branching andlooping (see module 6)- Make code more readable• Note: consistently use same number of spaces(see more in module 6)
  25. 25. 25 of 34Module 3 : Basic syntax and semantics4) Tokens• Tokens are special elements in a programminglanguage (note: interpreter/compiler will firstidentify them when parsing each statement in aprogram, so that the interpreter/compiler canlater understand the meaning of your statement)• In Python, we have four basic types of tokens:• Keywords• Operators• Punctuators and Delimiters• Literals
  26. 26. 26 of 34Module 3 : Basic syntax and semanticsand del from not whileas elif global or withassert else if pass yieldbreak except import printclass in raisecontinue finally is returndef for lambda tryKeywords• Special words reserved in Python• Programmers (we) cannot use them to name thingsNote: “exec” removed in Python 3
  27. 27. 27 of 34Module 3 : Basic syntax and semantics+ - * ** / // %<< >> & | ^ ~< > <= >= == !=Operators• Special characters (or sequence of characters)that imply certain operations, e.g.,mathematical and logical.Note: < > removed in Python 3
  28. 28. 28 of 34Module 3 : Basic syntax and semantics‘ “ # _( ) [ ] { } @, : . ` = ;+= -= *= /= //= %=&= |= ^= >>= <<= **=Punctuators & Delimiters• Punctuators, also known as delimiters separatedifferent types of elements in Pythonstatements and expressions
  29. 29. 29 of 34Module 3 : Basic syntax and semantics• Literals are fixed values used in a computerprogram, e.g., 123 and 3.14 are literalsE.g., 1, 2, and 3 in the program above are literalsHow many numerical literals in program above?Literals
  30. 30. 30 of 34Module 3 : Basic syntax and semantics5) Expressions• Anything that produces/returns a value• Let’s say by combining values (e.g., literals, variables,etc.) and operations (e.g., operators, functions, etc.)• E.g.,• 3.14• 100 * 5• result * 100• 2 * math.pi * radius + float(input("input:"))• Note:• Interpreter ignores whitespaces (but helps readability)• In Python, statements do not return a value
  31. 31. 31 of 34Module 3 : Basic syntax and semanticsMore: Side Effects and Returns• Make sure you get the difference:What is the difference between a side effectand a return?• 1 + 2 returns a value (it’s an expression). Youcan catch the return value. However, nothingelse changed as a result• print("hello") doesn’t return anything, butsomething else, the side effect, did happen.Something printed on screen!• How about a=1+2?
  32. 32. 32 of 34Module 3 : Basic syntax and semantics6) Interpreter Errors• The interpreter translates Python code intomachine language. The first stage of that processis determining whether it is valid or not• If the code is somehow malformed, Python cannotrun your code and you get an interpreter error:Syntax error:Python cannottranslate the code
  33. 33. 33 of 34Module 3 : Basic syntax and semanticsTake Home Messages• Semantics – Meaning of your program• Syntax – Specifying your algorithm using theprogramming language• This module is about terminologies and syntax:Statements, statement continuation, modules,comments, whitespace, indentation, tokens(keywords, operators, punctuators anddelimiters, literals), functions, expression,interpreter errors• Side effects and returns (statement VS expression)
  34. 34. 34 of 34Module 3 : Basic syntax and semanticsReading Assignment• TextbookChapter 1: Beginnings1.2 to 1.4