Python Course
Python Course
Python Course
1
Vo Hoang Nhat Khang (Christ) CONTENTS
Contents
1 Introduction 3
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.
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.
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.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 ’}
4
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS
7 result = add (3 , 5)
8 print ( result ) # Output : 8
9
5
Vo Hoang Nhat Khang (Christ) 3 FIRST STEP: GET A SENSE OF LEARNING BASICS
33 remainder = x % y
34 return quotient , remainder
35
3.2 Operators
Python supports various operators for performing operations on variables and values.
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 )
6
Vo Hoang Nhat Khang (Christ) 4 HERE COMES A LITTLE MORE ”BASICS”...
In this example:
• If x is greater than 0, it prints ”Positive”.
• If x is less than 0, it prints ”Negative”.
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
greet() is a user-defined function that takes one parameter name and prints a greeting message.
7
Vo Hoang Nhat Khang (Christ) 4 HERE COMES A LITTLE MORE ”BASICS”...
A lambda function named multiply takes two parameters (x and y) and returns their product.
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 ’]
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
• 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]
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}
• 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
• 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
10
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...
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:
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
11
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...
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
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.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 + " ! " )
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
13
Vo Hoang Nhat Khang (Christ) 5 JUST A LITTLE MORE ”BASICS”...
4 module1 . func1 ()
5 module2 . func2 ()
The math module from the standard library provides mathematical functions and constants.
– 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.
14
Vo Hoang Nhat Khang (Christ) 6 SMALL PYTHON PROJECTS FOR BEGINNERS
In this example, ValueError is caught when the user inputs a non-integer value, and ZeroDi-
visionError is caught when the user inputs zero.
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.
15
Vo Hoang Nhat Khang (Christ) 6 SMALL PYTHON PROJECTS FOR BEGINNERS
• 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.
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.
16
Vo Hoang Nhat Khang (Christ) 7 CONCLUSION
• 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