lec02-python-basics (new)
lec02-python-basics (new)
Computer
Principles and
Python
Programming
Lecture 2: Python Basics
2024-25 Term 2
By Dr. King Tin Lam
Outline
• Literals
• Keywords
• Variables
• Standard I/O
• Output formatting
• Python Core Data Types
• Operators and Expressions
• Comments
• Coding Styles
2
Tokens in Python
• A program in Python is a sequence of statements.
• Each statement is composed of lexical components known as tokens.
• Python contains various types of tokens.
3
String literals may be delimited using
Literals (Constants) either single or double quotes.
• Every value in Python has a specific data type. To know the exact type
of a value, Python offers an in-built function called type().
• For example,
>>> type('Hello World')
<class 'str'>
>>> type(123)
<class 'int'>
4
Literals (Constants)
• A literal has a specific data type:
Examples Result of type(value)
Integer literals 0, 1, 2, -1, 2 <class 'int'>
Float literals 3.14 <class 'float'>
String literals 'a', "hello", '1234' <class 'str'>
Boolean literals True, False <class 'bool'>
Complex literals 2j <class 'complex'>
List literals [], [2, 3, 4] <class 'list'>
Tuple literals (), (7,), (1, 3, 5) <class 'tuple'>
Dict literals {}, {'x':1} <class 'dict'>
Set literals {8,9,10} <class 'set'>
5
Literals (Constants)
• Python 2 has two integer types - int and long.
• In Python 3, there is no long type anymore – only int type!
• Python 3's int (and Python 2's long) literals are of unlimited size!
• Only subject to the size of your computer's available memory.
Python 2: Python 3:
>>> type(9223372036854775807) >>> type(9223372036854775807)
<type 'int'> <class 'int'>
>>> type(9223372036854775808) >>> type(9223372036854775808)
<type 'long'> <class 'int'>
>>> type(123123123123123123123123123) >>> type(123123123123123123123123123)
<type 'long'> <class 'int'>
6
Keywords (Reserved Words)
• The following identifiers are used as reserved words, or keywords of
the language, and cannot be used as ordinary identifiers. They must
be spelled exactly as written here:
7
Variables
• Our first Python program:
# Your first Python program
print('Hello, world!') print a string literal (constant)
9
Identifiers
• An identifier is the name used to denote a variable, function, class or
other objects in program code.
• Variables names are a subset of identifiers.
10
Identifiers: Naming Rules
• All identifiers must obey the following naming rules.
• An identifier
• can only contain letters, digits, and underscores.
• can start with a letter or an underscore but cannot start with a digit.
• cannot be a keyword.
11
Identifiers: Naming Rules
• Python gives a syntax error if a programmer writes an invalid
identifier.
• Distinguish which are valid and invalid identifiers:
• name • A1
• First Name ❌ • MeBeforeYou
• _address • 12Name ❌
• class_size • for ❌ Btw, what does this mean?
• Salary@ ❌ • _for >>> true = True
>>> true
• _i4you • True ❌ True
• __2in_one • false
12
Identifiers: Reserved Classes of Identifiers
REPL mode: >>> 7 ** 2
49
• How about using _ (a single underscore alone) as the name >>> _
of a variable? Is it a valid identifier? 49
>>> x = 18
• Yes, it is valid (syntactically). >>> _
49
• But it may have special meaning. >>> x
• So, don't use it as variable name. 18
>>> _
• The special identifier _ is used in the interactive mode to 18
>>> print(20)
store the result of the last evaluation; it is stored in 20
the builtins module. When not in interactive mode, _ has >>>
18
_
13
Identifiers: Reserved Classes of Identifiers
dunder = double underscore
14
Identifiers: Naming Guidelines
• Identifiers should be self-descriptive while not being too long.
• For example,
• number – way too vague; don't what number you refer to
• number_of_JUPAS_applicants – way too long
• jupas_app_count – about right
e.g.
• Some variables (e.g. loop variables) are just temporary. for x in fruits:
print(x)
Their names can be as simple as x, y, z, i, j, k, …
• Beware of using the uppercase letters l and O which could be
confused with the numbers 1 and 0.
15
Identifiers
• As an interesting fact, nowadays many programming languages (e.g.
Swift, Julia, …) allow constant and variable names to contain almost
any character, including any unicode characters.
• For example, in Swift, you can write:
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"
let 🍺 = "beer"
print(🍺) // prints "beer"
16
Identifiers
• Perhaps scientists love to use unicode identifiers for math symbols
and functions to make their code look more like math formulae.
Example: Version 1:
from math import sin, cos, pi Phi(z) = integral(N(x|0,1,1), -inf, z)
π = pi
Version 2:
def ƒ(θ, ω):
return sin(θ) * cos(ω) φ(z) = ∫(N(x|0,1,1), -∞, z)
α = (30 / 180) * π
β = (60 / 180) * π Which version looks more intuitive?
Which version gets clumsier when coding?
print(ƒ(α, β)) # 0.25
>>> ♥ = 4
File "<stdin>", line 1
♥ = 4
^
SyntaxError: invalid character in identifier
>>> a = 1
>>> b = a + 1
>>> b
2
20
Variable Assignment
• Python supports simultaneous assignment to multiple variables.
• Syntax:
var1, var2, var3, ... var_n = exp1, exp2, exp3, ... exp_n
21
Variable Assignment
• One common use of multiple assignment is to swap the values of two
variables in a simplified manner.
Usual way of swapping two variables: Python's way: Cool! Neat!
p = 2 p = 2
q = 3 q = 3
temp = p # Back up value of p into temp p, q = q, p # p, q = 3, 2
p = q # Assign value of q to p
q = temp # Assign value of temp to q
23
The print() Function
• Syntax of print() function:
print(argument)
• The argument can be a value or variable of any type int, str, float
etc.
• Printing a single argument is simple, e.g.
print("Why 6 is afraid of 7?")
24
Detour: Python 2's way to suppress print's default \n:
print x, # Trailing comma suppresses newline
• Another example:
sweety = 'Noelle'
darling = 'Victoria'
greeting = "how are you!" Output:
print(sweety, darling, greeting) Noelle Victoria how are you!
• Answer code:
print(sweety, darling, greeting, sep=" \u2661 ")
27
sweety = 'Noelle'
• If you have a Java background, you may also "weave the string" using
the + operator (string concatenation):
print(sweety + ', ' + darling + ', ' + greeting)
28
sweety = 'Noelle'
29
Escape Sequences
Escape Sequence Description Example Output
\\ Backslash print("\\") \
\` Single quote print("\'") '
\" Double quote print("\"") "
\a ASCII bell (BEL) - ring the bell alert sound (e.g. in xterm) print("\a") N/A
\b ASCII backspace (BS) - remove previous character print("ab" + "\b" + "c") ac
Hello
\n ASCII newline or linefeed (LF) print("Hello\nWorld!")
World!
Hello
\f ASCII formfeed (FF) print("Hello\fWorld")
World!
ASCII carriage return (CR) - move all characters after (CR) to the beginning
\r print("1234567\rXXXXX") XXXXX67
of the line while overriding same number of characters moved.
\t ASCII horizontal tab (TAB) print("\t@Noelle") @Noelle
Hello
\v ASCII vertical tab (VT) print("Hello\vWorld!")
World!
\ooo Prints character based on its octal value print("\043") #
\xhh Prints character based on its hex value print("\x23") #
\N{name} Prints a character from the Unicode database print("\N{DAGGER}") †
\uxxxx Prints 16-bit hex value Unicode character print("\u041b") Л
\Uxxxxxxxx Prints 32-bit hex value Unicode character print("\U000001a9") Ʃ
30
The Escape Character
• Any difference between the outputs of the left and right code
snippets?
x = """ y = """\
Flat E, Block 4, Flat E, Block 4, \
Beautiful Garden, Beautiful Garden,
High Street, High Street, \
Hong Kong Hong Kong \
""" """
32
The Escape Character
• What is the output of the following code?
print('C:\some\name')
C:\some
ame
C:\some\name
33
Output Formatting
• Using .format(), we can construct strings with the value of a variable.
• This is called string interpolation.
• Example:
name = "Victoria"
code = 1011
message = "Hey {}, your code number is {}.".format(name, code)
print(message)
34
Output Formatting
• Indeed, the placeholders can be identified by named indexes {price},
numbered indexes {0}, or empty braces {}.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 32.1))
For only 32.10 dollars!
35
Output Formatting
• Padding and aligning strings Align right:
padding
36
Output Formatting
• Truncating long strings
• Inverse to padding, it is also possible to truncate overly long values to a
specific number of characters.
• The number behind the dot (.) in the formatting string specifies the precision
of the output. For strings, that means the output is truncated to the specified
length. You may ignore this
• Example: >>> '{:.5}'.format('xylophone') usage as we seldom use
'xylop' it for truncating string.
>>> '{:.5}'.format(0.1526536)
'0.15265’
>>> '{:.5}'.format(3.1526536)
'3.1527'
37
f-Strings
• Since Python 3.6, you can do output formatting with "f-strings".
• Examples:
>>> name = "King Tin" >>> val = 12.3
>>> age = 44 >>> print(f'{val:.2f}')
>>> f"Hello, {name}. You are {age}." 12.30
'Hello, King Tin. You are 44.' >>> print(f'{val:.5f}')
12.30000
38
f-Strings
• Compared with using the
format() function, writing in
f-strings is more concise.
>>> pi = 3.14159265359
>>> print("{:.3f}".format(pi))
3.142
>>> print(f"{pi:.3f}")
3.142
https://mkaz.blog/code/python-string-format-cookbook/
39
Detour:
Python has another function
Getting User Input called raw_input() which has
been deprecated in Python 3.
40
Getting User Input
• The input() function, by default, will convert all the information it
receives into a string.
• So for numeric inputs, you need to typecast them to int or float.
• Example:
>>> qty = input("Enter a number: ")
Enter a number: 10
>>> price = qty * 2.5
TypeError: can't multiply sequence by non-int of type 'float'
43
Integer
• Integer literals are written without commas.
• Add a leading minus sign to indicate a negative value.
>>> 10
10
>>> 123007
123007
>>> -99
-99
>>> x = 123
>>> print(x)
123
>>> print(f"x = {x}")
x = 123
44
(Optional)
Integer
• Have you ever had issues figuring out whether 100000000 is a
hundred million or a billion?
• In Python 3.6 or later, you can add underscores anywhere in an
integer to group the zeros, e.g.:
>>> a = 1_000_000_000
>>> a
1000000000
45
(Optional)
Integer
• Integer literals can be in decimal, binary, octal or hexadecimal format.
• A binary (base 2) is 0b or 0B followed by digits 1's and 0's.
• An octal (base 8) is represented by 0o or 0O followed by a sequence of digits
from 0 to 7.
• Similarly, a hexadecimal (base 16) is written as 0x or 0X followed by a
sequence of digits from 0, 1, 2, …, 9, A, B, …, F.
Bin: >>> 0b100 Oct: >>> 0o12 Hex: >>> 0x20
4 10 32
>>> 0b1110 >>> 0o100 >>> 0x33
14 64 51
>>> 0B1111 >>> 0o101 >>> 0X1F
15 65 31
>>> 0b10000 >>> 0o111 >>> 0XAF
16 73 175 46
The int() Function
• The int() function converts a string or a number into a whole
number.
• It returns an integer object constructed from a number or string x, or
returns 0 if no arguments are given.
• Syntax:
int(x=0) # x can be a number or string
int(x, base=10) # x must be a string
47
The int() Function
• Examples:
>>> int()
0
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
48
(Optional)
49
Floating-Point Number
• Decimal and scientific notations:
Decimal Notation Scientific Notation Meaning
2.34 2.34e0 2.34 x 100
23.4 2.34e1 2.34 x 101
234.0 2.34e2 2.34 x 102
0.234 2.34e-1 2.34 x 10-1
0.0234 2.34e-2 2.34 x 10-2
• These two fractions (in different base notations) have identical values.
• Unfortunately, most decimal fractions cannot be represented exactly
as binary fractions.
Ref: https://docs.python.org/2/tutorial/floatingpoint.html 52
Floating-Point Number
• For example, 0.687510 can be represented 0 . 1 0 1 1
exactly as 0.10112 but most other values like
0.6873, 0.6874, 0.6876 cannot. 1 x 2-4 = 0.0625
Ref: https://docs.python.org/2/tutorial/floatingpoint.html 53
Floating-Point Number
• Almost all machines today use IEEE-754 floating point arithmetic, and
almost all platforms map Python floats to IEEE-754 double precision.
IEEE-754 doubles contain 53 bits of precision.
sign 64-bit double
exponent mantissa
(11 bits) (52 bits)
• So when you enter the decimal number 0.1, the value stored
internally is the binary fraction:
0.00011001100110011001100110011001100110011001100110011010
Ref: https://docs.python.org/2/tutorial/floatingpoint.html 54
Floating-Point Number
• But Python keeps the number of digits manageable by displaying a
rounded value instead, i.e. display 0.1.
• If you want to look closer into the internally stored value, try:
>>> print('%.55f' % 0.1)
0.1000000000000000055511151231257827021181583404541015625
Ref: https://docs.python.org/2/tutorial/floatingpoint.html 55
Typecasting to Float
• We can use the built-in function float() to convert an integer or a
string to a float value.
• For example,
a = 5 >>> float("3.14")
print(a,'is of type:',type(a)) 3.14
>>> float("3a")
a = float(a) ...
# alternative method: ValueError: could not convert
# a = a + 0.0 string to float: '3a'
print(a,'is of type:',type(a))
56
(Optional)
Complex Number
• A complex number is a number expressed in the form a + bj, where a
and b are real numbers and j is the imaginary unit j2 = -1.
• For example,
>>> x = 2 + 4j
>>> x
(2+4j)
>>> type(x)
<class 'complex'>
>>> 12j
12j
>>> type(12j)
<class 'complex'>
57
(Optional)
Complex Number
• Another way to create a complex number is to call the complex()
function:
complex([real[, imag]])
61
Operators
62
Operators
• Python contains various operators, viz. arithmetic, relational, logical
and bitwise operators, etc.
• A unary operator has only one operand, e.g. –x (negation)
• A binary operator has two operands, e.g. x + y, a is b
Operators Operator Type
Arithmetic Operators + - * / // % **
Relational Operators == != <> <= >=
Logical Operators and not or
Bitwise Operators & | ~ ^ << >>
Assignment Operators = += -= *= /= %= //= **= &= |= ^= >>= <<=
Identity Operators is is not
Membership Test Operators in not in 63
Arithmetic Operators
RESULT
OPERATOR MEANING EXAMPLE
(PY3)
+ Add two operands or unary plus 7 + 2 9
- Subtract right operand from the left or unary minus 7 - 2 5
* Multiply two operands 7 * 2 14
/ Divide left operand by the right one (always results into float) 7 / 2 3.5 *
% Modulus - remainder of the division of left operand by the right 7 % 2 1
Floor division - division that results into whole number adjusted
// 7 // 2 3
to the left in the number line
** Exponent - left operand raised to the power of right 7 ** 2 49
66
“Code tells you how; Comments tell you why.”
— Jeff Atwood (aka Coding Horror)
Comments
Why Documenting Your Code is So Important?
67
Uses of Comments
• To enhance readability of your code
• Essential to team programming
• As documentation
• To assist users using your code (classes and functions)
68
Python Comments
• There are 3 ways of creating comments in Python.
'''
This is a
multiline
comment.
'''
"""
This is also a
multiline
comment.
"""
69
Summary
• Basic syntax covered.
• Note your coding style!
70