Python
Python
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?
# 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:
● 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
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
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).
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.
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
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
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.
● Lists can be created using square brackets [] and separating items with
commas.
● The list() constructor can also be used to create lists.
nums = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# Extracting a sublist from index 2 to index 4
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]
● Curly braces { }
● 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.
● 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.
● 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}
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
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
● 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.
● 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
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
original_dict['key1'].append('value3')
print(deep_copied_dict) # Output?
Dictionary
Methods
Advantage of Dictionaries
Key Errors:- Accessing a key that doesn't exist raises a KeyError dict[key].
So be sure to use dict.get(key, default).
– Unknown