Week – 5
Python: Data Types, Functions,
Modules, Packages
Dr. Emel Küpçü
Department of Computer Engineering
İstanbul Bilgi University
Python
• It is a high-level, general-purpose programming language known for its
simplicity and versatility.
• It was created by Guido Van Rossum in 1991.
• It emphasizes readability and ease of use, making it an excellent choice for
both beginners and professionals.
• References:
• Introduction to Computation and Programming Using Python: With Application to
Understanding Data Second Edition
• https://ia802307.us.archive.org/13/items/gate-2020-computer-science-and-technology-by-
disha-
experts/Introduction%20to%20Computation%20and%20Programming%20Using%20Python.pdf
• W3Schools Python Tutorial
• https://www.w3schools.com/python/default.asp
• Official Python Documentation
• Python.org
Top Companies
• Google: Python is one of Google's core languages, used in various
services like YouTube, which is largely written in Python.
• Netflix: They utilize Python for automating server operations, as
well as analyzing data to improve user recommendations and
performance.
• Facebook and Instagram: Both platforms use Python extensively,
with Instagram relying on the Django framework to scale its
platform.
• Spotify: Python powers data analytics and backend services to
provide personalized playlists and recommendations.
• JP Morgan and Goldman Sachs: In the finance sector, these
companies use Python for algorithmic trading, risk management,
and data analysis.
General Uses of Python
• Web Development
• Frameworks like Django and Flask make it easy to develop robust web applications.
• Data Science & Machine Learning
• Libraries such as Pandas, NumPy, and TensorFlow help in data manipulation and model
building.
• Automation/Scripting
• Python can automate repetitive tasks with simple scripts.
• Game Development
• Tools like Pygame allow for building small games.
• Cybersecurity
• Python is widely used for writing security tools and performing penetration testing.
• Desktop Applications
• GUI libraries such as Tkinter enable the creation of standalone apps.
Key benefits and Features of Python
• It has a simple syntax that resembles English, making it easier to write
and read code.
• It has many ready-made libraries and frameworks, so you don't need
to write everything from scratch.
• Python code can run on Windows, macOS, Linux, and other platforms
without modification.
• It supports multiple programming paradigms like object-
oriented, functional, and procedural programming.
• It has one of the biggest communities, offering lots of help, tutorials, and
libraries for all kinds of projects.
• It is used for both small projects (scripts) and large-scale
applications, including machine learning and web services.
Python Code Execution
• Python's traditional runtime execution model:
• Source code you type is translated to byte code,
• It is then run by the Python Virtual Machine.
• Your code is automatically compiled, then it is interpreted.
• Source code extension is .py
• Byte code extension is .pyc (compiled python code)
Reference: https://www.slideshare.net/slideshow/python-seminar-ppt/60414401
Basic Syntax
• Python uses indentation to define the scope of loops, functions, and conditionals. Consistent use of spaces or
tabs is essential
• The header line for compound statements, such as if, while, def, and class should be terminated with a colon (:)
• Comments:
• Single line comments begin with a # symbol
• # This is a comment.
• Multiple line comments: use ''' '''
• '''
This is a multiline comment.
You can add more lines in to this part.
'''
• They are ignored by the interpreter.
• Printing to the Screen: print ("Hello, Python!")
• Reading Keyboard Input: name = input ("Enter your name: ")
• Python accepts single ('), double (") and triple (''' or "''' quotes to denote string literals
• Name1 = "sample string”
• Name2 = 'another sample string'
• Name3 = """a multiline
string example"""
Variables
• You don't need to declare the type of a variable explicitly when creating it. The
type is inferred at runtime based on the value assigned to the variable,
• Variables are assigned values using the = operator.
• Examples:
x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_valid = True # Boolean
• Variables can change type, simply by assigning them a new value of a different type
• Example:
x=1
x= "string value"
• Python allows you to assign a single value to several variables simultaneously
• Example: a = b = c = 1
• You can also assign multiple objects to multiple variables
• Example: a, b, c = 1, 2, "john"
Identifiers
A variable name is called an identifier, and It must follow some rules:
• Variables can have letters (A-Z and a-z), digits (0-9) and underscores.
• It cannot begin with an underscore (_) or a digit.
• It cannot have whitespace and signs like + and -, !, @, $, #,%.
• It cannot be a reserved keyword for Python.
Data Types
Data Type Description Example
int Whole numbers x = 10
Primitive Data Types
float Decimal numbers pi = 3.14
str Text or sequence of characters name = "Alice"
bool Logical values: True or False is_valid = True
NoneType Represents absence of value value = None
Collection Data Types
list Ordered, mutable sequence numbers = [1, 2, 3]
tuple Ordered, immutable sequence point = (1, 2)
dict Key-value pairs user = {"age": 30}
an unordered collection of unique
set elements my_set = {1, 2, 3, 4}
Data Types - List
• A mutable (changeable), ordered collection of elements.
• Allows duplication of elements and can store any data type (e.g.,
integers, strings, objects).
• It can be written as a list of comma-separated values (items)
between square brackets.
• Items in a list need not be of the same type.
• Example:
my_list = [1, 2, 3, 4]
list1 = ['physics', 'chemistry', 1997, 2000]
Common List Functions and Methods
• Example:
my_list = [1, 2, 3, 4]
my_list.append(5) # Add 5 to the end
print("Elements of the list are: ", my_list)
print("The maximum is: ", max(my_list))
Output:
Elements of the list are: [1, 2, 3, 4, 5]
The maximum is: 5
Referrence:https://www.slideshare.net/slideshow/python-final-ppt/79051994#69
Data Types - Tuple
• An immutable (unchangeable) ordered collection of elements.
• Also allows duplicates and can contain mixed data types.
• Useful when you want to store fixed data that shouldn't be modified.
• You can update an existing tuple by (re)assigning a variable to another tuple.
• Tuples are faster than lists and protect your data against accidental changes to these data
• The rules for tuple indices are the same as for lists and they have the same operations, functions as well
• A tuple contains items separated by commas and enclosed in parentheses instead of square brackets.
• A tuple with only one element needs a trailing comma (,) to differentiate it from a parenthesized expression.
• Without the comma, Python will treat it as just the integer surrounded by parentheses.
• Example: t = (3,) # A tuple with one element
• Example: Output:
my_tuple = (1, 2, "hello") 2
print(my_tuple[1]) (1, 2, 'hello', 4, 5)
my_tuple = my_tuple + (4, 5) # update by reassigning
print(my_tuple)
my_tuple[0] = 10 This will raise an error (immutable)
Data Types - Dictionary (dict)
• A key-value pair collection where keys are unique.
• Values can be any data type and keys must be immutable (e.g., strings, numbers, or
tuples).
• Useful when you need to map data
• A dictionary is enclosed by curly braces ({}), each key is separated from its value by a
colon (:) and the items are separated by commas (,)
• Dictionary's values can be assigned and accessed using square brackets ([]) with a key
to obtain its value
• Retrieving the value : dictionary_name[key]
Key Value Key Value
• Example:
• my_dict = {"name": "Alice", "age": 25} Output:
print(my_dict["name"]) Alice
my_dict["age"] = 26 # Modify the value {'name': 'Alice', 'age': 26}
print(my_dict) {'name': 'Alice', 'age': 26, 'ID': 2736}
my_dict["ID"] = 2736
print(my_dict)
Common Dictionary Functions and Methods
• len(dict) : gives the total number of (key, value) pairs in the dictionary
Referrence:https://www.slideshare.net/slideshow/python-final-ppt/79051994#69
Example - Dictionary
• # Define a dictionary to store student grades
grades = {
"Math": 85,
"Science": 90,
"English": 78,
"History": 88
}
# Calculate the total of the grades
total = sum(grades.values())
# Count the number of subjects using keys() Common Dictionary Methods
count = len(grades.keys()) and functions
# Calculate the average
average = total / count
Output:
# Display the average grade Average grade: 85.25
print("Average grade: ", average)
Data Types - Set
• A set is an unordered collection of unique elements in Python.
• The items have no index, and their order may change.
• Duplicate elements are not allowed; each element must be distinct.
• You can add or remove elements after the set is created.
• Sets can contain different data types (e.g., integers, strings).
• Sets are defined using curly braces {} or the set() constructor
• Example:
• x_set = {1, 2, 3}
• y_set = set([1, 2, 3])
• z_set = {3.14, "apple", "banana"}
Common Set Functions
Example - Set
• my_set = {1, 2, 3}# Using curly braces
another_set = set([ 2, 3, 3, 5])# Duplicate values will be ignored
print(my_set)
print(another_set)
my_set.add(4)
my_set.remove(2)
union_set = my_set.union(another_set)
intersection_set = my_set.intersection(another_set)
Output:
print(union_set) {1, 2, 3}
print(intersection_set) {2, 3, 5}
{1, 2, 3, 4, 5}
{3}
Type Checking
• Type checking is the process of verifying the type of a variable or object in
your code.
• In Python, you can use two main functions for this:
• type(): This function returns the type of an object.
• Usage: type(object)
• Example:
x=5 Output:
print(type(x)) <class 'int'>
y = "Hello" <class 'str'>
print(type(y))
• isinstance(): This function checks if an object is an instance of a specific class or a
subclass.
• Usage: isinstance(object, classinfo)
• Example:
Output:
x=5
print(isinstance(x, int)) True
print(isinstance(x, str)) False
y = [1, 2, 3] True
print(isinstance(y, list))
Type Conversion
• Type conversion, also known as type casting, is the process of converting one data type
into another.
• There are two types of Type Conversion in Python:
• Implicit Type Conversion
• Explicit Type Conversion
• Implicit Type Conversion
• The Python interpreter automatically converts one data type to another without any user involvement.
• What happens when you mix an int and float in an expression?
x = 5.0 * 2
• Converting a float to an int will lose information, integer can be converted to floating value by adding “.0”
• In mixed-typed expressions Python will convert ints to floats.
• Explicit Type Conversion
• The data type is manually changed by the user as per their requirement.
• Example: x = 3.14 # Float Output:
y = int(x) # Convert float to integer
print(y) Truncates the decimal part 3
• With explicit type conversion, there is a risk of data loss since we are forcing an expression to be
changed in some specific data type.
Type Conversion
In Python, there are built-in functions to convert between common data
types. Some of them are :
• int(): Converts a value to an integer. If the value is a float, it truncates the decimal.
• float(): Converts a value to a float.
• str(): Converts a value to a string.
• tuple(): This function is used to convert to a tuple.
set(): This function returns the type after converting to set.
list(): This function is used to convert any data type to a list type.
• dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
Example: Type Conversion
From To Conversion
int float, str, bool float(5) -> 5.0
float int, str, bool int(3.9) -> 3
str int, float, list list("42") -> ['4', '2']
list tuple, set, str tuple([1, 2]) -> (1, 2)
tuple list, set list((1, 2)) -> [1, 2]
set list, tuple list({1, 2}) -> [1, 2]
dict str str({'a': 1}) -> "{'a': 1}"
Control Structures
• Control structures manage the flow of execution in a program.
• They decide which blocks of code run based on conditions, loops,
or specific cases.
• Types of control structures in Python:
• Conditional Statements:
• if, elif, and else
• Loops:
• for and while
• Loop Control Statements
• break and continue
Conditional Statements (if, elif, and else)
• These allow a program to make decisions based on conditions
using if, elif, and else.
• if: Runs if the condition is true.
• elif: Runs if the previous conditions are false but this one is true.
• else: Runs if none of the conditions are true.
• Example: General Format:
if expression1: statement (s)
• age = 20 elif expression2: statement (s)
if age < 18: elif expression3: statement (s)
print("You are a minor.") else:
elif age == 18: statement (s)
print("You just became an adult.")
else:
print("You are an adult.") Output: You are an adult.
Loops (for and while)
• Loops allow you to repeat a block of code multiple times.
• for – Iterate over a sequence. Output:
• General Format: Example: variable iterable 1
2
for variable in iterable: for i in range(1, 6): 3
# Code to execute for each element print(i) 4
5
• while – Repeat until a condition is false.
Example:
• General Format:
while condition: count = 0
# Code to execute repeatedly while count < 3:
print("count value is :" ,count)
# while condition is true count += 1 Output:
count value is: 0
count value is: 1
count value is: 2
Loop Control Statements (break and continue)
• These alter the normal flow of control by breaking, continuing, or exiting
loops.
• break: Exits the loop immediately.
• continue: Skips the current iteration and moves to the next one.
• Example:
for i in range(5):
if i == 3: Stop the loop when i is 3
break
Output:
elif i == 1: Skip the iteration when i is 1
0
continue 2
print(i)
Functions
• A function in Python is a block of organized, reusable code that performs a specific task.
• Functions make programs easier to manage, reuse, and debug.
• Python provides built-in functions (such as print() and len()), and you can also create your own functions.
• Python returns the value None, if no return is given.
• Represents the absence of a value.
• The statement return [expression] exits a function. A return statement with no arguments is the same as
return None
• Use the def keyword to define a function.
• The documentation string of the function or docstring can be an optional statement
• The code block within every function starts with a colon (:) and is indented.
• General format of definition: Example: Example with Return:
def greet(name): def square(num):
• def function_name(parameters): print(f"Hello, {name}!")
"function docstring" return num * num
# function statements
return value # Optional greet("Alice") result = square(4)
Output: Output:
greet("Bob") print(result)
Hello, Alice! 16
Hello, Bob!
Function Arguments
• You can call a function by using any of the following types of arguments:
• Required arguments: the arguments passed to the function in correct positional
order.
• def func( name, age ):
…
func ("Alex", 50)
• Keyword arguments: the function call identifies the arguments by the parameter
names.
• def func( name, age ):
…
func( age=50, name="Alex")
• Default arguments: the argument has a default value in the function declaration used
when the value is not provided in the function call
• def func( name, age = 35 ):
...
func( "Alex" )
Reference: https://www.slideshare.net/slideshow/python-final-ppt/79051994#2
Function with Variable-Length Arguments
• Variable-length arguments: This used when you need to process unspecified
additional arguments.
• In Python, variable-length arguments allow you to pass an arbitrary number of arguments to a
function, even if you don't know in advance how many arguments will be passed.
• An asterisk (*) is placed before the variable name in the function declaration.
• *args collects additional positional arguments into a tuple.
• Useful when a function needs to accept a varying number of positional arguments.
• Example: Output:
Output is:
• def printinfo (arg1, *vartuple ): 5
print ("Output is: ") Output is:
print (arg1) 10
for var in vartuple: 20
print (var) 30
return
# Calling the function with different numbers of arguments
printinfo( 5 )
printinfo( 10, 20, 30 )
Reference: https://www.slideshare.net/slideshow/python-final-ppt/79051994#2
Variable Scope in Functions
• Local Variables: Variables defined inside a function are local to that
function.
• Global Variables: Variables defined outside a function are global and
can be accessed inside functions.
• Example:
x = 10 # Global variable x = 10 # Global variable
def func(): def func():
x = 5 # Local variable global x
print("Inside function:", x) x = 5 # Global variable
print("Inside function:", x)
func() func()
print("Outside function:", x) print("Outside function:", x)
Output: Output:
Inside function: 5 Inside function: 5
Outside function: 10 Outside function: 5
Function Call Mechanisms in Python
• Passing Immutable Objects (integers, strings, tuples, etc.)
• If you try to modify the value, a new object is created, and the original remains unchanged.
• This behavior looks like call by value.
• def modify_number(x):
x = x + 1 # Creates a new integer object
num = 5
modify_number(num) Output:
print(num) 5
• Passing Mutable Objects (lists, dictionaries, etc.)
• If you modify the object inside the function, the change persists outside the function.
• This behavior looks like call by reference.
• def modify_list(lst):
lst.append(100) # Modifies the original list
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) Output:
[1, 2, 3, 100]
Modules
• A module is a file consisting of Python code that can define functions,
classes and variables that you can import and reuse in other
programs.
• A module allows you to organize your code by grouping related code
which makes the code easier to understand and use.
• You can use any Python source file as a module by executing an import
statement.
• Example: import my_module # imports my_module.py
Creating and Using Modules
• You can create your own module by saving a Python file with .py extension.
def add(a, b): calculator.py
#Returns the sum of two numbers.
return a + b
def subtract(a, b):
#Returns the difference between two numbers.
return a - b
PI = 3.14159 # A useful constant
import calculator # Importing the custom module main.py
# Using functions and variable from the calculator module Output:
result1 = calculator.add(10, 5) Addition: 15
result2 = calculator.subtract(10, 5) Subtraction: 5
print(f"Addition: {result1}") Value of PI: 3.14159
print(f"Subtraction: {result2}") #
print(f"Value of PI: {calculator.PI}")
Different Ways to Import Modules
• Import Entire Module:
• import math
print(math.sqrt(16)) # Output: 4.0
• Import Specific Functions or Variables:
• from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
• Import with Alias:
• import math as m
print(m.sqrt(9)) Output: 3.0
• Import Everything from a Module (Not recommended, as it may cause
conflicts):
• from math import * # Import all functions and variables from the math module
# Using math functions directly without the 'math.' prefix
print(sin(0)) # Output: 0.0
print(cos(0)) # Output: 1.0
Built-in Python Modules
• Python comes with several built-in modules. Some commonly used
example bult-in modules are:
• math: Provides mathematical functions.
• import math
print(math.factorial(5)) # Output: 120
• random: Generates random numbers.
• import random
print(random.randint(1, 10)) # Output: Random integer between 1 and 10
Using Math Library
• Besides (+, -, *, /, //, **, %, abs), we have lots of other math functions
available in a math library.
• A library is a module with some useful definitions/functions.
• To use the library, we need to make sure this line is in our program:
import math
• Importing a library makes whatever functions are defined within it available to the
program.
• To access the sqrt library routine as an example, we need to access it as
math.sqrt(x).
• Using this dot notation tells Python to use the sqrt function found in
the math library module.
Reference: https://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter03.pptx
Functions of Math Library
Python Mathematics English
pi An approximation of pi
e e An approximation of e
sqrt(x) 𝑥 The square root of x
sin(x) sin x The sine of x
cos(x) cos x The cosine of x
tan(x) tan x The tangent of x
asin(x) arcsin x The inverse of sine x
acos(x) arccos x The inverse of cosine x
atan(x) arctan x The inverse of tangent x
log(x) ln x The natural (base e) logarithm of x
log10(x) log10 𝑥 The common (base 10) logarithm of x
exp(x) 𝑒𝑥 The exponential of x
ceil(x) 𝑥 The smallest whole number >= x
floor(x) 𝑥 The largest whole number <= x
Reference: https://mcsp.wartburg.edu/zelle/python/ppics3/slides/Chapter03.pptx
Packages
• A package is a collection of modules organized into directories.
• Think of a package as a folder containing multiple modules (Python
files), similar to how files are organized into folders on your computer.
• A package in Python is a way to organize related
modules into directories (folders) for better code management and
reusability.
• Each package requires a special __init__.py file (can be empty),
which tells Python that the directory should be treated as a package.
• Create a directory and give it your package's name.
• Put your functions, classes in it.
• Create a __init__.py file in the directory
Creating and Using a Simple Package
main.py
# Importing specific functions from the package
def add(a, b): arithmetic.py from my_package.arithmetic import add, subtract
"""Returns the sum of two numbers.""" from my_package.geometry import *
return a + b
# Using the imported functions
def subtract(a, b): result1 = add(5, 3)
"""Returns the difference between two numbers.""" result2 = subtract(10, 4)
return a - b
circle_area = area_circle(7)
pi_val=PI
PI = 3.14159 print("Addition:", result1)
def area_circle(radius): print("Subtraction:", result2)
"""Returns the area of a circle.""" print("Circle Area:", circle_area)
return PI * radius * radius print("Circle Area:", PI)
Output:
def perimeter_circle(radius): Addition: 8
"""Returns the perimeter of a circle.""" Subtraction: 6
return 2 * PI * radius geometry.py Circle Area: 153.93791
Circle Area: 3.14159
Installing Third-Party Packages
• You can install external modules from the Python Package Index (PyPI) using pip.
• Examples:
• pandas: Provides data manipulation tools.
• requests: Used to send HTTP requests.
• numpy: Used for numerical computations.
• Example: Installing and using the numpy library, which is widely used for numerical
computations in Python.
• Open Your Terminal or Command Prompt.
• Use the Following Command:
• pip install numpy
• You can check if the installation was successful by starting a Python interpreter and trying to import
the module:
• import numpy
print(numpy.__version__)
Example Usage of the numpy
• import numpy as np
array = np.array((1, 2, 3, 4, 5)) # Create a numpy array
# Perform basic operations
mean_value = np.mean(array) # Calculate the mean
sum_value = np.sum(array) # Calculate the sum
squared_array = np.square(array) # Square each element
print("Array:", array) Output:
print("Mean:", mean_value) Array: [1 2 3 4 5]
Mean: 3.0
print("Sum:", sum_value) Sum: 15
print("Squared:", squared_array) Squared: [ 1 4 9 16 25]
Managing Dependencies
• pip install : installs packages.
• pip freeze : lists installed packages and their versions.
• pip uninstall package_name : removes a package.
Questions ?