0% found this document useful (0 votes)
12 views29 pages

P2 Start

The document outlines fundamental concepts in Python programming, including syntactic elements like literals, identifiers, expressions, and statements. It covers data types, variables, basic input-output operations, and the print() function, along with details on escape characters and argument types. Additionally, it discusses arithmetic operators, variable assignment, comments, and user input handling.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views29 pages

P2 Start

The document outlines fundamental concepts in Python programming, including syntactic elements like literals, identifiers, expressions, and statements. It covers data types, variables, basic input-output operations, and the print() function, along with details on escape characters and argument types. Additionally, it discusses arithmetic operators, variable assignment, comments, and user input handling.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Syntactic Elements/Terms

 Literals
 Identifier
 Keywords, Reserved Words

 Expressions: produce values


 arithmetic expressions: e.g. year % 4

 relational expressions: e.g. year % 4 == 0

 boolean expressions: e.g. year%4 == 0 and year%100 != 0

 Statements : perform actions


 assignment statements: e.g. a = a + 1

 condition statements : if, switch

 repetitive/loop/iteration statement: while, for

 compound statements, procedure statements, empty

statements
廖文宏 Python Programming 1
PE1 Module 2
 Data Types, Variables, Basic Input-Output Operations,
Basic Operators
 How to write and run the first Python program;

 Python literals;

 Python operators and expressions;

 Variables – naming and using;

 Basic input/output operations in Python.

廖文宏 Python Programming 2


2.1.1 print() Function
 The print() function writes the value of the argument(s) it is
given
 print("python", python_version())

 for python 2/3


 print "python", python_version()
 for python 2
 consists of the following parts:
 function name: print

 pair of opening/closing parenthesis

 If you're going to use a function which doesn't take any


argument, you still have to have the parentheses.
 a quoted string
廖文宏 Python Programming 3
2.1.1 What is Function?
 a group of the computer code
 cause some effect (e.g., send text to the terminal, create a

file, draw an image, play a sound, etc.)


 evaluate a value or some values (e.g., the square root of a

value or the length of a given text)


 Where do the functions come from?
 built-in

 add-on modules

 user defined

廖文宏 Python Programming 4


2.1.1 print() Function
 What is the effect the print() function causes?
 sends to the output device

 What arguments does print() expect?


 all types of data offered by Python, include strings,

numbers, characters, logical values, objects, …


 What value does the print() function evaluate(return)?
 None

廖文宏 Python Programming 5


Note
 Python requires that there cannot be more than one
instruction in a line.
 but …..

 semicolon (multiple statements within one line)


a=1; b=2; c=3
 It allows one instruction to spread across more than one line

廖文宏 Python Programming 6


2.1.1.11 Escape Character
 print out new line
 print()

 print("\n")

 backslash (\) has a very special meaning when used inside


strings – this is called the escape character.
 backslash doesn’t mean anything in itself, but is only a kind
of announcement, that the next character after the backslash
has a different meaning
 note: If you don’t want characters prefaced by \ to be
interpreted as special characters, you can use raw strings by
adding an r before the first quote:
e.g. print(r'C:\some\name')
廖文宏 Python Programming 7
2.1.1.11 Escape Character
 常用 Escape Character
\n LF, linefeed, ASCII 10, CTRL-J
\r CR, carriage return, ASCII 13, CTRL-M
\f FF, formfeed, ASCII 12, CTRL-L
\a BEL, alert, ASCII 7, CTRL-G
\b BS, backspace, ASCII 8, CTRL-H
\t HT, horizontal TAB, ASCII 9, CTRL-I
\v VT, vertical TAB, ASCII 11, CTRL-K
\" 輸出 "
\\ 輸出 \
\ooo octal number
\xhh hexadecimal value

廖文宏 Python Programming 8


2.1.1.13 Positional Arguments
 invoke more than one argument, that are separated by
commas.
 e.g.
print("Pussy cat,", "Pussy cat", "where have you been?")
 print() function outputs them all on one line
 print() function puts a space between the outputted
arguments.

 note: argument versus parameter


廖文宏 Python Programming 9
2.1.1.15 Keyword Arguments
 use keyword arguments to change print() behavior
 e.g. use keyword argument end to avoid the newline after
the output
print("Pussy cat,", "Pussy cat,", end=" ")
print("where have you been?")
 keyword arguments have to be put after the last positional
argument
 sep
 separator of outputted auguments

 e.g. print("Jan", "Feb", "Mar", sep=". ", end=".")

廖文宏 Python Programming 10


2.2.1 Literal
 Bytes Literal 二進位, e.g. 0b01000001 (0x41)
 Integer Literal 整數, e.g. 123 或 1_234
 八進位 0o123 (83)

 十六進位 0x123 (291)

 Floating-Point Literal 浮點數, e.g. 12.3 或 4. 或 5.0


 scientific notation e.g. 3e8, 3E8 (3x10 )
8

 String Literal 字串 'hello


 Boolean Literal 布林值 True(1) False(0) (case-sensitivity)
 Imaginary Literal 複數
 Special Literal
 None

廖文宏 Python Programming 11


2.2.1 Data Type 1/2
 Every kind of data is encoded in computer as a sequence of
bits
 consider 01000011
Is it an integer? float? or character?
 Data declarations allow the computer to make the right
interpretation
 Python Data Types:
 Numeric: int 整數, float 浮點數(實數), complex 複數

 Text/String: str 字串

 Boolean: bool

廖文宏 Python Programming 12


2.2.1 Data Type 2/2
 Binary: bytes, bytearray, memoryview
 Sequence: list, tuple, range

 Mapping: dict

 Set Types: set, frozenset

 Python uses object classes to define data types, including its


primitive types.
 get the data type of variable: type()
 type casting: int(), float(), str()

廖文宏 Python Programming 13


2.2.1.3 Integer, Float, Complex
 integer numbers (e.g. 2, 4, 20) have type int
 二進位 0b, 八進位 0o, 十六進位 0x
 convert: int(), oct(), hex()

 e.g. convert string '10' to binary int('10', 2)

 the ones with a fractional part (e.g. 5.0, 1.6) have type float.
 In addition to int and float, Python supports other types of
numbers, such as Decimal and Fraction.
 Python also has built-in support for complex numbers, and
uses the j or J suffix to indicate the imaginary part (e.g.
3+5j).

廖文宏 Python Programming 14


2.2.1.8 String
 be enclosed in single quotes ('...') or double quotes ("...")
with the same result
 e.g. 'Hello', "World"

 text span multiple lines, enclosed in three double quotes


 e.g. """This is multiple line

texts"""
 anything you put inside the quotes will be taken literally,
not as code, but as data.
 Python strings cannot be changed — they are immutable
 There is no separate character type
a character is simply a string of size one
廖文宏 Python Programming 15
2.2.1.10 Boolean
 These two Boolean values have strict denotations in Python:
True (not 0)
False (0)
 To take these symbols as they are,

including case-sensitivity.
 0, 0.0, empty string、empty list, empty tuple、empty
container, None 都視為 False

廖文宏 Python Programming 16


Expression 運算式
 expression 由 operand (運算元) 和 operator (運算子) 組合
而成
 e.g. 3 + 5

 e.g. 3 ** 2

 e.g. 'Hello' + 'World'

 e.g. (a * h ) / 2

 a, h, 2 為 operand
 * / 為 operator

廖文宏 Python Programming 17


2.3 Arithmetic Operators 算術運算子
 + - * / // % **
 Division (/) always returns a float.

 // floor division and get an integer result (discarding any

fractional result)
+ 加
 % remainder

 ** exponent
- 減
* 乘
/ 兩數相除取商
// 整數除法
% 兩數相除取餘數
** 次方
廖文宏 Python Programming 18
2.3.1.7 Operator Precedence
 operator precedence
 https://docs.python.org/3/reference/expressions.html

 e.g. 8 + 12 / 4 =?

 subexpressions in parentheses are always calculated first.

 operator associativity/binding
 left-to-right

 right-to-left

 e.g. 2 ** 2 ** 3 = ?

廖文宏 Python Programming 19


2.4 Variable
 A variable denotes some location of memory to store the
data
 A variable comes into existence as a result of assigning a
value to it. You don't need to declare it in any special way.
 e.g. assign string "welcome" to variable hello

hello = "welcome"
 An assignment statement to a variable modified the contents
of the memory location associated to the variable
 dynamic data type
 binding at runtime

廖文宏 Python Programming 20


2.4 Identifier
 identifier (including variable, function name)
識別字(變數、函數名稱)命名規則
 [a-zA-Z_][0-9a-zA-Z_]

 upper-case or lower-case letters, digits, and the character _


(underscore) 英文字母大小寫、數字 0~9、底線 _
 begin with a letter 第一個字不能是數字
 case sensitive 區分大小寫
 must not be any of Python’s reserved words
保留字不能用
 Python 使用 Unicode 編碼,所以可以用中文當作識別
字, 但是強烈建議不要
 no more BIG-5 許(B35C) 功(A55C) 蓋(BB5C)
廖文宏 Python Programming 21
Python Reserved Words

廖文宏 Python Programming 22


2.4.1.5 Variables Assignment
 Equal sign is an assignment operator.
 It assigns the value of its right argument to the left, while
the right argument may be an arbitrarily complex
expression involving literals, operators and already defined
variables.
 a = 4 + 3

 b = a * 4.5 var = expression


 c = (a+b)/2.5

 a = "Hello World"

廖文宏 Python Programming 23


Lab 2.4.1.7, 2.4.1.9, 2.4.1.10

廖文宏 Python Programming 24


2.4.1.8 Shortcut Assignment Operator
 variable = variable op expression
It can be simplified and shown as follows:
variable op= expression

廖文宏 Python Programming 25


Supplement: Variable Delete
 The del keyword is used to delete objects.
 In Python everything is an object, so the del keyword can
also be used to delete variables, lists, or parts of a list etc.
 del remove identifier only, not the data/instance. e.g.
x = 10
y=x
del x
print(y) # 10
 del x doesn’t directly call x.del() — the former decrements
the reference count for x by one, and the latter is only called
when x‘s reference count reaches zero

廖文宏 Python Programming 26


2.5 Comments
 Line comments in Python
A piece of text that begins with a hash character sign # and
extends to the end of the line.
 Good comments make a program readable, maintainable,
and reliable
 responsible developers describe each important piece of
code
 e.g., explaining the role of the variables;

 although it must be stated that the best way of commenting


variables is to name them in an unambiguous manner.
 Comments are ignored by the compiler/interpreter

廖文宏 Python Programming 27


2.6 input()
 read data entered by the user and to return the data to the
running program
 the result of the input() function is a string.
It is not an integer or a float.
 e.g.
var = input("Enter a number: ") # input data with prompt
 type casting (convert the data type)
 int(string), float(string)

 str(number)

廖文宏 Python Programming 28


2.6 String Operator
 concatenation operator +
 Strings can be concatenated (glued together) with the +

operator
e.g. 'un' + 'ium' gives 'unium'
 ensure that both its arguments are strings.

 replication operator *
 Strings can be replicated(repeated) with the * operator

e.g. 3 * 'm' gives 'mmm'

廖文宏 Python Programming 29

You might also like