0% found this document useful (0 votes)
20 views40 pages

02 - Variables and Datatypes

Uploaded by

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

02 - Variables and Datatypes

Uploaded by

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

ENGM 4676/6676

02- Variables and Datatypes

Issam Hammad, Ph.D., P.Eng

Department of Engineering
Mathematics and Internetworking

1
Agenda
▪ Variables
▪ Numeric Data Types
▪ Arithmetic, Logical Comparison
▪ Type Checking and Conversion
▪ Math and Random Modules
▪ Mutable vs Immutable
▪ Lists, Dictionaries, Tuples, Sets, and Arrays (Data Structures)
▪ Booleans
▪ Strings and String formatting
▪ Indexing and Slicing
▪ Comments in Python 2
Variables
▪ Variables are named containers for storing data
▪ Python variables are dynamically typed
▪ Compiler recognizes data type at compile time
▪ Type declaration not required like in C
▪ Variables can be reassigned to any type

▪ Provides flexibility!

3
Declaring and Assigning Variables
▪ Several rules for declaring variables in Python:
▪ Names cannot start with a number
▪ Names cannot contain spaces, use _ instead
▪ Names cannot contain '",<>/?|\!@#%^&*~-+:
▪ Python standard is to use names with lowercase letters with underscores, also known
as “snake_case”

4
Numeric Data Types
▪ Three main numeric data types:
▪ Integers or int
▪ Floating point or float
▪ Complex

5
Arithmetic
▪ Addition: ▪ Floor division:
▪ 2+1 ▪ 3//2

▪ Subtraction: ▪ Modulo (remainder):


▪ 2-1 ▪ 7%4 = 3

▪ Multiplication: ▪ Exponentiation:
▪ 2*2 ▪ 2**3

▪ Division: ▪ Python obeys order of operations (PEMDAS):


▪ 3/2 ▪ 4 + 6/3 + 5*9 - 12

6
Arithmetic

7
Python Operators Precedence Rule - PEMDAS
▪ P – Parentheses.
▪ E – Exponentiation.
▪ M – Multiplication.
▪ D – Division.
▪ A – Addition.
▪ S – Subtraction.

8
Python Operators Precedence Rule - PEMDAS

9
Logical Comparison and Assignment
▪ logical comparisons test equality or
relational conditions, returning True
or False.
▪ The assignment operator = sets a
variable's value.
▪ Understanding the difference is vital
for accurate code logic.

10
Floating-point limitation
▪ Computers approximate decimals using binary, leading to slight inaccuracies
due to finite digit storage, not software limitations.

11
Type Checking
▪ Can check the type of a variable with the type() method

12
Type Conversion
▪ Can convert between different types with float(x) and int(x)

13
Type Conversion
▪ Python automatically casts
certain types, such as integers to
floats in mixed operations, to
maintain precision.
▪ You can you “isintance()” to
confirm the type.

14
Python Math Modules
▪ The math library in Python
provides a wide range of
mathematical functions and
constants, allowing for efficient
and accurate mathematical
calculations.

▪ It includes functions for basic


arithmetic, logarithms, and
more, making it essential for
scientific computing.

15
Python Math Modules
Summary of some math methods:
Function Description
acos(x) Returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
cos(x) Returns the cosine of x.
sin(x) Returns the sine of x.
tan(x) Returns the tangent of x.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
log2(x) Returns the base-2 logarithm of x.
log10(x) Returns the base-10 logarithm of x.

Note these tables are not exhaustive, math have many more methods!
More functions: https://docs.python.org/3/library/math.html

16
Python Random Modules
▪ The random library in Python
offers functionalities to
generate pseudo-random
numbers and choose random
elements, useful for
simulations, games, testing,
and more.

▪ It allows for random selection


from sequences, generation of
random numbers within a
range, and shuffling data.

17
Python Random Functions
Summary of some random methods:
Function Description
random() Returns a random float in the open interval [0.0, 1.0].
uniform(a, b) Returns a random float between a and b.
randint(a, b) Returns a random integer between a and b inclusive.
randrange(start, stop[, Returns a randomly selected element from
step]) range(start, stop, step).
Returns a new list containing k unique elements from
sample(population, k)
population.
seed(a=None, version=2) Initializes the random number generator with a seed.

Note these tables are not exhaustive, random have many more methods!
More functions: https://docs.python.org/3/library/random.html

18
Mutable vs Immutable
▪ Mutable Objects:
▪ Objects whose state can be modified
after creation such as lists, dictionaries,
sets.

▪ Immutable Objects:
▪ Objects whose state cannot be changed
once created such as integers, strings,
tuples

19
Python Data Structures
Data Structure Nature Mutability Operations Use Cases
Appending,
Ordered, versatile Elements can be Ideal for dynamic collections in
Lists [] removing, slicing,
collections changed programs
sorting

Unordered Values can be


Fast data retrieval
Dictionaries {} collections of key- changed; keys are Suitable for database-like storage
using keys
value pairs unique

Efficient for
Ordered collections, Immutable (cannot Perfect for data that should not
Tuples () immutable data
similar to lists be changed) be altered
handling

Membership
Unordered
Mutable but no testing, removing Useful for mathematical and set-
Sets {} collections of
duplicates duplicates, set based operations
unique elements
operations

20
Lists
▪ Lists are ordered, mutable collections of objects of any type
▪ List operations:
▪ append(): Add items to the end (acts like push)
▪ insert(): Insert an item at a specific index
▪ pop(): Remove and return item at index
▪ remove(): Remove the first occurrence of a value

21
Lists

22
Dictionaries
▪ Dictionaries are unordered, mutable, collections of key-value pairs.
▪ Keys must be unique and can only appear once in a dictionary
▪ Keys must also be immutable objects

23
Dictionaries

24
Tuples
▪ Tuples are ordered, immutable collections of objects
▪ Operations:
▪ Indexing: Access elements via index
▪ Slicing: Create sub-tuples
▪ Note: Tuples can also contain one item

25
Tuples

26
Sets
▪ Sets are unordered, mutable collections of unique elements
▪ Operations:
▪ add(): Add an element
▪ remove() and discard(): Remove an element, discard() without raising an error.
▪ Set operations such as union(), intersection(), difference(), and symmetric_difference().

27
Sets

28
Sets

29
Arrays
▪ Arrays are data structures similar to lists, used
for storing multiple items of the same type.
▪ The Python array module offers a more
efficient form of a list for numeric data.
▪ Arrays vs. Lists : Arrays store elements of the
same type, leading to more efficient memory
use.
▪ Lists can store elements of different types but
are generally slower and use more memory.
▪ NumPy Arrays: NumPy arrays (must be same
type) are the foundation in scientific computing
within Python (To be covered in Module 2)

30
Booleans
▪ The Boolean data type has a value
of either True or False, or 1 or 0
▪ Performing a comparison in Python
returns a Boolean. For instance,
performing the comparison 1 < 2
returns a Boolean output of True
▪ A number is False if zero and True
otherwise
▪ Other objects are False if empty, and
True otherwise

31
Strings
▪ A string is an ordered, immutable
sequence of letters, words, and other
characters
▪ Used to store text information
▪ Syntax:
▪ my_name = “My name is John!” (double
quote)
▪ my_name = ‘My name is John!’ (single
quote)
▪ my_name = ‘‘‘My name
Is John’’’ (triple quote)

32
String Formatting
▪ String formatting allows you to inject
or insert items into a string. There are
three ways to perform string
formatting:
1. Basic concatenation
2. F-string (use curly braces {})
3. Use the string formatting operator “%”
4. .format() method

33
Built-In String Methods
▪ Strings have various built-in methods which can be invoked with the following
syntax:
▪ object.method(parameters)

▪ Some examples:

34
Built-In String Methods
Method Description Example Usage
capitalize() Capitalizes the first letter of the string s = 'hello'.capitalize() -> 'Hello'

upper() Converts all characters to uppercase s = 'hello'.upper() -> 'HELLO'

lower() Converts all characters to lowercase s = 'Hello'.lower() -> 'hello'

strip() Removes leading and trailing whitespaces s = ' hello '.strip() -> 'hello'

split() Splits the string into a list of substrings s = 'a,b,c'.split(',') -> ['a', 'b', 'c']

replace() Replaces a specified substring with another s = 'hello'.replace('e', 'a') -> 'hallo'
Returns the index of the first occurrence of
find() s = 'hello'.find('e') -> 1
a substring
Checks if all characters in the string are
isdigit() s = '123'.isdigit() -> True
digits
Joins elements of an iterable with the string
join() s = ','.join(['a', 'b', 'c']) -> 'a,b,c'
as separator

s = 'Name: {}, Age: {}'.format('Alice', 30) ->


format() Formats the string using placeholders
'Name: Alice, Age: 30'

35
Indexing and Slicing
▪ We can use indexing and slicing to extract a specific element or range of elements in a
data structure
▪ We can perform indexing and slicing on several data structures including lists, strings,
tuples, and dictionaries
▪ Indexing syntax:
▪ data_structure[index]
▪ Note indexing starts at 0

▪ Slicing syntax:
▪ data_structure[start:stop:step]
▪ Note the following default values are used if not specified:
▪ start=0, stop=len(data_structure), step=1

36
Indexing Examples

37
Slicing Examples

38
Negative Indexing and Slicing
▪ We can use negative numbers to revere the order of our indexing and slicing, for
example:

39
Python Comments
▪ Single-line Comments:
• Begin with #.
• Used for short explanations.

▪ Multi-line Comments:
• Use triple double-quotes """ or triple single-quotes '''.
• Ideal for lengthy descriptions.
• Not official syntax but widely used.

▪ Usage:
• Enhance code readability.
• Explain complex logic.
• Temporarily disable code during debugging.

40

You might also like