0% found this document useful (0 votes)
7 views49 pages

Python Data Types and Variables Guide

Uploaded by

66723179wan
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)
7 views49 pages

Python Data Types and Variables Guide

Uploaded by

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

Python Basics

COMP1117B Computer Programming

1
Values and Types Type defines the operation
that you can perform with or
on a value.
Values are of different types.

Type Example Values

bool Boolean values True, False

int Integers -4, 0, 65

float Real numbers -2.36, 6.0e5, 7e-2


"abcde",
Character 'abcde', You can use type() to find out the
str type of a value.
strings "ab'cde",
Also note the different colors that
'ab"cde' the syntax highlighter hints you. 2
Values and Types
You may use either ' ' (single
quotes) or " " (double quotes)
to delimit a string.

Beware of the smart quotes


‘’ or “” (or quotes in any other
language encodings, e.g.,
Chinese) when you do copy-
and-paste.
3
Type Casting – convert a value from one type to another
Non-zero values are considered as True.

True -> 1, False -> 0 if


convert to a number

Warning: Make sure you know the


difference between
True and "True". 4
Type Casting – convert a value from one type to another

The operators of ‘+’ are two Booleans.


Type cast the Booleans to integers
2 before doing the addition.

The operators of ‘+’ are two strings.


The ‘+’ operator performs string
'TrueTrue' concatenation (joining) instead.

5
Variable: a Name that refers to a value
After a long and difficult computation, you have got an important
value. Then, you can give this value some "name", and in the rest of
your program, you can use this "name" to refer to this value.

From now on, you can use BMI to refer to


BMI 22.49
the value 22.49, until you associate BMI
with another value.
The above diagram reminds us that BMI
Sometimes, we say that BMI is a variable.
is referring to the value 22.49 6
Rules for naming a variable
Variables names must start with a letter or an underscore, such as:
• temperature, _underscore

The remainder of your variable name may consist of letters, digits


and underscores.
• password1, n00b, un_der_scores, _ooOoo_

Names are case sensitive.


• case_sensitive, CASE_SENSITIVE, and Case_Sensitive are
different variable names
7
Rules for naming a variable
There are some "reserved" words (keywords) in Python that
cannot be used as variable names.

You do not need to memorize the list.


The syntax highlighter can tell.

8
Rules for naming a variable
There are other words that
are not keywords, but you
should avoid using them as
variable names, e.g., input,
print, type, which are
names of some “build-in”
functions.

9
Input()
We can use input() to read a string from the keyboard and give
this string a name. Prompt message for the user

Regardless of what the user types at


the prompt, the input is always a string.

An error is raised when we add


a number with a string 10
Input()
How can we obtain an integer (or a float number) input then?
Use type casting

11
Exercise
Write a program that prompts the user for a radius of a sphere, and
calculates and outputs the volume of the sphere.

12
Sequence of values: Lists
list: A sequence of values (can be of different types)
Examples:
• [1, 30, 25, 100]
• ['A', 'B', 'C', 'D', 'E']
• [[1,2,3], "happy", 40.0, True]

If a list is associated with a variable name (say, L), we can access the
entries in the list by indexes: L[0], L[1], …, L[length – 1], where length is
total number of entries in the list.
Note that the index of the first entry is 0.
13
Sequence of values: Lists
We can change the value of any entry in a list.

We can append a new entry to a list


14
Sequence of values: Lists
We can construct a table using list.
Example: Construct the following table T:
0 1 2

3 4 5

6 7 8

Output:
[0, 1, 2]
0 4 8
15
Exercise
A magic square is a 3x3 table with nine distinct integers from 1 to 9 so
that the sum of integers in each row, column, and corner-to-corner
diagonal is the same.
An example:
2 7 6
9 5 1

4 3 8

Write a Python program that reads a 3x3 table and prints the sum of
integers in each row, column, and corner-to-corner diagonal.

16
A useful way to solving the problem
#create a 3 x 3 table T. Don’t worry how to do it at the moment.
#input entries of the table
T[0][0]=int(input())
T[0][1]=int(input())
T[0][2]=int(input()) T[0][0] T[0][1] T[0][2]

… T[1][0] T[1][1] T[1][2]


#print sums
T[2][0] T[2][1] T[2][2]
print(T[0][0]+T[0][1]+T[0][2])

print(T[0][0]+T[1][1]+T[2][2])
print(T[0][2]+T[1][1]+T[2][0])

17
How to create a 3x3 table
#method 1 #method 3
T=[[0,0,0],[0,0,0],[0,0,0]] R = [0,0,0]
T = [] 0 0 0
0 0 0
[Link](R)
0 0 0
#method 2
[Link](R)
T=[]
[Link](R)
[Link]([0,0,0])
[Link]([0,0,0])
[Link]([0,0,0])

18
How to create a 3x3 table
#method 1 #method 3
T=[[0,0,0],[0,0,0],[0,0,0]] R = [0,0,0]
T = [] 0 0 0
0 0 0
[Link](R)
0 0 0
#method 2


[Link](R)
T=[]
[Link](R)
[Link]([0,0,0])
[Link]([0,0,0]) Method 3 is wrong. Why?
[Link]([0,0,0])

19
How to create a 3x3 table
# Try this (method 3)
R = [0,0,0]
T = []
[Link](R)
[Link](R)
[Link](R)
print(T)
T[1][1] = 7
print (T)

20
How to create a 3x3 table
# Try this (method 3) [Link] provides a good tool to visualize Python code execution.

1 R = [0,0,0]
2 T = []
3 [Link](R) After line 5:

4 [Link](R)
5 [Link](R)
6 print(T) There is only one R list in the main memory. When we
append R to T, it simply append a pointer to R to T.
7 T[1][1] = 7 (i.e., no copying of R is done)

8 print (T)

21
How to create a 3x3 table
# Try this (method 3) [Link] provides a good tool to visualize Python code execution.

1 R = [0,0,0]
2 T = []
3 [Link](R) After line 5:

4 [Link](R)
5 [Link](R)
6 print(T)
7 T[1][1] = 7 After line 7:

8 print (T)

We follow the pointer, access and update R. 22


How to create a 3x3 table
#method 1 #method 3
T=[[0,0,0],[0,0,0],[0,0,0]] R = [0,0,0]
T = [] 0 0 0
0 0 0
[Link](R)
0 0 0
#method 2


[Link](R)
T=[]
[Link](R)
[Link]([0,0,0])
[Link]([0,0,0])
#method 4


[Link]([0,0,0])
R = [0,0,0]
Method 4 is wrong for the same
T = [R, R, R] reason. 23
How to create a 3x3 table
#method 1 #method 3 Advice for beginners: Use actual values.
T = []
T=[[0,0,0],[0,0,0],[0,0,0]] [Link]([])
[Link]([]) 0 0 0
[Link]([]) 0 0 0
print(T) 0 0 0
#method 2 T[0].append(0)
T=[] T[0].append(0)
T[0].append(0)
[Link]([0,0,0]) T[1].append(0)
[Link]([0,0,0]) T[1].append(0)


T[1].append(0)
[Link]([0,0,0]) T[2].append(0)
T[2].append(0)
T[2].append(0) 24
Yet another method

R1, R2 and R3 are 3 different lists in the main memory.

25
Sequence of values: Tuples
tuple: A sequence of values (can be of different types) like list. But
you cannot make any change to it. tuple can be viewed as a
constant list.
Examples:
([1,2,3], "happy", 40.0, True)

If we associate a tuple with a variable


name (say, T), we can access the entries
in the list by indexes (e.g., T[0], T[1], …,
T[length – 1], where length is total
number of entries in the tuple. For tuple, you can omit the parentheses.
Example:
mytuple = 'a', 'b', True, 54 26
Sequence of values: Tuples
For tuple, you can omit the parentheses.
Example:
>>> mytuple = 'a', 'b', True, 54
>>> print(mytuple)
('a', 'b', True, 54)
>>> a = 1,
>>> print(a)
(1,)
>>> a = 1
>>> print(a)
1 27
Sequence of values: Tuples
Our old friend str can be viewed as a special case of tuple, in which
all entries are characters.

28
type() and type casting for list, tuple and string

list(A): cast A into a list

tuple(B): cast B into a tuple

str(C): cast C into a string

29
Set
A collection of values (or you
may view set as a sequence of
values, but without order)

As there is no order, we cannot


refer its entries by indexes.

30
Set
Set membership testing: the in operator

tuple can be an element


list cannot be an element

31
Set
Add elements to a set

32
Dictionary
A set of key:value pairs. Again, the entries do not have order.

Given a key, we can access


the corresponding value.

Add a new key:value pair


to the dictionary

How about this? phonelist["Tim"]="abcde"


Yes, it’s correct. The type of entry doesn’t matter.
33
A more complicated example

What is the type of users?

What is the type of users[0]?

34
Summary of Python Built-in Data Types

Type Example values


bool True, False
int 34, -41
float 34.5, -3.14e7
str "Peter", 'Mary' [Link]

list a = [1, 'h', [6, 7,8]] è a[0], a[1], a[2]


tuple t = ('a','b',22,[True,False]) è t[0], t[1], t[2], t[3]
set s = {1, 'a', ("Hello", 4)} è s[0]´
dictionary d = {"Peter":100, "Mary":89} è d["Peter"]
35
Expressions
Expression is a combination of operators and operands that should
evaluate to some values. 1+2 a–1 a * (b // 3)

Operators for simple values Operators for sequences of values (i.e.,


for lists, tuples, and strings, but not for
• Arithmetic operators
dictionaries and sets)
• Relational (Comparison) operators
• Concatenator +
• Logical operators
• Repeat *
• Membership operators
• Relational (Comparison) operators

36
Arithmetic
E.g., a = 10, b = 20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b / a = 2.0

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20

// Floor Division - The division of operands where the result is 9 // 2 = 4


the quotient in which the digits after the decimal point are 9.0 // 2.0 = 4.0
removed. But if one of the operands is negative, the result is -11 // 3 = -4
floored, i.e., rounded away from zero (towards negative -11.0 // 3 = -4.0
infinity) −

37
Relational (Comparison)
E.g., a = 10, b = 20
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a != b) is true.
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is
similar to != operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is not true.
condition becomes true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.

Deprecated in Python 3
38
Logical and True if both operands are True, and
E.g., A = True, B = False
A and B = False
False otherwise

or False if both operands are False, and A or B = True


True otherwise

not True if operand is False, and False if not A = False


operand is True not B = True

Membership
in Evaluates to true if it finds a variable in x in y, here in results is a 1
the specified sequence and false if x is a member of
otherwise. sequence y.
not in Evaluates to true if it does not find a x not in y, here not in
variable in the specified sequence and results is a 1 if x is not a
false otherwise. member of sequence y.
39
Operator Precedence
Operator Description
or Boolean OR
Low
and Boolean AND
not x Boolean NOT
Comparisons, including membership tests and identity
<, <=, >, >=, !=, ==
tests
+, - Addition and subtraction
Multiplication, matrix multiplication, division, floor
*, /, //, %
division, remainder
High +x, -x Positive, negative
** Exponentiation

e.g., 4 + 3 ** 2 evaluates to 13
Question: what would 4 and 3 + 2 > – 5 // 2 evaluate to?
40
operator + for combining two sequences

ç 2 tuples

ç 2 lists

ç 1 tuple & 1 list

ç 2 sets

Only for sequences 41


Operator * for repeating a sequence

ç Repeat a tuple 4 times

ç Repeat a list 4 times

ç Repeating a set is not allowed!!!

42
Comparison operators on sequences
Lexicographical (dictionary) order on sequences
• Given two sequences a, b of equal length.
• a == b if both sequences have the same values at the same position.
• a < b if at the first position where a and b have different values, a’s value is smaller than
b’s.
• When a and b have different lengths. Suppose without loss of generality that a
is the shorter sequence. Then let a’ be the sequence of a appended with the
NULL values so that the length of a’ and b are equal. Here, NULL is smaller than
any other value. Then
• a < b if and only if a’ < b.

Examples
• [4, 5, 6] == [4, 5, 6]: True
• [4, 5, 6] < [4, 3, 100]: False
• [4, 5, 6] < [4, 5, 6, 7]: True (because [4, 5, 6, NULL] < [4, 5, 6, 7])
43
Special characters

\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL) ç
\b ASCII Backspace (BS) ç
\f ASCII Formfeed (FF) ç May have different behavior
\n ASCII newline because of the environment (e.g.,
Windows OS, MacOS)
\r ASCII Carriage Return (CR) ç
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT) ç

44
Example

45
Example

46
raw string
You can ask Python to ignore special characters by using raw-string.
You create a raw string using r"".

47
sep (separator) & end for print

default: sep=' ', and end='\n'


48
f-string
A new feature introduced in Python 3.6
It provides a simple way to substitute values into strings.

Without using f-string The string in {} is treated as an ordinary


No need to use , and ‘ / “ to compose the
expression, and Python will print the
string. Instead, we use {} to enclose a
result of this expressionin the f-string. 49
variable.

You might also like