0% found this document useful (0 votes)
60 views

Lec02 Python Basics

The document provides an overview of Python basics such as literals, variables, data types, operators, and coding styles. It discusses the different types of literals in Python and their corresponding data types. The document also covers Python keywords, naming rules for variables and identifiers, and various reserved classes of identifiers.

Uploaded by

Marcus Lee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Lec02 Python Basics

The document provides an overview of Python basics such as literals, variables, data types, operators, and coding styles. It discusses the different types of literals in Python and their corresponding data types. The document also covers Python keywords, naming rules for variables and identifiers, and various reserved classes of identifiers.

Uploaded by

Marcus Lee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

CSCI2040

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.

• Literals are values (like numbers, strings or characters) that appear


directly in a program.
88 # Integer literal
41.62 # Floating point literal
"Hello" # String literal

• 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:

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

7
Variables
• Our first Python program:
# Your first Python program
print('Hello, world!') print a string literal (constant)

• Let us massage it a bit:


# Your second Python program
mesg = 'Hello, world!'
print(mesg) print a string variable

• These two programs generate the same output.


• In the second version, we assign a string-type value to a variable.
8
Variables
• In Python, we don't declare a variable (with a type) as we do in C/C++.
std::string warning = 'Now for something completely different';
int n = 41;
const double pi = 3.1415926535897932;

• Instead, we use an assignment statement to create a new variable


and give it a value:
>>> warning = 'Now for something completely different'
>>> n = 41
>>> pi = 3.1415926535897932

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
_

no special meaning and is not defined. >>> 21


21
>>> _
21

13
Identifiers: Reserved Classes of Identifiers
dunder = double underscore

• __*__ : system-defined names, informally known as "dunder" names.


• For example, __name__, __init__ are dunder names.
• These names are defined by the interpreter and its implementation (including
the standard library). See the Special method names section of Python 3 spec.
Any use of __*__ names, in any context, that does not follow explicitly
documented use, is subject to breakage without warning.
• __* : Class-private names
• e.g. __student_id is a private variable of a class
• These names, when used within the context of a class definition, are re-
written to use a mangled form to help avoid name clashes between “private”
attributes of base and derived classes. See section Identifiers (Names).

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

More info: http://xahlee.info/comp/unicode_support_ruby_python_elisp.html


17
Identifiers
• However, you can't use emoji as identifiers in Python 3.
• Luckily (to me), I won't see symbols like 🤬 in your code.
>>> ☃ = "brrr!"
Traceback (most recent call last):
...
SyntaxError: invalid character in identifier

>>> ♥ = 4
File "<stdin>", line 1
♥ = 4
^
SyntaxError: invalid character in identifier

Python 3 restricts variable names to unicode characters


that represent characters in written languages.
18
Variable Assignment
• Note: A variable must be assigned a value before it can be used in an
expression. >>> b = a + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

>>> a = 1
>>> b = a + 1
>>> b
2

• Assigning value to a literal is surely an error:


>>> 10 = x
File "<stdin>", line 1
SyntaxError: cannot assign to literal
19
Variable Assignment
• What is the result of below?
>>> a = b = c = 300
>>> print(a, b, c)
300 300 300

• Python allows chained assignment, i.e. assigning the same value to


several variables simultaneously.

20
Variable Assignment
• Python supports simultaneous assignment to multiple variables.
• Syntax:
var1, var2, var3, ... var_n = exp1, exp2, exp3, ... exp_n

• Example: >>> x, y, z = 1, 3.14, "good"


>>> x
1
>>> y
3.14
>>> z
'good'

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

# After swapping, p and q become: # After swapping


>>> p >>> p
3 3
>>> q >>> q
2 2
22
Standard Input and Output

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?")

• What to do if we have multiple values to print?

24
Detour: Python 2's way to suppress print's default \n:
print x, # Trailing comma suppresses newline

The print() Function


• You may call print() multiple times: Output:
print('Hello') Hello
print('World') World
print('Good Bye') Good Bye

• Note that print() automatically appends a newline character (\n) at


the end of your argument string. If you want to display the above
messages in one line, you can invoke print() by passing a special
argument named end with it set to a space (replacing the default \n).
print('Hello', end=' ') # Appends a space instead of a newline
print('World', end=' ') # Appends a space instead of a newline
print('Good Bye')

Output: Hello World Good Bye


25
The print() Function
• A simpler way to print the same is to provide multiple arguments as a
comma-separated list to one print() call:
Output:
print('Hello', 'World', 'Good Bye') Hello World Good Bye

• Another example:
sweety = 'Noelle'
darling = 'Victoria'
greeting = "how are you!" Output:
print(sweety, darling, greeting) Noelle Victoria how are you!

• By default, print() adds a space separator between the arguments.


26
sweety = 'Noelle'

The print() Function


darling = 'Victoria'
greeting = "how are you!"

• Can we change the default separator from space to another symbol?


• For example, how to print:
Noelle, Victoria, how are you!
• Answer code:
print(sweety, darling, greeting, sep=", ")

• How to make it sweeter like


Noelle ♡ Victoria ♡ how are you! ♡ U+2661

• Answer code:
print(sweety, darling, greeting, sep=" \u2661 ")
27
sweety = 'Noelle'

The print() Function


darling = 'Victoria'
greeting = "how are you!"
age = 3

• If you have a Java background, you may also "weave the string" using
the + operator (string concatenation):
print(sweety + ', ' + darling + ', ' + greeting)

Noelle, Victoria, how are you!

• How about this one?


print(sweety + ", are you " + age + " years old?")

age is of int type; it cannot


• An error will be seen: be concatenated with strings

TypeError: can only concatenate str (not "int") to str

28
sweety = 'Noelle'

The print() Function


darling = 'Victoria'
greeting = "how are you!"
age = 3

• So unlike Java, Python does not involve an implicit type conversion of


the age variable from int type (3) to str type ("3").
• You need to convert explicitly using the built-in str() function in this
case before doing the string concatenation.
print(sweety + ", are you " + str(age) + " years old?")

Noelle, are you 3 years old?

• We will learn more operations on strings later.

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 \
""" """

Flat E, Block 4, Beautiful Garden,


Flat E, Block 4, High Street, Hong Kong
Beautiful Garden,
High Street,
Hong Kong
31
The Escape Character
• Through the last example, we see that string literals can span multiple
lines. One way is using triple-quotes: """...""" or '''...'''.
• End of lines are automatically included in the string, but it’s possible
to prevent this by adding a backlash \ at the end of the line.

32
The Escape Character
• What is the output of the following code?
print('C:\some\name')

C:\some
ame

• Beware of \n which means newline!


• If you don’t want characters prefaced by \ to be interpreted as special
characters, use raw strings by adding an r before the first quote:
print(r'C:\some\name')

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:

print("Toys: %5d, Price: %7.2f" % (432, 67.058))

format string tuple with values


string modulo operator

• Output: Toys: 432, Price: 67.06

1 space 5 digits 1 space 7 digits

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

Toys: 00432, Price: +67.06


flags:
0 zero padded for numeric values.
print("Toys: %-5d, Price: %-+7.2f" % (432, 67.058)) - left adjusted
+ A sign character ("+" or "-") will
Toys: 432 , Price: +67.06 precede

More details: https://docs.python.org/2.4/lib/typesseq-strings.html 36


Output Formatting
• Since Python 2.6 has been introduced, the string method format
should be used instead of the old-style formatting.
• Using .format(), we can construct strings with the value of a variable.
• This is called string interpolation.
name = "Victoria"
code = 1011
message = "Hey {}, your code number is {}.".format(name, code)
print(message)

Hey Victoria, your code number is 1011.

• A pair of braces is used to denote a placeholder for each argument.


37
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!

txt1 = "My name is {fname}, I'am {age}".format(fname = "Noelle", age = 2.5)


txt2 = "My name is {0}, I'am {1}".format("Noelle", 2.5)
txt3 = "My name is {}, I'am {}".format("Noelle", 2.5)

print(txt1) My name is Noelle, I'am 2.5


print(txt2) My name is Noelle, I'am 2.5
print(txt3) My name is Noelle, I'am 2.5

38
Output Formatting
• Padding and aligning strings Align right:

• You can add a '<' or '>' symbol to make '{:>10}'.format('test')


the output left-adjusted or right-
adjusted.
• Without the '<' or '>' symbol, default padding
alignment is left-adjusted.
Align left:

'{: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.

• Python 3 has a built-in function input() to accept user input (in


terms of strings) through the keyboard.
>>> user_name = input("Enter your username: ") Underlined here to
Enter your username: ktlam indicate this string
>>> user_name is input by the user.
'ktlam'
>>> print("Your username is", user_name)
Your username is ktlam

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'

>>> qty = int(input("Enter a number: "))


Enter a number: 10
>>> price = qty * 2.5
>>> price
25.0
44
Getting User Input
• How to deal with situations that you are not sure about the data type
of the user input? That is, the user may enter a value of any type like
int, float, string, complex, etc.
• Using eval() can automatically determine the type.
• Example: >>> name = (input('Enter your name :'))
Enter your name: Victoria
>>> age = eval(input('Enter your age: '))
Enter your age: 5
age and height are
>>> height = eval(input('Enter your height: ')) int and float respectively.
Enter your height: 101.5
>>> print('User details are as follows:')
User details are as follows:
>>> print(f'name: {name}, age: {age}, height: {height}')
name: Victoria, age: 5, height: 101.5
>>>
45
Python Core Data Types

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

• For floating point numbers, int() truncates towards zero, meaning


everything after the decimal point gets removed.

50
The int() Function
• Examples:
>>> int()
0

>>> x = int(123.456) # float


>>> y = int("123") # string
>>> print(x == y)
True
>>> print(x, y)
123 123

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

• Examples with base other than 10:


Binary: Octal: Hexadecimal:
>>> int('10', 2) >>> int('10', 8) >>> int('10', 16)
2 8 16
>>> int('100', 2) >>> int('100', 8) >>> int('100', 16)
4 64 256
>>> int('110', 2) >>> int('1000', 8) >>> int('1000', 16)
6 512 4096
>>> int('1000', 2) >>> int('1011', 8) >>> int('1001', 16)
8 521 4097

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

>>> 3.14 # decimal notation


3.14
>>> 2.34e2 # scientific notation
234.0
>>> 2.34e-2 # scientific notation
0.0234
53
Floating-Point Number
• Experiment below yourself. What do you observe?
>>> print(0.1) >>> print(0.1 + 1.0) >>> print(0.1 + 2.0)
0.1 1.1 2.1
>>> print(0.1 + 0.1) >>> print(0.1 + 1.1) >>> print(0.1 + 2.1)
0.2 1.2000000000000002 2.2
>>> print(0.1 + 0.2) >>> print(0.1 + 1.2) >>> print(0.1 + 2.2)
0.30000000000000004 1.3 2.3000000000000003
>>> print(0.1 + 0.3) >>> print(0.1 + 1.3) >>> print(0.1 + 2.3)
0.4 1.4000000000000001 2.4
>>> print(0.1 + 0.4) >>> print(0.1 + 1.4) >>> print(0.1 + 2.4)
0.5 1.5 2.5
>>> print(0.1 + 0.5) >>> print(0.1 + 1.5) >>> print(0.1 + 2.5)
0.6 1.6 2.6
>>> print(0.1 + 0.6) >>> print(0.1 + 1.6) >>> print(0.1 + 2.6)
0.7 1.7000000000000002 2.7
>>> print(0.1 + 0.7) >>> print(0.1 + 1.7) >>> print(0.1 + 2.7)
0.7999999999999999 1.8 2.8000000000000003
>>> print(0.1 + 0.8) >>> print(0.1 + 1.8) >>> print(0.1 + 2.8)
0.9 1.9000000000000001 2.9
>>> print(0.1 + 0.9) >>> print(0.1 + 1.9) >>> print(0.1 + 2.9)
1.0 2.0 3.0 54
Floating-Point Number
• Floating-point numbers are represented in computer hardware as
base 2 (binary) fractions.
• Consider: 0.125 = 1/10 + 2/100 + 5/1000
10

0.0012 = 0/2 + 0/4 + 1/8

• 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

• The decimal value 0.1 cannot be represented 1 x 2-3 = 0.0125


exactly as a base 2 fraction. In base 2, 1/10 is 0 x 2-2 = 0
the infinitely repeating fraction:
1 x 2-1 = 0.5
0.0001100110011001100110011001100110011001100110011...
0.687510
• All these values can only be approximated on a
binary digital computer.

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

• Operations over the imprecise values can accumulate into more


apparent data representation error:
>>> 0.1 + 0.2
0.30000000000000004

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

5 is of type: <class 'int'>


5.0 is of type: <class 'float'>

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

• For example, >>> complex()


0j
>>> complex(2)
(2+0j)
>>> complex(3j)
3j
>>> z = complex(5, 3);
>>> print ("The real part: ", z.real)
5.0
>>> print ("The imaginary part: ", z.imag)
3.0
61
Boolean Type
• The Boolean data type is represented in Python as type bool. This
type has only one of the two values – True or False (case-sensitive).
• Internally, the True value is represented as 1 and False as 0.
>>> True >>> 5 == 4
True False
>>> type(True) >>> 5 == 5
<class 'bool'> True
>>> False >>> 6 > 3
False True
>>> type(False) >>> 3 > 6
<class 'bool'> False
>>> true >>> True == 1
... True
NameError: name 'true' is not defined >>> False == 0
True
62
String Type
• A string literal or variable in Python can be created using single,
double and triple quotes.
• Examples:
>>> p = 'Sammy says, "Hello!"' >>> p
>>> q = "Sammy's balloon is red." 'Sammy says, "Hello!"'
>>> q
>>> s = ''' "Sammy's balloon is red."
This string is on >>> s
multiple lines '\nThis string is on\nmultiple lines\nwithin
within three single three single\nquotes on either side.\n'
quotes on either side. >>> t
''' 'This string is on\nmultiple lines\nwithin
three double\nquotes on either side.'
>>> t = """This string is on >>>
multiple lines
within three double
quotes on either side.""" 63
Typecasting to String
• The str() function is used to convert a number into a string.
• Examples:
>>> 12.5
12.5
>>> type(12.5)
<class 'float'>
>>> s = str(12.5)
>>> s
'12.5'
>>> type(s)
<class 'str'>

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

* Note: In Py2, the result of 7/2 is 3 (int).


To get 3.5 in Py2, you need to do 7.0 / 2.
67
Assignment Operators
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3 68
Logical Operators
• Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

69
Bitwise Operators
• Let x = 10 (0000 10102) and y = 4 (0000 01002) in the examples:

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)

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)

• To disable portion of code


• For convenience in program testing and debugging
• In cases that the code being disabled might better be retained for possibility
of future resumption.

78
Python Comments
• There are 3 ways of creating comments in Python.

# This is a single-line comment

'''
This is a
multiline
comment.
'''

"""
This is also a
multiline
comment.
"""
79
Self-Study

“Code is more often read than written.”


— Guido van Rossum

Style Guide for Python Code


A Foolish Consistency is the Hobgoblin of Little Minds

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)

# Further indentation required as indentation is not distinguishable.


def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)

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

Naming Conventions my_var = 'good'


last_name = "Lam"

def my_function():
• Constant Names pass
• All capital letters
def multiply_by_two(x):
• Use underscore to separate words return x * 2

• Variable, Function, and Module Names my_module.py

• All lower case class CoolCat():


• Use underscore to separate words
class NaughtyBaby():

• Class names, Type


• Use camel case convention (CapWords convention)
• Capital letters for the start of each word in an identifier

87
Automatically Formatting Your Python Code
• You can make your code adhere to PEP8 style automatically!
• Install autopep8:
$ pip install autopep8

• Show the reformatted code of your script file, e.g. hello_world.py:


$ autopep8 hello_world.py

• Directly apply the reformatting to your script file in-place:


$ autopep8 -i hello_world.py

88
Summary
• Basic syntax covered.
• Note your coding style!

89

You might also like