You are on page 1of 17

Python Course: From Basics to Advanced

Vo Hoang Nhat Khang


February 13, 2024

1
Vo Hoang Nhat Khang (Christ) CONTENTS

Contents
1 Introduction 3

2 Installing Python on Windows and macOS for Beginners 3


2.1 For windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 For macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3 First step: Get a sense of learning basics 3


3.1 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.1.1 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.1.2 Floats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.3 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.5 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.6 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.7 NOTE: Dynamic datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1.8 Type Hinting in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.2 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3.1 Conditional Statements: if-elif-else . . . . . . . . . . . . . . . . . . . . . . . 7
3.3.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4 Here comes a little more ”Basics”... 7


4.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.1.1 User-defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.1.2 Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.1.3 Lambda Functions (Anonymous Functions) . . . . . . . . . . . . . . . . . . 8
4.1.4 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2 Lists and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2.2 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

5 Just a little more ”Basics”... 10


5.1 Object-Oriented Programming (OOP) . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.1.1 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.1.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.1.3 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.1.4 Type Hinting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2 Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2.3 Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5.2.4 Additional libraries for major domains . . . . . . . . . . . . . . . . . . . . . 14
5.3 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5.3.1 try-except Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3.2 Multiple Except Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3.3 finally Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6 Small Python Projects for Beginners 15

7 Conclusion 17

2
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS

1 Introduction
Python is a high-level, interpreted programming language known for its simplicity and readability.
It is widely used in various domains such as web development, data science, artificial intelligence,
and more. This course aims to provide a comprehensive guide to Python programming, starting
from the basics and progressing to advanced topics.

2 Installing Python on Windows and macOS for Beginners


Installing Python on both Windows and macOS is a straightforward process. Below are step-by-
step instructions on how to install Python using official methods:

2.1 For windows


1. Visit the official Python website at https://www.python.org/.
2. Navigate to the Downloads section and click on the latest version of Python for Windows.

3. Scroll down to the Files section and choose either the Windows x86-64 executable installer
for 64-bit systems or the Windows x86 executable installer for 32-bit systems.
4. Once the installer file is downloaded, double-click on it to launch the installer.
5. Check the box that says ”Add Python version to PATH” during installation to ensure Python
is added to your system PATH, making it easier to run Python from the command line.
6. Follow the prompts in the installer to complete the installation.
7. After installation, open Command Prompt and type python --version to verify that Python
has been installed correctly.

2.2 For macOS


1. Visit the official Python website at https://www.python.org/.
2. Navigate to the Downloads section and click on the latest version of Python for macOS.

3. Scroll down to the Files section and choose the macOS 64-bit installer.
4. Once the installer file is downloaded, double-click on it to launch the installer.
5. Follow the prompts in the installer to complete the installation.

6. After installation, open Terminal and type python3 --version to verify that Python has
been installed correctly.

3 First step: Get a sense of learning basics


3.1 Variables and Data Types
In Python, variables are used to store data. Python supports various data types, including integers,
floats, strings, lists, tuples, dictionaries, etc.

3.1.1 Integers
Integers are whole numbers without any decimal point. They can be positive or negative.
1 # Example of integer variables
2 x = 10
3 y = -5

3
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS

3.1.2 Floats
Floats, or floating-point numbers, are numbers with a decimal point or numbers written in expo-
nential notation.
1 # Example of float variables
2 pi = 3.14159
3 radius = 2.5

3.1.3 Strings
Strings are sequences of characters enclosed within single or double quotes.
1 # Example of string variables
2 name = " Alice "
3 message = ’ Hello , World ! ’

3.1.4 Lists
Lists are ordered collections of items. They are mutable, meaning their elements can be changed
after creation.
1 # Example of list variables
2

3 my_list = [1 , 2 , 3 , 4]
4 names = [ ’ Alice ’ , ’ Bob ’ , ’ Charlie ’]

3.1.5 Tuples
Tuples are similar to lists, but they are immutable, meaning their elements cannot be changed
after creation.
1 # Example of tuple variables
2 my_tuple = (5 , 6 , 7 , 8)
3 coordinates = (10.0 , 20.0)

In Python, tuples don’t necessarily need to have brackets. They can be defined simply by
separating the elements with commas:
1 # Example of tuple without brackets
2 another_tuple = 1 , 2 , 3
3 print ( another_tuple ) # Output : (1 , 2 , 3)
And yes, you can even have single-element tuples by including a trailing comma after the single
element:
1 # Example of single - element tuple
2 s i n g l e _ element_tuple = 1 ,
3 print ( s ingle_element_tuple ) # Output : (1 ,)

3.1.6 Dictionaries
Dictionaries are collections of key-value pairs. They are unordered and mutable.
1 # Example of dictionary variables
2 my_dict = { ’a ’: 1 , ’b ’: 2 , ’c ’: 3}
3 person = { ’ name ’: ’ Alice ’ , ’ age ’: 30 , ’ city ’: ’ New York ’}

3.1.7 NOTE: Dynamic datatypes


Variables in Python can dynamically change their type based on the assigned value. For example,
a variable initially assigned an integer value can later be assigned a string value.

4
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS

1 # Dynamic typing in Python


2 x = 10
3 print ( x ) # Output : 10
4

5 x = " Hello "


6 print ( x ) # Output : Hello

3.1.8 Type Hinting in Python


Type hinting is a feature in Python that allows you to annotate variables, function parameters, and
return types with their expected types. While Python is dynamically typed, meaning you don’t
need to specify the data type of variables explicitly, type hinting provides a way to indicate the
expected types for better code clarity and to catch type-related errors early during development.
Type hints are optional and are primarily used by static type checkers like Mypy or Pyright
to analyze your code for type inconsistencies. However, they can also be used by IDEs to provide
better code completion and to assist with refactoring.
Here’s an example of how to use type hints in Python:
1 def greet ( name : str ) -> str :
2 return f " Hello , { name }! "
3

4 greeting = greet ( " Alice " )


5 print ( greeting ) # Output : Hello , Alice !
In this example, we’ve annotated the parameter name of the greet function with the type str,
indicating that it expects a string argument. Similarly, we’ve annotated the return type of the
greet function as str, indicating that it returns a string.
Type hints support various types including built-in types like int, float, str, as well as user-
defined types and generics. You can also specify optional types using Union or use Any to indicate
that a variable can be of any type.
1 from typing import List , Tuple , Union
2

3 # Function with multiple parameters and return type


4 def add ( x : int , y : int ) -> int :
5 return x + y
6

7 result = add (3 , 5)
8 print ( result ) # Output : 8
9

10 # Function with a list parameter and return type


11 def double_list ( lst : List [ int ]) -> List [ int ]:
12 return [ x * 2 for x in lst ]
13

14 result = double_list ([1 , 2 , 3 , 4])


15 print ( result ) # Output : [2 , 4 , 6 , 8]
16

17 # Function with multiple return types


18 def parse_value ( value : str ) -> Union [ int , float ]:
19 if ’. ’ in value :
20 return float ( value )
21 else :
22 return int ( value )
23

24 result1 = parse_value ( " 10 " )


25 print ( result1 ) # Output : 10 ( int )
26

27 result2 = parse_value ( " 3.14 " )


28 print ( result2 ) # Output : 3.14 ( float )
29

30 # Function with tuple return type


31 def divide ( x : int , y : int ) -> Tuple [ int , float ]:
32 quotient = x // y

5
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS

33 remainder = x % y
34 return quotient , remainder
35

36 result = divide (10 , 3)


37 print ( result ) # Output : (3 , 1)

3.2 Operators
Python supports various operators for performing operations on variables and values.

3.2.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations such as addition, subtraction,
multiplication, and division.
1 # Example of arithmetic operators
2 a = 10
3 b = 5
4 sum = a + b
5 difference = a - b
6 product = a * b
7 quotient = a / b

3.2.2 Operator Precedence


Operator precedence determines the order in which operations are performed in an expression.
Operators with higher precedence are evaluated first. Additionally, Python follows the relational
precedence rules, which dictate the order of evaluation for relational operators such as <, <=, >, >=,
==, and !=. These operators have lower precedence compared to arithmetic operators, and they
are evaluated left to right.

Operator Description
** Exponentiation
*, /, //, % Multiplication, Division, Floor Division, Modulus
+, - Addition, Subtraction
<, <=, >, >=, ==, != Relational Operators

Moreover, logical operators such as and, or, and not have lower precedence than arithmetic
and relational operators. The not operator has the highest precedence among logical operators,
followed by and, and then or.
Examples:
1 # Example 1
2 result = 2 + 3 * 4
3 # Output : 14 ( Multiplication has higher precedence )
4

5 # Example 2
6 result = (2 + 3) * 4
7 # Output : 20 ( Parentheses have highest precedence )
8

9 # Example 3
10 result = 2 ** 3 * 4
11 # Output : 32 ( Exponentiation has higher precedence than multiplication )

3.3 Control Flow


Python provides constructs like if, elif, and else for decision making, and loops like for and
while for iteration.

6
Vo Hoang Nhat Khang (Christ) 4 HERE COMES A LITTLE MORE ”BASICS”...

3.3.1 Conditional Statements: if-elif-else


Conditional statements allow you to execute different blocks of code based on certain conditions.
1 # Example of if - else statement
2 x = 10
3 if x > 0:
4 print ( " Positive " )
5 elif x < 0:
6 print ( " Negative " )
7 else :
8 print ( " Zero " )

In this example:
• If x is greater than 0, it prints ”Positive”.
• If x is less than 0, it prints ”Negative”.

• If x is neither greater nor less than 0 (i.e., x is 0), it prints ”Zero”.

3.3.2 Loops
Loops are used to execute a block of code repeatedly.
1 # Example of for loop
2 fruits = [ " apple " , " banana " , " cherry " ]
3 for fruit in fruits :
4 print ( fruit )
5

6 # Example of while loop


7 count = 0
8 while count < 5:
9 print ( count )
10 count += 1
The for loop iterates over each element in the list fruits and prints it. The while loop prints
numbers from 0 to 4.

4 Here comes a little more ”Basics”...


4.1 Functions
Functions are reusable blocks of code that perform a specific task. They help in organizing code
and promoting reusability.

4.1.1 User-defined Functions


User-defined functions are created by the user to perform a specific task. They are defined using
the def keyword followed by the function name and parameters (if any). Here’s an example:
1 # Example of a user - defined function
2 def greet ( name ) :
3 print ( " Hello , " + name + " ! " )
4

5 greet ( " Alice " )

greet() is a user-defined function that takes one parameter name and prints a greeting message.

4.1.2 Built-in Functions


Python provides several built-in functions that are readily available for use without the need for
explicit definition. Examples of built-in functions include print(), len(), max(), min(), etc.

7
Vo Hoang Nhat Khang (Christ) 4 HERE COMES A LITTLE MORE ”BASICS”...

1 # Example of built - in functions


2 numbers = [5 , 2 , 8 , 1 , 9]
3 print ( " Length : " , len ( numbers ) )
4 print ( " Maximum : " , max ( numbers ) )
5 print ( " Minimum : " , min ( numbers ) )
len(), max(), and min() are built-in functions used to find the length, maximum, and minimum
value in a list, respectively.

4.1.3 Lambda Functions (Anonymous Functions)


Lambda functions, also known as anonymous functions, are small, single-expression functions that
are defined using the lambda keyword. They can have any number of parameters but can only
have one expression.
1 # Example of a lambda function
2 multiply = lambda x , y : x * y
3 print ( " Result : " , multiply (5 , 3) )

A lambda function named multiply takes two parameters (x and y) and returns their product.

4.1.4 Recursive Functions


Recursive functions are functions that call themselves within their own definition. They are useful
for solving problems that can be broken down into smaller, similar subproblems.
1 # Example of a recursive function
2 def factorial ( n ) :
3 if n == 0:
4 return 1
5 else :
6 return n * factorial ( n - 1)
7

8 print ( " Factorial of 5: " , factorial (5) )

The factorial() function calculates the factorial of a number using recursion.

4.2 Lists and Dictionaries


Lists and dictionaries are versatile data structures in Python used to store collections of items.

4.2.1 Lists
A list is an ordered collection of items, where each item has an index associated with it. Lists
are mutable, meaning their elements can be changed after creation. Lists can contain elements of
different data types, including integers, floats, strings, or even other lists.
1 # Example of list
2 my_list = [1 , 2 , 3 , 4 , ’ apple ’ , ’ banana ’]

Common Operations on Lists:

• Accessing Elements: Elements in a list are accessed using their index.


1 my_list = [1 , 2 , 3 , 4 , 5]
2 print ( my_list [0]) # Output : 1
3 print ( my_list [2]) # Output : 3

• Slicing: Slicing allows you to extract a subset of elements from a list.


1 my_list = [1 , 2 , 3 , 4 , 5]
2 print ( my_list [1:4]) # Output : [2 , 3 , 4]
3 print ( my_list [:3]) # Output : [1 , 2 , 3]
4 print ( my_list [2:]) # Output : [3 , 4 , 5]

8
Vo Hoang Nhat Khang (Christ) 4 HERE COMES A LITTLE MORE ”BASICS”...

• Appending and Extending: You can add elements to a list using the append() method
or extend it with another list using the extend() method.
1 my_list = [1 , 2 , 3]
2 my_list . append (4)
3 print ( my_list ) # Output : [1 , 2 , 3 , 4]
4

5 another_list = [5 , 6 , 7]
6 my_list . extend ( another_list )
7 print ( my_list ) # Output : [1 , 2 , 3 , 4 , 5 , 6 , 7]

• Removing Elements: Elements can be removed from a list using the remove() method or
by using the del statement.
1 my_list = [1 , 2 , 3 , 4 , 5]
2 my_list . remove (3)
3 print ( my_list ) # Output : [1 , 2 , 4 , 5]
4

5 del my_list [0]


6 print ( my_list ) # Output : [2 , 4 , 5]

• List Comprehension: List comprehension provides a concise way to create lists based on
existing lists.
1 numbers = [1 , 2 , 3 , 4 , 5]
2 squared = [ x ** 2 for x in numbers ]
3 print ( squared ) # Output : [1 , 4 , 9 , 16 , 25]

Lists can contain elements of different types, including other lists:


1 # List in list
2 nested_list = [[1 , 2] , [3 , 4] , [5 , 6]]
3 print ( nested_list ) # Output : [[1 , 2] , [3 , 4] , [5 , 6]]

Lists support various operations, including:

• Concatenation: Combining two or more lists into a single list.


1 list1 = [1 , 2 , 3]
2 list2 = [4 , 5 , 6]
3 combined_list = list1 + list2
4 print ( combined_list ) # Output : [1 , 2 , 3 , 4 , 5 , 6]

• Repetition: Repeating the elements of a list a specified number of times.


1 list1 = [1 , 2]
2 repeated_list = list1 * 3
3 print ( repeated_list ) # Output : [1 , 2 , 1 , 2 , 1 , 2]

• Membership Testing: Checking if an element is present in a list.


1 my_list = [1 , 2 , 3 , 4 , 5]
2 print (3 in my_list ) # Output : True
3 print (6 in my_list ) # Output : False

NOTE: In addition to positive indices, Python also supports negative indices, which count
from the end of the list. So, my list[-1] accesses the last element, my list[-2] accesses the
second to last element, and so on.
1 print ( my_list [ -1]) # Output : 5 ( last element )
2 print ( my_list [ -2]) # Output : 4 ( second to last element )

9
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...

4.2.2 Dictionaries
A dictionary is an unordered collection of key-value pairs. Each key is unique within a dictionary,
and it is used to access its associated value. Dictionaries are mutable, meaning their elements
(both keys and values) can be changed after creation.
1 # Example of dictionary
2 my_dict = { ’a ’: 1 , ’b ’: 2 , ’c ’: 3}

Common Operations on Dictionaries:

• Accessing Elements: Elements in a dictionary are accessed using their keys.


1 my_dict = { ’a ’: 1 , ’b ’: 2 , ’c ’: 3}
2 print ( my_dict [ ’a ’ ]) # Output : 1
3 print ( my_dict [ ’c ’ ]) # Output : 3

• Adding or Updating Elements: You can add new key-value pairs to a dictionary or
update existing values by assigning new values to them.
1 my_dict = { ’a ’: 1 , ’b ’: 2}
2 my_dict [ ’c ’] = 3 # Adding a new key - value pair
3 print ( my_dict ) # Output : { ’ a ’: 1 , ’b ’: 2 , ’c ’: 3}
4

5 my_dict [ ’a ’] = 10 # Updating an existing value


6 print ( my_dict ) # Output : { ’ a ’: 10 , ’b ’: 2 , ’c ’: 3}

• Removing Elements: Elements (key-value pairs) can be removed from a dictionary using
the del statement or the pop() method.
1 my_dict = { ’a ’: 1 , ’b ’: 2 , ’c ’: 3}
2 del my_dict [ ’b ’] # Removing a key - value pair using del
3 print ( my_dict ) # Output : { ’ a ’: 1 , ’c ’: 3}
4

5 value = my_dict . pop ( ’a ’) # Removing and returning a value using pop


6 print ( value ) # Output : 1
7 print ( my_dict ) # Output : { ’ c ’: 3}

• Dictionary Comprehension: Similar to list comprehension, dictionary comprehension


provides a concise way to create dictionaries based on existing dictionaries.
1 my_dict = { ’a ’: 1 , ’b ’: 2 , ’c ’: 3}
2 squared_dict = { key : value ** 2 for key , value in my_dict . items () }
3 print ( squared_dict ) # Output : { ’ a ’: 1 , ’b ’: 4 , ’c ’: 9}

5 Just a little more ”Basics”...


5.1 Object-Oriented Programming (OOP)
Object-oriented programming (OOP) is a programming paradigm that allows you to organize your
code into objects, which represent real-world entities. In Python, everything is an object, and
OOP concepts like classes, objects, inheritance, and polymorphism are supported.

5.1.1 Classes and Objects


A class is a blueprint for creating objects. It defines attributes (data) and methods (functions)
that characterize an object’s behavior. An object is an instance of a class.
1 # Example of a class
2 class Circle :
3 def __init__ ( self , radius ) :
4 self . _radius = radius # Public attribute
5

6 def area ( self ) :

10
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...

7 return 3.14 * self . _radius ** 2


8

9 # Creating an object of the Circle class


10 circle = Circle (5)
11 print ( circle . area () ) # Output : 78.5
In this example, the Circle class represents a circle with a radius. The init () method
is a special method called a constructor, used to initialize object attributes. The area() method
calculates the area of the circle.
Naming Convention for Visibility:
• Public: Attributes and methods intended for public use should have names with a single
leading underscore.
• Protected: Attributes and methods intended for internal use but still accessible in subclasses
should have names with a single leading underscore.
• Private: Attributes and methods intended for internal use and not accessible in subclasses
should have names with double leading underscores.
Here’s an example demonstrating the naming convention:
1 class MyClass :
2 def __init__ ( self ) :
3 self . public_attribute = 10
4 self . _protected_attribute = 20
5 self . __private_attribute = 30
6

7 def public_method ( self ) :


8 pass
9

10 def _protected_method ( self ) :


11 pass
12

13 def __private_method ( self ) :


14 pass
15

16 obj = MyClass ()
17 print ( obj . public_attribute ) # Accessible
18 print ( obj . _protected_attribute ) # Accessible , but conventionally
considered private
19 print ( obj . __private_attribute ) # Results in AttributeError : ’ MyClass ’
object has no attribute ’ __private_attribute ’
In this example:

• public attribute and public method() are public.


• protected attribute and protected method() are protected.
• private attribute and private method() are private.

5.1.2 Inheritance
Inheritance allows a class (subclass) to inherit attributes and methods from another class (super-
class). It promotes code reusability and allows you to create hierarchical relationships between
classes.
1 # Example of inheritance
2 class Animal :
3 def sound ( self ) :
4 pass
5

6 class Dog ( Animal ) :


7 def sound ( self ) :
8 return " Woof ! "

11
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...

10 class Cat ( Animal ) :


11 def sound ( self ) :
12 return " Meow ! "
13

14 # Creating objects of subclasses


15 dog = Dog ()
16 cat = Cat ()
17 print ( dog . sound () ) # Output : Woof !
18 print ( cat . sound () ) # Output : Meow !

The Animal class is a superclass, and the Dog and Cat classes are subclasses. They inherit the
sound() method from the Animal class.

5.1.3 Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
It allows methods to be called on objects without knowing their specific types.
1 # Example of polymorphism
2 class Shape :
3 def area ( self ) :
4 pass
5

6 class Rectangle ( Shape ) :


7 def __init__ ( self , length , width ) :
8 self . length = length
9 self . width = width
10

11 def area ( self ) :


12 return self . length * self . width
13

14 class Circle ( Shape ) :


15 def __init__ ( self , radius ) :
16 self . radius = radius
17

18 def area ( self ) :


19 return 3.14 * self . radius ** 2
20

21 # Function to calculate total area of shapes


22 def total_area ( shapes ) :
23 total = 0
24 for shape in shapes :
25 total += shape . area ()
26 return total
27

28 # Creating objects of different shapes


29 shapes = [ Rectangle (4 , 5) , Circle (3) ]
30 print ( " Total area : " , total_area ( shapes ) ) # Output : 47.26

Shape

inherits inherits

Rectangle Circle

The Shape class is a superclass with an area() method. Both Rectangle and Circle classes
are subclasses of Shape and override the area() method. The total area() function demonstrates
polymorphism by accepting a list of shapes (objects of different classes) and calculating their total
area without knowing their specific types.

12
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...

5.1.4 Type Hinting


Type hinting in OOP allows you to annotate class attributes, method parameters, and return types
with their expected types. This provides clarity about the structure of your classes and methods,
making your code easier to understand and maintain.
1 class Person :
2 def init ( self , name : str , age : int ) -> None :
3 self . name = name
4 self . age = age
5

6 def greet ( self , other_person : Person ) -> str :


7 return f " Hello , { other_person . name }! My name is { self . name }. "
In this example, we’ve defined a simple Person class with two attributes: name and age. We’ve
used type hints to specify that name should be a string and age should be an integer.
The greet method takes another Person object as a parameter and returns a greeting message.
We’ve annotated the parameter other person with the type Person to indicate that it expects an
instance of the Person class. The return type of the greet method is annotated as str, indicating
that it returns a string.

5.2 Modules and Packages


Modules and packages are essential for organizing Python code into reusable units and facilitating
code maintenance.

5.2.1 Modules
A module is a Python file containing Python code, such as functions, classes, or variables. You
can import modules in other Python scripts to use their functionality.
1 # Example of a module
2 # File : my_module . py
3 def greet ( name ) :
4 print ( " Hello , " + name + " ! " )

To use the greet() function from my module.py in another Python script:


1 # Importing a module
2 import my_module
3

4 my_module . greet ( " Alice " ) # Output : Hello , Alice !

5.2.2 Packages
A package is a collection of Python modules organized in directories. It helps in organizing and
managing large Python projects by providing a hierarchical structure.
1 # Example of a package
2 # Directory structure :
3 # my_package /
4 # __init__ . py
5 # module1 . py
6 # module2 . py
7

8 # In module1 . py
9 def func1 () :
10 pass
11

12 # In module2 . py
13 def func2 () :
14 pass

To use functions from modules within a package:

13
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...

1 # Importing modules from a package


2 from my_package import module1 , module2
3

4 module1 . func1 ()
5 module2 . func2 ()

5.2.3 Standard Library


Python comes with a vast standard library that provides modules and packages for various pur-
poses, such as file I/O, networking, mathematics, etc. You can directly import and use modules
from the standard library in your Python scripts.
1

2 # Example of importing modules from the standard library


3 import math
4

5 print ( math . sqrt (25) ) # Output : 5.0

The math module from the standard library provides mathematical functions and constants.

5.2.4 Additional libraries for major domains


• Web Development:
– Flask: A lightweight web framework for building web applications in Python.
– Django: A high-level web framework that encourages rapid development and clean,
pragmatic design.
• Artificial Intelligence (AI):
– TensorFlow: An open-source machine learning framework developed by Google for
building and training neural networks.
– PyTorch: A deep learning framework that provides tensors and dynamic neural networks
in Python.
• Machine Learning (ML):
– Scikit-learn: A simple and efficient tool for data mining and data analysis, built on
NumPy, SciPy, and matplotlib.
– XGBoost: An optimized distributed gradient boosting library designed for efficient and
accurate large-scale machine learning tasks.
• Data Science:
– Pandas: A powerful data analysis and manipulation library that provides data structures
and functions for working with structured data.
– NumPy: A fundamental package for scientific computing with Python, providing sup-
port for arrays, matrices, and mathematical functions.
• Natural Language Processing (NLP):

– NLTK (Natural Language Toolkit): A leading platform for building Python programs
to work with human language data.
– SpaCy: An industrial-strength natural language processing library designed for perfor-
mance and usability.

5.3 Exception Handling


Exception handling in Python allows you to gracefully manage errors and unexpected situations
that may occur during program execution.

14
Vo Hoang Nhat Khang (Christ) 6 SMALL PYTHON PROJECTS FOR BEGINNERS

5.3.1 try-except Block


The try block is used to enclose the code that may raise an exception, and the except block is
used to handle the exception.
1 # Example of exception handling
2 try :
3 x = 1 / 0
4 except ZeroDivisionError :
5 print ( " Cannot divide by zero " )
In this example, a ZeroDivisionError exception is caught when attempting to divide by zero.

5.3.2 Multiple Except Blocks


You can have multiple except blocks to handle different types of exceptions.
1 # Example of handling multiple exceptions
2 try :
3 x = int ( input ( " Enter a number : " ) )
4 y = 10 / x
5 except ValueError :
6 print ( " Invalid input . Please enter a valid number . " )
7 except ZeroDivisionError :
8 print ( " Cannot divide by zero " )

In this example, ValueError is caught when the user inputs a non-integer value, and ZeroDi-
visionError is caught when the user inputs zero.

5.3.3 finally Block


The finally block is used to execute cleanup code, regardless of whether an exception occurs or
not. It is often used for releasing resources or performing cleanup actions that should always occur,
regardless of whether an exception is raised or not.
1 # Example of finally block
2 try :
3 # Open a file
4 file = open ( " example . txt " , " r " )
5 # Perform file operations
6 # ...
7 except FileNotFoundError :
8 print ( " File not found " )
9 else :
10 print ( " File opened successfully " )
11 finally :
12 # Close the file , regardless of whether an exception occurred or not
13 file . close ()
14 print ( " File closed " )

In this example, the finally block ensures that the file is closed properly, regardless of whether
the file operations within the ‘try‘ block are successful or if an exception is raised. This ensures
proper cleanup of resources, promoting good coding practices and preventing resource leaks.

6 Small Python Projects for Beginners


After learning Python, it’s essential to practice your skills by working on small projects. These
projects not only reinforce your understanding of Python concepts but also give you hands-on
experience in solving real-world problems. Here are some suggestions for small Python projects
suitable for beginners:

15
Vo Hoang Nhat Khang (Christ) 6 SMALL PYTHON PROJECTS FOR BEGINNERS

1. To-Do List Application


• Starting Point: Begin by designing the basic structure of your to-do list application.
Identify the features you want to include, such as adding tasks, marking tasks as
complete, and removing tasks.

• Libraries to Research: For creating a user interface, consider libraries like Tkinter
for desktop applications or Flask/Django for web-based applications. You may also
need to explore file handling modules like pickle or json for storing tasks.

2. Web Scraping Script


• Starting Point: Choose a website to scrape data from and identify the specific
information you want to extract. Create a plan for navigating the website’s structure
and retrieving the desired data.
• Libraries to Research: Look into libraries such as BeautifulSoup and requests for
fetching and parsing HTML content. You may also need to explore libraries like
Selenium for scraping dynamic websites or APIs for accessing structured data.

3. Calculator
• Starting Point: Decide whether you want to build a command-line or GUI-based
calculator. Plan out the user interface and the operations your calculator will support.

• Libraries to Research: For building a GUI, consider libraries like Tkinter, PyQt,
or Kivy. If you’re developing a command-line application, you won’t need additional
libraries beyond Python’s built-in functionality.

4. Simple Game
• Starting Point: Choose a game to implement and outline its rules and mechanics.
Start with a basic version of the game and gradually add complexity.
• Libraries to Research: Depending on the game you choose, you may need libraries
like pygame for building graphical games, or you can stick to text-based games using
only Python’s built-in modules.

5. Personal Budget Tracker


• Starting Point: Determine the categories you want to track, such as income, ex-
penses, and savings. Design a user interface for inputting transactions and generating
reports.
• Libraries to Research: For creating a GUI, consider libraries like Tkinter or PyQt.
You may also need to explore libraries like pandas for data manipulation and mat-
plotlib or seaborn for data visualization.

16
Vo Hoang Nhat Khang (Christ) 7 CONCLUSION

6. Basic Web Application


• Starting Point: Choose a micro-framework like Flask or Django and set up a basic
project structure. Define the functionality and pages your web application will have.

• Libraries to Research: For web development, you’ll need to learn about HTML,
CSS, and possibly JavaScript for the frontend. In addition to Flask or Django, you
may need to explore libraries like SQLAlchemy for database interaction and Jinja2
for templating.

7. Automation Script
• Starting Point: Identify a repetitive task that you perform manually and outline
the steps involved in automating it. Determine the input parameters and expected
output of your automation script.
• Libraries to Research: Depending on the task, you may need libraries like os or
shutil for file operations, requests for interacting with web APIs, or smtplib for sending
emails. You may also need to explore libraries like schedule for scheduling recurring
tasks.

These small projects are excellent opportunities to apply your Python skills and continue learn-
ing. Choose a project that interests you and start coding!

7 Conclusion

And there you have it, folks! We’ve reached the end of our Python adventure, from dipping
our toes into the shallow waters of basic syntax to diving headfirst into the deep sea of advanced
topics. Just like a magician pulling a rabbit out of a hat, Python has shown us its tricks, and boy,
are they impressive!
But wait, don’t pack up your circus tent just yet! Python’s journey doesn’t end here—it’s
more of a ”see you later, alligator” situation. Python’s simplicity and versatility make it a magical
language for a wide array of applications. Whether you’re scripting like a wizard, crunching
numbers like a mathematician, or creating masterpieces like a digital artist, Python’s got your
back.

17

You might also like