Lec02 Python Basics
Lec02 Python Basics
Introduction to
Python
Lecture 2: Python Basics
2022-23 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 method 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: 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
• Is there a printf() function in Python?
• A burning question for Python newbies coming from the C-language camp.
• No, but the functionality of the "ancient" printf is contained in Python.
• The modulo operator "%" is overloaded by the string class to perform
string formatting. Therefore, it is often called string modulo operator.
• Another term for it is "string interpolation", because it interpolates
various class types (like int, float, ….) into a formatted string.
https://www.python-course.eu/python3_formatted_output.php 34
Output Formatting in Old (C-like) Manner
• See how the string modulo operator works:
35
Output Formatting in Old (C-like) Manner
• The general syntax for a format placeholder is
%[flags][width][.precision]type
type:
• More examples: d Signed integer decimal
f floating point decimal
s string - converts any python
print("Toys: %05d, Price: %+7.2f" % (432, 67.058))
object using str()
38
Output Formatting
• Padding and aligning strings Align right:
'{:10}'.format('test')
'{:<10}'.format('test')
padding
39
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.
• Example: >>> '{:.5}'.format('xylophone')
'xylop'
>>> '{:.5}'.format(0.1526536)
'0.15265’
>>> '{:.5}'.format(3.1526536)
'3.1527'
40
f-Strings
• Since Python 3.6, you can do output formatting with "f-strings".
• Examples:
>>> name = "King Tin" >>> val = 12.3
>>> age = 74 >>> print(f'{val:.2f}')
>>> f"Hello, {name}. You are {age}." 12.30
'Hello, King Tin. You are 74.' >>> print(f'{val:.5f}')
12.30000
41
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/
42
Detour:
Python has another function
Getting User Input called raw_input() which has
been deprecated in Python 3.
43
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'
46
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("x = %d" % x)
x = 123
47
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
48
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 49
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
50
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'
51
The int() Function
• Recall syntax: int(x, base=10) # x must be a string
52
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 55
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 56
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 57
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 58
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))
59
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'>
60
Complex Number
• Another way to create a complex number is to call the complex()
function:
complex([real[, imag]])
64
Operators
65
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 66
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
69
Bitwise Operators
• Let x = 10 (0000 10102) and y = 4 (0000 01002) in the examples:
70
Identity Operators
• Python identity operators (is and is not) are used to check if two
variables point to the same object in memory.
• Before talking the operators, let's understand the id() function first.
• Calling id(x) returns the "identity" of an object x.
• This id is an integer guaranteed to be unique and constant for the
object during its lifetime.
• Two objects with non-overlapping lifetimes may have the same id
value.
• In CPython implementation, this id is the object's memory address.
71
Identity Operators
• Simply put, the identity operators compare the memory locations of
two objects.
Operator Description Example
is Evaluates to true if the variables on either side of
x is y, here is results in 1 if
the operator point to the same object and false
id(x) equals id(y).
otherwise.
is not Evaluates to false if the variables on either side of
x is not y, here is not results
the operator point to the same object and true
in 1 if id(x) is not equal to id(y).
otherwise.
72
“Code tells you how; Comments tell you why.”
— Jeff Atwood (aka Coding Horror)
Comments
Why Documenting Your Code is So Important?
77
Uses of Comments
• To enhance readability of your code
• Essential to team programming
• As documentation
• To assist users using your code (classes and functions)
78
Python Comments
• There are 3 ways of creating comments in Python.
'''
This is a
multiline
comment.
'''
"""
This is also a
multiline
comment.
"""
79
Self-Study
https://www.python.org/dev/peps/pep-0008/#naming-conventions
80
Famous Features of Python’s Syntax
• No ; (semicolons)
• No { } (parentheses)
• No troubles for programming beginners.
• Indentation (or white space) matters!
81
Python Coding Style
• PEP8 https://www.python.org/dev/peps/pep-0008/ is the official
style guide.
82
Code Layout Python 3 disallows mixing the use of
tabs and spaces for indentation.
• Indentation
• Always use 4 spaces per indentation level. Why not 3 or 2 or 5 spaces?
• Don't use tab for indentation (for good portability)
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# Hanging indents should add a level. # Hanging indents *may* be other than 4 spaces.
foo = long_function_name( foo = long_function_name(
var_one, var_two, var_one, var_two,
var_three, var_four) var_three, var_four) 83
Code Layout
• Indentation
• Wrong style below:
# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
84
Code Layout
• Maximum Line Length
• Limit all lines to a maximum of 79 characters.
• For flowing long blocks of text with fewer structural restrictions (docstrings or
comments), the line length should be limited to 72 characters.
• Limiting the required editor window width makes it possible to have several
files open side-by-side, and works well when using code review tools that
present the two versions in adjacent columns.
• The default wrapping in most tools disrupts the visual structure of the code,
making it more difficult to understand. The limits are chosen to avoid
wrapping in editors with the window width set to 80, even if the tool places a
marker glyph in the final column when wrapping lines. Some web-based tools
may not offer dynamic line wrapping at all.
https://www.python.org/dev/peps/pep-0008/#naming-conventions
85
Code Layout
• Maximum Line Length
• Some teams strongly prefer a longer line length. For code maintained
exclusively or primarily by a team that can reach agreement on this issue, it is
okay to increase the line length limit up to 99 characters, provided that
comments and docstrings are still wrapped at 72 characters.
• The Python standard library is conservative and requires limiting lines to 79
characters (and docstrings/comments to 72).
• The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
https://www.python.org/dev/peps/pep-0008/#naming-conventions
86
GRAVITY_ACCEL = 9.8
def my_function():
• Constant Names pass
• All capital letters
def multiply_by_two(x):
• Use underscore to separate words return x * 2
87
Automatically Formatting Your Python Code
• You can make your code adhere to PEP8 style automatically!
• Install autopep8:
$ pip install autopep8
88
Summary
• Basic syntax covered.
• Note your coding style!
89