Lecture 3 basic syntax and semantics

34
Introduction to Computational Thinking Module 3 : Basic syntax and semantics Asst Prof ChiWing FU, Philip Office: N402c104 email: cwfu[at]ntu.edu.sg

Transcript of Lecture 3 basic syntax and semantics

Page 1: Lecture 3  basic syntax and semantics

1 of 34Module 3 : Basic syntax and semantics

Introduction to       Computational Thinking

Module 3 :                                        Basic syntax and semantics

Asst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104

email: cwfu[at]ntu.edu.sg

Page 2: Lecture 3  basic syntax and semantics

2 of 34Module 3 : Basic syntax and semantics

Topics• Semantics and Syntax• Let’s learn with a simple example• More on Python Syntax

Page 3: Lecture 3  basic syntax and semantics

3 of 34Module 3 : Basic syntax and semantics

Semantics and SyntaxWhen writing programs, you have to take care of• Semantics – Meaning of your program• Syntax – Specifying your algorithm using a

programming language

Problem Algorithm Program

Run onComputational

ThinkingProgramming

SemanticsSyntax

Page 4: Lecture 3  basic syntax and semantics

4 of 34Module 3 : Basic syntax and semantics

Semantics and SyntaxJust like communication with English:• The meaning (semantics) of the sentence,

as well as • The grammar (syntax) of the sentence, so that

others can understand, e.g.,√ he has X he have√ we are X we is

Page 5: Lecture 3  basic syntax and semantics

5 of 34Module 3 : Basic syntax and semantics

Semantics and Syntax• Different languages have different syntax;

this applies to both spoken languages and computer programming languages

• To make sure the Python shell can understand your Python program, your program has to follow the syntax of the Python language

This module talks about basic

Python syntax

Page 6: Lecture 3  basic syntax and semantics

6 of 34Module 3 : Basic syntax and semantics

Topics• Semantics and Syntax• Let’s begin with a simple example• More on Python Syntax

Page 7: Lecture 3  basic syntax and semantics

7 of 34Module 3 : Basic syntax and semantics

Code Listing 1.1• To understand Python syntax, it is better to

take a working Python program as an example:

Page 8: Lecture 3  basic syntax and semantics

8 of 34Module 3 : Basic syntax and semantics

Terminology #1) Statement

• Each line of code in a Python program is called a statement• Python interprets and runs statements one by one

Page 9: Lecture 3  basic syntax and semantics

9 of 34Module 3 : Basic syntax and semantics

Statement 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

Page 10: Lecture 3  basic syntax and semantics

10 of 34Module 3 : Basic syntax and semantics

Terminology #2) Comments

• The pound sign # in Python indicates a comment• Anything after # is ignored for interpretation (in green)• Comments provide information to improve code readability

Comment lines

Page 11: Lecture 3  basic syntax and semantics

11 of 34Module 3 : Basic syntax and semantics

Terminology #3) Keywords

• Python reserves certain words for specific purposes in the programming language itself, e.g., import, etc. (light blue)

• You cannot use these words to define your own stuff; theyare called the reserved words

Light blue

Page 12: Lecture 3  basic syntax and semantics

12 of 34Module 3 : Basic syntax and semantics

Terminology #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

Page 13: Lecture 3  basic syntax and semantics

13 of 34Module 3 : Basic syntax and semantics

Terminology #5) User Input

• input is a built-in function provided by Python• Prints the message string on the screen and waits till the

user types something (anything), ending with Enter• Returns a string (a sequence of characters) no matter

what is given, even a number

a function call to get input

Page 14: Lecture 3  basic syntax and semantics

14 of 34Module 3 : Basic syntax and semantics

Terminology #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 variables

main computation

variables

Page 15: Lecture 3  basic syntax and semantics

15 of 34Module 3 : Basic syntax and semantics

Terminology #7) Print results

• print is another built-in function provided by Python;it displays the related message and data on the Python shell screen (note: use comma to separate elements)

• A single print() makes an empty line -> try several empty print()

Page 16: Lecture 3  basic syntax and semantics

16 of 34Module 3 : Basic syntax and semantics

So altogether… this program?

• There are three steps in the program…See the comments on top of the program!!!

Page 17: Lecture 3  basic syntax and semantics

17 of 34Module 3 : Basic syntax and semantics

So 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)

Page 18: Lecture 3  basic syntax and semantics

18 of 34Module 3 : Basic syntax and semantics

Topics• Semantics and Syntax• Let’s learn with a simple example• More on Python Syntax

Page 19: Lecture 3  basic syntax and semantics

19 of 34Module 3 : Basic syntax and semantics

Let’s look at more syntax stuff• Comments• Whitespace• Indentation• Tokens: Keywords, Operators, Punctuators

and Delimiters, Literals• Expressions• Interpreter Errors

Page 20: Lecture 3  basic syntax and semantics

20 of 34Module 3 : Basic syntax and semantics

1) Comments• Basics: Anything that follows # is ignored (by

interpreter/compiler) on that statement• Though contributing nothing to the program

execution, comments are important things to improve readability…

• But… No universal rules for right style and number of comments

Page 21: Lecture 3  basic syntax and semantics

21 of 34Module 3 : Basic syntax and semantics

1) Comments• Useful guidelines:

•Why philosophy:Good comments do not repeat the code or explain 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

Page 22: Lecture 3  basic syntax and semantics

22 of 34Module 3 : Basic syntax and semantics

2) Whitespace• Purpose: to separate words in a statement• Python counts the following characters

as white space:•Space, tab, return, etc. (see textbook)

• For the most part, you can place “white space”(spaces) anywhere in your program; use it to make 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 )

Page 23: Lecture 3  basic syntax and semantics

23 of 34Module 3 : Basic syntax and semantics

• Leading whitespace at the beginning of a statement defines indentation, e.g.,(will see morein module 6)

3) Indentation

1 level2 levels

Indentation:

Page 24: Lecture 3  basic syntax and semantics

24 of 34Module 3 : Basic syntax and semantics

3) Indentation• Purpose:

- Python requires indentation for grouping, in particular for control flow: branching andlooping (see module 6)

- Make code more readable

• Note: consistently use same number of spaces(see more in module 6)

Page 25: Lecture 3  basic syntax and semantics

25 of 34Module 3 : Basic syntax and semantics

4) Tokens• Tokens are special elements in a programming

language (note: interpreter/compiler will first identify them when parsing each statement in a program, so that the interpreter/compiler can later understand the meaning of your statement)

• In Python, we have four basic types of tokens:•Keywords•Operators•Punctuators and Delimiters• Literals

Page 26: Lecture 3  basic syntax and semantics

26 of 34Module 3 : Basic syntax and semantics

and del from not while

as elif global or with

assert else if pass yield

break except import print

class in raise

continue finally is return

def for lambda try

Keywords• Special words reserved in Python• Programmers (we) cannot use them to name things

Note: “exec” removed in Python 3

Page 27: Lecture 3  basic syntax and semantics

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

Page 28: Lecture 3  basic syntax and semantics

28 of 34Module 3 : Basic syntax and semantics

‘ “ # \ _

( ) [ ] { } @

, : . ` = ;

+= -= *= /= //= %=

&= |= ^= >>= <<= **=

Punctuators & Delimiters• Punctuators, also known as delimiters separate

different types of elements in Python statements and expressions

Page 29: Lecture 3  basic syntax and semantics

29 of 34Module 3 : Basic syntax and semantics

• Literals are fixed values used in a computer program, e.g., 123 and 3.14 are literals

E.g., 1, 2, and 3 in the program above are literalsHow many numerical literals in program above?

Literals

Page 30: Lecture 3  basic syntax and semantics

30 of 34Module 3 : Basic syntax and semantics

5) 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

Page 31: Lecture 3  basic syntax and semantics

31 of 34Module 3 : Basic syntax and semantics

More: Side Effects and Returns• Make sure you get the difference:

What is the difference between a side effect and a return?

• 1 + 2 returns a value (it’s an expression). You can catch the return value. However, nothingelse changed as a result

• print("hello") doesn’t return anything, but something else, the side effect, did happen. Something printed on screen!

• How about a=1+2?

Page 32: Lecture 3  basic syntax and semantics

32 of 34Module 3 : Basic syntax and semantics

6) Interpreter Errors• The interpreter translates Python code into

machine language. The first stage of that process is determining whether it is valid or not

• If the code is somehow malformed, Python cannot run your code and you get an interpreter error:

Syntax error:Python cannot translate the code

Page 33: Lecture 3  basic syntax and semantics

33 of 34Module 3 : Basic syntax and semantics

Take Home Messages• Semantics – Meaning of your program• Syntax – Specifying your algorithm using the

programming language• This module is about terminologies and syntax:

Statements, statement continuation, modules, comments, whitespace, indentation, tokens(keywords, operators, punctuators and delimiters, literals), functions, expression, interpreter errors

• Side effects and returns (statement VS expression)

Page 34: Lecture 3  basic syntax and semantics

34 of 34Module 3 : Basic syntax and semantics

Reading Assignment• Textbook

Chapter 1: Beginnings1.2 to 1.4