0% found this document useful (0 votes)
15 views130 pages

Python

Uploaded by

aquahizhee
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)
15 views130 pages

Python

Uploaded by

aquahizhee
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
You are on page 1/ 130

Python Track

Basics, Conditionals,
Loops & Functions
Python Basics
Introducing Python
● High-level, interpreted programming language
● Emphasizes readability and simplicity
● Dynamically typed, no variable declaration
● Large community and library support
Why Python?
Python - Why?

● It is easier to implement complex algorithms and data structures.


● To make sure everyone has equal understanding of programming.
● We use Python for lectures.
Syntax
● No semicolons required.
● White Spaces matter.
● Similar to the English language.
// Java
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

# Python
print('Hello, world!')
Syntax - Indentation
● In Python, unlike other programming languages, indentation serves a crucial
purpose beyond just readability.
● Python uses indentation as a way to indicate and define blocks of code.
Variables
● Variables are used to store and manipulate data.
● Python has no command for declaring a variable.
● They are created by assigning a value to a name.
● Python has dynamic typing.
x = 4 # x is of type int
x = "A2SV" # x is now of type str
Variables - Names
● Must start with a letter or the underscore character
● Can not start with a number
● Can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
● Case-sensitive (age, Age and AGE are three different variables)
● Can not be a keyword (if, while, and, for, …)
● snake_case
Data Types in Python
● Data types define the kind of data that can be stored and manipulated in a
program.
● Common Built-in Data Types:
○ Boolean (bool)
○ Integer (int)
○ Float(float)
○ String (str)
○ None
Boolean
● In programming you often need to know if an expression is True or False.
● You can evaluate any expression in Python, and get one of two answers, True
or False.
● When you compare two values, the expression is evaluated and Python
returns the Boolean answer:
10 > 9 # True
10 == 9 # False
10 < 9 # False
Boolean- Evaluation
● The bool() function allows you to evaluate any value, and give you True or
False in return,
● In Python values with content are True:
○ Any string is True , except empty strings.
○ Any number is True , except 0.
○ Any list, tuple, set, and dictionary are True , except empty ones.
Numeric data types
● Integer:
○ Represent integer numbers without any decimal points
○ Can be positive or negative numbers, or zero.
○ Examples of integers are: x = -5, x = 0, x = 10, x = 100
Numeric data types
● Float:
○ Represent decimal numbers or numbers with a fractional part
○ They are written with a decimal point, even if the fractional part is zero
○ Examples of floating-point numbers are: x =-2.5, x = 3.14, x = 1.0
None Type
● Represents the absence of value
● Equivalent to "null" in other languages
● Immutable and has a single instance
Operators
● Operators are used to perform operations on variables and values.
● In the example below, we use the + operator to add together two values

print(10 + 5)
Operators
● Python divides the operators in the following groups:

○ Arithmetic operators ○ Logical operators


○ Assignment operators ○ Identity operators
○ Comparison operators ○ Membership operators
Operators- Arithmetic

● Arithmetic operators are used with numeric values to perform common


mathematical operations.
Operators- Arithmetic
Operators- Precedence
Operators- Comparison

● Comparison Operators are used to compare two values.


Operators- Comparison
Operators- Logical

● Logical operators are used to combine conditional statements.


Operators- Logical
Operators- Identity

● Identity Operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location.
Operators- Identity
Operators- Membership

● Membership Operators are used to test if a sequence is presented in an


object.
Operators- Membership
Strings
● Strings in python are surrounded by either single quotation marks, or double
quotation marks.
● String in python are immutable.
● You can assign a multiline string to a variable by using three quotes:
Word = “Lorem”
Single_qoute_word = ‘ipsum’
multi_line_sentence = """Lorem ipsum
dolor sit amet,consectetur adipiscing
elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
Strings - Slicing Strings
● You can return a range of characters by using the slice syntax.
● Specify the start index (inclusive) and the end index (exclusive), separated by
a colon, to return a part of the string. We can also specify step as a third
parameter (optional). b = "Hello, World"
print(b[2])
print(b[-3])
print(b[2:5])
print(b[:5])
print(b[2:])
print(b[5:2:-1])
print(b[::-1])
print(b[::2]
Strings - Slicing Strings
Syntax : string[start:end:step]
b = "Hello, World"
print(b[2]) # character: l
print(b[-3]) # character: r
print(b[2:5]) # slice from Index 2 to 4
print(b[:5]) # Slice from the Start
print(b[2:]) # Slice from the end
print(b[5:2:-1]) # Slice in reverse order
print(b[::-1]) # Reverse the whole string
print(b[::2]) # Slice with a step of 2
Strings - String Concatenation
● To concatenate, or combine, two strings you can use the + operator.

a = "Hello"
b = "World"
c = a + b
print(c)
Strings - Formatting
● To format strings in python we can use f-strings.

a = 1
b = "hello"
print(f"{b} {a} {a + 2}") # hello 1 3
Strings - Substring search
● In python we can use the ”in” operator to check if a string occurs as a
substring of another string

print("Hello" in "Hello world")


Variables - Casting
● Variable casting allows converting a value from one data type to another.
● Python provides built-in functions for explicit casting, such as ’str()’, ’int()’,
and ’float()’.
y = int(3.0) # y will be 3
z = float(3) # z will be 3.0
Conditionals
If statement
● We use if statement to write a single alternative decision structure.
● Here is the general format of the if statement:
if condition:
statement1
statement2
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
● The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".

a = 33
b = 33
if b > 33:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
● The else keyword catches anything which isn't caught by the preceding
conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Conditionals
● You can have if statements inside if statements, this is called nested if
statements.
● We can use logical operators to combine conditional statements.
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Loops
While Loop
● With the while loop we can execute a set of statements as long as a
condition is true.
i = 1
while i < 6:
print(i)
i += 1
For Loop
● A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
Nested Loops
● A nested loop is a loop inside a loop.
● The "inner loop" will be executed one time for each iteration of the "outer
loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The range() Function
● The range() function generates a sequence of numbers, it is commonly used
for looping a specific number of items.
Syntax:
range(start, stop, step)
● start (optional): Beginning of sequence (default is 0).
● stop: End of sequence (exclusive).
● step (optional): Increment (default is 1).
The range() Function - Examples
for x in range(6):
print(x) # Output: ?

for x in range(2, 6):


print(x) # Output: ?

for x in range(2, 10, 2):


print(x) # Output: ?

for x in range(12, 3, -3):


print(x) # Output: ?
The range() Function - Examples
for x in range(6):
print(x) # Output: 0, 1, 2, 3, 4, 5

for x in range(2, 6):


print(x) # Output: 2, 3, 4, 5

for x in range(2, 10, 2):


print(x) # Output: 2, 4, 6, 8

for x in range(12, 3, -3):


print(x) # Output: 12, 9, 6
Continue Statement
● With the continue statement we can stop the current iteration, and continue
with the next.
i = 0 for i in range(9):
while i < 9: if i == 3:
i += 1 continue
if i == 3: print(i)
continue
print(i)
Break Statement
● With the break statement we can stop the loop even if the while condition is
true:
for i in range(9): i = 1

if i > 3: while i < 9:

break print(i)

print(i) if i == 3:
break
i += 1
For - Else
● With the else statement we can check if the loop finishes it’s iteration or not.

fruits = ["apple", "banana", "mango", "orange"]

for fruit in fruits:


if fruit == "pineapple":
print("Found pineapple!")
break
else:
print("Pineapple not found in the list.")
Functions
Functions
● A function is a reusable block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● A function can return data as a result.

def my_function():
print("Hello from a function")

my_function()
Arguments
● Information can be passed into functions as arguments.
● Arguments are specified after the function name, inside the parentheses.
● You can add as many arguments as you want, just separate them with a
comma.
def my_function(fname):
fname[0] = “anna”
print(fname[0] + " Refsnes")

data = ["Emil"]
my_function(data)
print(data[0])
Return Values
● To let a function return a value, use the return statement:
● If we don’t specify the return value, it will automatically return None.

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Lambda
● A lambda function is a small anonymous function.
● A lambda function can take any number of arguments, but can only have one
expression.
● Syntax:
lambda arguments : expression

x = lambda a : a + 10
print(x(5))

x = lambda a, b : a * b
print(x(5, 6))
Common Pitfalls
1. Infinite Loops

Forgetting to Increment Misusing continue

x = 0 x = 0
while x < 5: while x < 5:
print(x) if x == 2:
continue
print(x)
x += 1
Common Pitfalls
2. Incorrect Variable Increment in for Loops

i = 0
arr = [1, 2, 3, 4]
while i < len(arr):
for i in range(len(arr)):
print(arr[i])
i += 2
i += 2

# This does not change the


# Use a while loop if you
actual loop variable
need manual incrementing.
Common Pitfalls
3. Incorrect break in Nested Loops

for i in range(3):
for j in range(3):
if j == 1:
break Fix: Use flags or
print(i + j) return if inside a function.

# This only breaks the inner


loop, not the outer one
Lists
What are lists?

● Lists are fundamental data structures in Python used to store collections


of data.
● They can hold items of any data type, including numbers, strings, and
even other lists.
● Lists are ordered, changeable, and allow duplicate values.
Creating lists

● Lists can be created using square brackets [] and separating items with
commas.
● The list() constructor can also be used to create lists.

# Creating a list using square brackets


fruits = ["apple", "banana", "cherry"]

# Convert iterables to list using the list() constructor


numbers = list((1, 2, 3, 4, 5))
List data types
List items can be of any data type
● list1 = ["apple", "banana", "cherry"]
● list2 = [1, 5, 7, 9, 3]
● list3 = [True, False, False]
● list4 = ["abc", 34, True, 40.5, "male"]
Accessing List Items
● List items are accessed using their index number, starting from 0.
● Negative indexing can be used to access items from the end of the list.
nums = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# Accessing the first item
nums[0]
# Accessing the last item
nums[-1]
Slicing Lists
● Slicing allows extracting a sublist from a list.
● Slicing uses the colon : to separate start (inclusive) and end indices (exclusive).

nums = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# Extracting a sublist from index 2 to index 4

nums[2:5] # [12, 13, 14]

nums[-4 : -1] ??
Modifying Lists
● Lists are mutable, allowing you to change their contents.
● You can modify items using their index or extend the list using append()
and insert().
● You can also remove items using remove() and pop().
Examples
fruits = ["apple", "banana", "cherry"]
# Changing the first item
fruits[0] = "orange" # fruits = ["orange", "banana", "cherry"]
# Adding an item to the end
fruits.append("mango") # fruits = ["orange", "banana", "cherry", "mango"]
# Removing an item by value
fruits.remove("cherry") # fruits = ["orange", "banana", "mango"]
# Removing the last item
removed_item = fruits.pop() # removed_item = "mango", fruits =
["orange", "banana"]
Common List Operations
● Checking if an item exists: in keyword
● Sorting a list: sort() method
● sorted ( nums , key = myFunction ( ), reverse = True/False)
● Reversing a list: reverse() method
Examples
fruits = ["orange", "banana"]
# Checking if "orange" exists in the list
if "orange" in fruits:
print("Yes, orange is in the list")
# Sorting the list in ascending order
fruits.sort() # fruits = ["banana", "orange"]
# Reversing the sorted list
fruits.reverse() # fruits = ["orange", "banana"]
Combining Lists
● Concatenating lists using the + operator or extend() method
● Adding items from one list to another individually
Examples
numbers = [1, 2, 3]

fruits = ["orange", "banana"]


# Concatenating lists using '+' operator

new_list = fruits + numbers # new_list = ["orange", "banana", 1, 2, 3]

# Extending a list using extend() method

fruits.extend(numbers) # fruits = ["orange", "banana", 1, 2, 3]


Traversing Lists
● Iterating through lists using for loops
● Accessing both index and value using enumerate() function
● for index in range(len(nums)):
print(nums[index])

● for num in nums:


print(num)

● for index, num in enumerate(nums):


print(index, num)
List Comprehension
Let’s try to find even_numbers from the given array number.
numbers = [1, 2, 3, 4, 5]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
List Comprehension
● Creating new lists based on existing lists
● Using expressions and conditions to filter and transform list elements

# Creating a list of even numbers from a list of numbers


numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
# even_numbers = [2, 4]
Why List Comprehension?
my_list = [[0]] * 5
my_list = ? #[[0], [0], [0], [0], [0]]
my_list[0][0] = 1
my_list = ?
Why List Comprehension?
my_list = [[0]] * 5
my_list[0][0] = 1
my_list = [[1], [1], [1], [1], [1]] # Why?
Why List Comprehension?
● Creates 5 references to the same inner list [0].
● Changing one inner list modifies all, as they share the same memory
location.
Why List Comprehension?
my_list = [[0] for _ in range(5)]
my_list[0][0] = 1
# Result: [[1], [0], [0], [0], [0]]
● Creates a new, independent list for each iteration.
● Each inner list is stored in a unique memory location.
Other List Methods
Tuples
What are Tuples?

● A tuple is a collection which is ordered, allows duplicates and is


unchangeable. Tuples are also known as Immutable Lists.

● Tuples are written with round brackets.


○ fruits = ("apple", "banana", "cherry")
○ fruit = ("apple")
Creating Tuples
● Tuples are written with round brackets ().
● This is called ‘packing’ a tuple.
fruits = ("apple", "banana", "cherry")
fruit = ("apple",) # or just () to create an empty one
● The tuple() constructor:
fruits = tuple(["apple", "banana", "cherry"])
numbers = tuple()
Unpacking tuples
● In Python, we are also allowed to extract the values back into variables.
This is called "unpacking".
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
fruits = ("apple", "banana", "cherry", “oranges”, “pineapples”)
green, yellow, *red = fruits
Unpacking tuples
● In Python, we are also allowed to extract the values back into variables. This is
called "unpacking".
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
fruits = ("apple", "banana", "cherry", “oranges”, “pineapples”)
(green, yellow, *red) = fruits #red = [“cherry”,“oranges”, “pineapples”]
Tuples
● Is it possible to
○ add an element to a Tuple? How?
○ delete an element?
○ join two tuples?
Tuple Similarities with List

● Similar data types


● Slicing and Indexing
● Similar Iteration

Q: Is it possible to have “Tuple Comprehension” ?


Tuple Methods
Why Do We Need Tuples When We Have
Lists?
Why Tuples?
● Tuples are immutable, ensuring data cannot be changed.
● Tuples are faster than lists due to their fixed size.
● Tuples consume less memory than lists.
● Tuples are hashable and can be used as dictionary keys or set
elements.
Sets
What Is Set?
Set

● A set is a built-in data type in Python that represents an unordered,


unindexed collection of unique and immutable elements.
Initialization
● set() constructor
empty_set = set() #empty set
numbers_set = set([1, 2, 3, 4, 5]) #
Converts any iterable to a set

● Curly braces { }

numbers_set = {1, 2, 3, 4, 5} # Creates a set with


elements
empty_set = {} # Valid ?
What Data Type Can Set Store?
● It can store elements of various data types, as long as those elements
are immutable.
● Integers, Floats, Strings,Tuples and Booleans.

my_set = {1, 2.5, “apple”, (1, 2, 3), True}

invalid_set = {1, 2, [3, 4]} # Why invalid?


Basics of how Set works

● Sets in Python use a hash table to store elements which is like a big storage
box with lots of compartments (buckets).
● When you add an element to the set, a special function (hash function) turns
the element into a unique code that determines which bucket the element
goes into.
● When you want to check if an element is in the set (lookup), the hash
function is used again to find the compartment where that element should
be.
Why Immutable?
● Hashing: Sets rely on hashing for efficient membership testing and
duplicate removal. Immutable objects have a fixed hash value, ensuring
consistent behavior.

● Error Prevention: Using mutable objects in sets can lead to unexpected


behavior and errors due to changing hash values.
Access Elements
● You cannot access items in a set by referring to an index or a key.
● To check if an item is in a set, you use the in operator.
my_set = {1, 2, 3, 4, 5}
if 3 in my_set:
#code

● You can iterate through all items in a set using a for-in loop
for item in my_set:
#code
Add And Remove Elements
● The add() method is used to add a single element to a set.
● The update() method is used to add multiple elements using iterables
(lists, tuples)
● The union() method Return a set containing the union of sets
my_set = set() my_set.update([3, 4, 5, 6])
my_set.add(1)
my_set.add(2) print(my_set) # {1, 2, 3, 4, 5, 6}
my_set.add(3) union_set = my_set.union({1, 4, 45, 16})
print(my_set) # {1,2,3}
# output?
Add And Remove Elements
● The clear() method Removes all the elements from the set.
● The remove() and discard() methods Remove the specified item.
● pop() Removes and Returns an arbitrary element from the set.

my_set = {1,2,3,4,5} my_set.pop() # ?


my_set.remove(2) # ? my_set.clear() # ?
my_set.remove(6) # ?
my_set.discard(2) # ?
my_set.discard(6) # ?
Add And Remove Elements
Method Error Returns a Value? Notes

remove(x) ❌ Raises KeyError ❌ No Use when you are sure the


element exists.

discard(x) ✅ No error ❌ No Safer than remove(), as it


won’t cause an error if the
element is missing.

pop() ❌ Raises KeyError if set ✅ Yes Removes and returns an


is empty arbitrary element.

my_set = {1, 2, 3, 4, 5} my_set.pop()


my_set.remove(2) # Removes 2 # Removes and returns an arbitrary
my_set.remove(6) # KeyError element from the set.
my_set.discard(2) # No error my_set.clear() # Deletes all of the
my_set.discard(6) # No error elements from the set.
What Are Valid And Invalid Operators
In Set?
Valid Operators
● Union ( | ) set1 = {1, 2, 3}
union_set = set1 | set2 set2 = {3, 4, 5}
# union_set = {1, 2, 3, 4, 5, 6}

● Intersection (&)
intersection_set = set1 & set2
# intersection_set = {3}

● Difference (-)
difference_set = set1 - set2
# difference_set = {1, 2}
Valid Operators
Symmetric Difference (^) set1 = {1, 2, 3, 4}
symmetric_difference_set = set1 ^ set2 set2 = {3, 4, 5, 6}
# {1, 2, 5, 6}

Subset (<=) and Superset (>=) set1 = {1, 2}


is_subset = set1 <= set2 # True set2 = {1, 2, 3, 4}
is_superset = set2 >= set1 # True

Equality(==)
set1 = {1, 2, 3}
set1 == set2 # True
set1 == set3 # False
set2 = {3, 2, 1}
set3 = {1, 2, 4}
Invalid Operators
● Concatenation (+)
● Multiplication (*)
● Indexing ([]) and Slicing ([:])
Set Comprehension

● A set comprehension in Python is a concise way to create a set


using curly braces {} .

Set_name = {expression for item in iterable if condition}

squares_set = {x**2 for x in range(10)}


squares_set = {x**2 for x in range(10) if x % 2}
Set
Methods
Advantage of sets

1. Uniqueness of Elements
2. Fast Membership Testing
3. Mathematical Set Operations
Frozenset
● a frozenset is an immutable and hashable version of a set.
frozen_set = frozenset([1, 2, 3])
frozen_set = frozenset([1, 2, 3])

frozen_set.add(4) # possible?
union_frozenset = frozenset1 | frozenset2 # possible?
intersection_frozenset = frozenset1 & frozenset2 # possible?
Dictionaries
What Is Dictionary?
Dictionary

● A dictionary is an ordered (as of Python version 3.7) collection of


key-value pairs, where each key must be unique and is associated with a
specific value.
● They are also mutable and dynamic data structures
Initialization
● dict() constructor
empty_dictionary = dict() #empty dictionary
dictionary_from_list = dict([('name', 'John'),('age',
30),('city','New York')])

● Curly braces { }
dictionary = {'name': 'John', 'age': 30, 'city': 'New York'}

● Dictionary comprehension
sqr_dict = {num: num**2 for num in range(1, 11)}
What data types can be used as
dictionary keys in Python?
● Dictionary keys must be immutable data types to maintain data integrity.
● Integers, Floats, Strings,Tuples and Booleans.

my_dictionary = {(1, 2): "Tuple Key", False: "Key"}


my_dictionary = {[1, 2]: "List Key"} #why invalid?
Common Operations In Dictionary
● Access
age = my_dict["age"]
age = my_dict.get("age", 0) #why safe?

● Add or Update

my_dict["age"] = 20
my_dict["age"] = my_dict.get("age",0) + 10
● Removing Key

value = my_dict.pop("age")
del my_dict[“age”]
Common Operations In Dictionary
● Checking if the key exist

if "age" in my_dict

● Iterating

● Through Keys:
for key in my_dict:
● Through key-value pairs:
for key, value in my_dict.items():
● Through values:
for value in my_dict.values():
Dictionary Copying
● Assignment Operator (=):
my_dict1 = {'key1': 'value1', 'key2': 'value2'}
my_dict2 = my_dict1
my_dict2[‘key1’] = ‘value3’
print(my_dict1) # Output?
Shallow Copy
● A shallow copy creates a new dictionary but does not create new
copies of the objects inside the dictionary.
● Changes made to mutable objects (like lists) within the original
dictionary will affect the corresponding objects in the copied
dictionary, and vice versa.
Shallow Copy

● Shallow copy is performed using methods like copy(), dict(), or


dictionary unpacking ({**original_dict}).
Shallow Copy
original_dict = {'key1': ['value1'], 'key2': 'value2'}
shallow_copied_dict = original_dict.copy()

original_dict['key1'].append('value3')
original_dict['key2'] = ‘value4’

print(shallow_copied_dict) # Output?
Deep Copy
● A deep copy creates a new dictionary and recursively creates new
copies of all objects inside the original dictionary, including nested
objects.
● Changes made to mutable objects within the original dictionary will
not affect the corresponding objects in the copied dictionary, and
vice versa.
Deep Copy

● Deep copy is performed using the deepcopy function from the


copy module.
Deep Copy
import copy

original_dict = {'key1': ['value1'], 'key2': 'value2'}


deep_copied_dict = copy.deepcopy(original_dict)

original_dict['key1'].append('value3')

print(deep_copied_dict) # Output?
Dictionary
Methods
Advantage of Dictionaries

1. Efficient Data Retrieval


2. Fast Membership Testing
3. Dynamic Size
Common Pitfalls

Key Errors:- Accessing a key that doesn't exist raises a KeyError dict[key].
So be sure to use dict.get(key, default).

Mutable Keys:- Set elements and Dictionary keys must be immutable


(e.g., lists can't be keys, but tuples can if they contain only immutable
elements).
“Life is like a Python
dictionary—sometimes things get
added, sometimes they get removed,
but it’s always a key to something
new.”

– Unknown

You might also like