Python_Course_book
Python_Course_book
Carlos Barbosa
January 2025
Contents
2 Variables 7
3 f-Strings 9
4 Basic Operations 11
5 Lists 14
6 Dictionaries 16
7 Tuples 18
8 Conditional Statements 20
9 Loops 22
10 Functions 24
14 Introduction to Pandas 35
15 Introduction to NumPy 37
1
16 Introduction to Matplotlib 39
17 Introduction to scikit-learn 41
18 Hands-On Exercises 44
2
Chapter 1: Introduction to Google Colab
Objective:
Learn how to use Google Colab effectively, including running code, accessing help, and
exploring library functions.
Key Features:
• Interactive notebook environment for writing and executing Python code.
Getting Started:
1. Open Google Colab.
4. Rename the notebook by clicking on the default title (e.g., Untitled0.ipynb) in the
top-left corner.
• Write Python code in a code cell and press Shift + Enter or click the play button to
execute it.
• Example:
3
1 # Example : Print a message
2 print ( " Hello , World ! " )
• Exploring Library Documentation: Use the dir() function to list all available
attributes and methods of a module or object.
1 # Example : List all methods in the NumPy library
2 import numpy as np
3 dir ( np )
4
• Read documentation for a specific function: Use help() or np.function_name?.
1 # Example : Learn about np . mean ()
2 help ( np . mean )
3 np . mean ?
Importing Libraries:
Many libraries come pre-installed in Google Colab. Import them using the import statement:
1 # Importing libraries
2 import numpy as np
3 import pandas as pd
4 import matplotlib . pyplot as plt
5
Using GPUs and TPUs:
Enable hardware accelerators for better performance:
3. Click Save.
6
Chapter 2: Variables
Objective:
Understand variables and their assignment.
Explanation:
Variables are used to store data that can be referenced and manipulated in a program. In
Python, variables are created when you assign a value to them.
Hands-on Examples:
1 # Assigning different types of variables
2 name = " John " # String
3 age = 25 # Integer
4 height = 5.9 # Float
5 is_student = True # Boolean
6
7 # Printing variables
8 print ( name ) # Output : John
9 print ( age ) # Output : 25
10 print ( height ) # Output : 5.9
11 print ( is_student ) # Output : True
Common Errors:
• Uninitialized Variable: Accessing a variable before assigning a value to it results in
a NameError.
1 print ( score ) # NameError : name ’ score ’ is not defined
• Case Sensitivity: Python is case-sensitive; name and Name are different variables.
1 Name = " Alice "
2 print ( name ) # NameError : name ’ name ’ is not defined
Assessment Questions:
1. What will be the output of the following code?
7
1 x = 10
2 y = " 10 "
3 print ( x + y )
• a) 20
• b) 1010
• c) TypeError
• d) 10
• a) 1st name
• b) first-name
• c) first name
• d) first name
8
Chapter 3: f-Strings
Objective:
Learn how to format strings using f-strings.
Explanation:
f-strings, introduced in Python 3.6, allow for easy and readable string formatting by embed-
ding expressions inside curly braces {} prefixed with an f.
Hands-on Examples:
1 # Basic usage of f - strings
2 name = " Alice "
3 age = 30
4 print ( f " My name is { name } and I am { age } years old . " )
5 # Output : My name is Alice and I am 30 years old .
6
11 # Formatting numbers
12 pi = 3.14159
13 print ( f " Pi rounded to two decimal places is { pi :.2 f }. " )
14 # Output : Pi rounded to two decimal places is 3.14.
Common Errors:
• SyntaxError: Forgetting the f prefix results in a syntax error.
1 print ( " My name is { name } " ) # Output : My name is { name }
9
Assessment Questions:
1. What will be the output of the following code?
1 quantity = 3
2 item = " apple "
3 print ( f " I bought { quantity } { item } s . " )
• a) I bought 3 apple.
• b) I bought 3 apples.
• c) I bought quantity items.
• d) SyntaxError
10
Chapter 4: Basic Operations
Objective:
Perform arithmetic operations and understand operator precedence.
Explanation:
Python supports various arithmetic operations such as addition, subtraction, multiplication,
division, and more. Understanding operator precedence is crucial for evaluating expressions
correctly. The precedence determines the order in which operations are performed in an
expression. For instance, multiplication and division have higher precedence than addition
and subtraction. Parentheses can be used to explicitly specify the desired order of operations.
Hands-on Examples:
1 # Arithmetic operations
2 a = 15
3 b = 4
4
5 print ( a + b) # Addition : 19
6 print ( a - b) # Subtraction : 11
7 print ( a * b) # Multiplication : 60
8 print ( a / b) # Division : 3.75
9 print ( a % b) # Modulus : 3
10 print ( a ** b ) # Exponentiation : 50625
11 print ( a // b ) # Floor Division : 3
Operator Precedence:
In Python, the order of operations follows standard mathematical conventions, often remem-
bered by the acronym PEMDAS:
• Parentheses
• Exponents
11
Operations with higher precedence are performed before those with lower precedence. Op-
erators with the same precedence are evaluated from left to right (left-associative), except
for exponentiation, which is right-associative.
5 # With parentheses
6 result = (10 + 3) * 2
7 print ( result ) # Output : 26
8
9 # Exponentiation associativity
10 result = 2 ** 3 ** 2
11 print ( result ) # Output : 512 ( equivalent to 2 ** (3 ** 2) )
Common Errors:
• ZeroDivisionError: Dividing by zero is not allowed.
1 print ( a / 0) # ZeroD ivisio nError : division by zero
Assessment Questions:
1. What is the result of the following expression?
1 result = 10 + 3 * 2
2 print ( result )
2. How can you modify the expression above to change the result to 26?
3. Explain why the following code raises an error and how to fix it:
12
1 number = 10
2 text = " The number is : "
3 print ( text + number )
13
Chapter 5: Lists
Objective:
Create, access, and modify lists.
Explanation:
Lists are ordered, mutable collections that can store elements of different types. They are
one of Python’s most versatile data structures.
Hands-on Examples:
1 # Basic list operations
2 fruits = [ " apple " , " banana " , " cherry " ]
3 print ( fruits ) # Print entire list
4 print ( fruits [0]) # Access first element
5
6 # Modifying a list
7 fruits . append ( " orange " ) # Add an item
8 print ( fruits )
9
16 # Nested lists
17 nested_list = [[ " apple " , " banana " ] , [ " cherry " , " orange " ]]
18 print ( nested_list [1][0]) # Access ’ cherry ’
Common Errors:
• IndexError: Trying to access an index that does not exist.
1 print ( fruits [5]) # IndexError : list index out of range
14
1 fruits + " grape " # TypeError : can only concatenate list (
not " str ") to list
Assessment Questions:
1. What will the following code output?
1 fruits = [ " apple " , " banana " , " cherry " ]
2 print ( fruits [ -1])
• a) ”apple”
• b) ”cherry”
• c) IndexError
2. Write a Python function that takes a list and returns the second-largest element.
15
Chapter 6: Dictionaries
Objective:
Work with key-value pairs.
Explanation:
Dictionaries are unordered collections that store data in key-value pairs. Keys must be
unique and immutable.
Hands-on Examples:
1 # Basic dictionary operations
2 student = {
3 " name " : " Alice " ,
4 " age " : 22 ,
5 " major " : " Computer Science "
6 }
7 print ( student [ " name " ]) # Access value by key
8
9 # Modifying a dictionary
10 student [ " age " ] = 23 # Update value
11 student [ " graduated " ] = False # Add a new key - value pair
12 print ( student )
13
18 # Nested dictionaries
19 class_info = {
20 " class_name " : " Math 101 " ,
21 " students " : [
22 { " name " : " Alice " , " grade " : 90} ,
23 { " name " : " Bob " , " grade " : 85}
24 ]
25 }
26 print ( class_info [ " students " ][0][ " name " ]) # Access ’ Alice ’
16
Common Errors:
• KeyError: Accessing a key that does not exist.
1 print ( student [ " address " ]) # KeyError : ’ address ’
Assessment Questions:
1. Write a Python program to count the frequency of elements in the following list:
1 items = [ " apple " , " banana " , " apple " , " orange " , " banana " , "
apple " ]
17
Chapter 7: Tuples
Objective:
Introduce immutable collections.
Explanation:
Tuples are ordered, immutable collections. Once created, the elements of a tuple cannot be
changed.
Hands-on Examples:
1 # Basic tuple operations
2 colors = ( " red " , " green " , " blue " )
3 print ( colors [0]) # Access first element
4
5 # Tuple unpacking
6 r , g , b = colors
7 print ( r ) # Output : red
8
13 # Nested tuples
14 nested_tuple = ((1 , 2) , (3 , 4) )
15 print ( nested_tuple [1][0]) # Access 3
Common Errors:
• TypeError: Attempting to modify a tuple.
1 colors [0] = " yellow " # TypeError : ’ tuple ’ object does not
support item assignment
18
Assessment Questions:
1. What is the output of the following code?
1 colors = ( " red " , " green " , " blue " )
2 print ( len ( colors ) )
• a) 2
• b) 3
• c) TypeError
2. Write a Python function that accepts a tuple of numbers and returns their average.
19
Chapter 8: Conditional Statements
Objective:
Understand if, elif, and else.
Explanation:
Conditional statements allow decision-making in a program based on conditions. The syntax
includes:
Hands-on Examples:
1 # Basic conditional statements
2 age = 20
3
11 # Nested conditions
12 score = 85
13 if score >= 90:
14 print ( " Grade : A " )
15 elif 80 <= score < 90:
16 print ( " Grade : B " )
17 else :
18 print ( " Grade : C " )
Common Errors:
• IndentationError: Improper indentation can lead to syntax errors.
20
1 if age < 18:
2 print ( " Minor " ) # IndentationError
Assessment Questions:
1. Write a program to determine if a number is positive, negative, or zero.
21
Chapter 9: Loops
Objective:
Use for and while loops to iterate over sequences or perform repeated tasks.
Explanation:
• For Loop: Iterates over a sequence (e.g., list, range).
Hands-on Examples:
1 # For loop
2 for i in range (5) :
3 print ( i )
4
10 # While loop
11 count = 0
12 while count < 5:
13 print ( count )
14 count += 1
15
Common Errors:
• Infinite Loops: Forgetting to update the loop variable.
22
1 count = 0
2 while count < 5:
3 print ( count ) # Infinite loop
Assessment Questions:
1. Write a program to calculate the factorial of a number using a while loop.
23
Chapter 10: Functions
Objective:
Write reusable code blocks using functions.
Explanation:
Functions allow modular programming by grouping reusable blocks of code. They make the
code more organized, readable, and easier to debug or extend. Functions are defined using
the def keyword followed by the function name and parentheses.
Syntax:
1 def function_name ( parameters ) :
2 """ Optional docstring describing the function . """
3 # Function body
4 return result
Hands-on Examples:
1 # Example 1: Basic Function
2 def greet () :
3 print ( " Hello , World ! " )
4
17 result = add (5 , 3)
18 print ( result ) # Output : 8
19
24
20 # Example 4: Function with Default Parameters
21 def multiply (a , b =2) :
22 return a * b
23
Common Errors:
• TypeError: Calling a function without the required number of arguments.
1 def subtract (a , b ) :
2 return a - b
3
Best Practices:
• Use meaningful function names that describe their purpose.
25
Assessment Questions:
1. Write a function to calculate the factorial of a number.
2. Modify the add function to handle any number of arguments using *args.
26
Chapter 11: Putting It All Together
Objective:
Build a simple project combining multiple programming concepts.
Explanation:
This project demonstrates how to combine variables, loops, conditional statements, and
functions to create a simple and reusable program. By following the steps, you will learn
how to structure a program in a modular way.
• Validate input using conditional statements (e.g., ensure the age is a positive integer).
27
7 major = input ( " Enter your major : " )
8 return { " name " : name , " age " : age , " major " }
9
28
Additional Ideas for Enhancement:
• Save student data to a file (e.g., CSV or JSON).
Assessment Questions:
1. Modify the program to allow updating a student’s major.
2. Extend the program to calculate and display the average age of students.
29
Chapter 12: Importing Libraries and Files
Objective:
Learn how to import Python libraries and external files.
Explanation:
• Libraries are pre-written code modules that extend Python’s capabilities. Examples
include math, pandas, and numpy.
• Import libraries using import and optionally assign aliases with as for convenience.
• To read external files (e.g., CSVs, JSON), use functions like open, pandas.read_csv,
or json.load.
Hands-on Examples:
1 # Importing and using a standard library
2 import math
3 print ( math . sqrt (16) ) # Output : 4.0
4
30
23 print ( excel_data . head () )
24
31
Common Errors:
• FileNotFoundError: Occurs if the specified file path is incorrect.
1 data = pd . read_csv ( ’ missing . csv ’) # Fi leNotF oundEr ror
Assessment Questions:
1. Write a program to read and display the contents of a text file line by line.
2. What happens if you try to import a library that is not installed? Provide a solution
to fix it.
3. Write a script to load and display the first 3 rows of a CSV file using pandas.
32
Chapter 13: Popular Libraries for AI and Data Science
Objective:
Introduce essential libraries for AI and Data Science.
Explanation:
Python is widely used in AI and data science due to its rich ecosystem of libraries. Below
are some of the most popular ones:
• Pandas: For data manipulation and analysis. It provides powerful data structures
like DataFrames.
• NumPy: For numerical operations on arrays. It serves as the foundation for many
other libraries.
Hands-on Examples:
1 # Pandas : Reading a CSV file and performing operations
2 import pandas as pd
3 data = pd . DataFrame ({ " Name " : [ " Alice " , " Bob " ] , " Score " : [85 , 90]})
4 print ( data )
5
33
18 # Matplotlib : Creating a line plot
19 import matplotlib . pyplot as plt
20 x = [1 , 2 , 3 , 4]
21 y = [1 , 4 , 9 , 16]
22 plt . plot (x , y )
23 plt . title ( " Simple Line Plot " )
24 plt . xlabel ( "X - axis " )
25 plt . ylabel ( "Y - axis " )
26 plt . show ()
27
Common Errors:
• ImportError: Using the wrong import syntax for a library.
Assessment Questions:
1. Write a program using NumPy to calculate the standard deviation of an array.
2. Use Matplotlib to create a bar chart showing monthly sales for 6 months.
3. Load a CSV file and train a linear regression model using scikit-learn.
34
Chapter 14: Introduction to Pandas
Objective:
Learn to manipulate and analyze tabular data effectively using Pandas.
Explanation:
Pandas is a powerful library for data manipulation and analysis. It provides two main data
structures:
Hands-on Examples:
1 # Importing Pandas
2 import pandas as pd
3
4 # Creating a DataFrame
5 data = {
6 " Name " : [ " John " , " Bob " , " Charlie " ] ,
7 " Age " : [25 , 30 , 35] ,
8 " City " : [ " Miami " , " Los Angeles " , " Fort Lauderdale " ]
9 }
10 df = pd . DataFrame ( data )
11 print ( df )
12
16 # Basic operations
17 print ( df [ " Age " ]. mean () ) # Calculate the average age
18 print ( df [ df [ " City " ] == " Miami " ]) # Filter rows by city
19
24 # Dropping a column
25 df = df . drop ( columns =[ " City " ])
35
26 print ( df )
Common Errors:
• KeyError: Accessing a non-existent column.
1 print ( df [ " NonEx istent Column " ]) # KeyError : ’
Non Existe ntColu mn ’
Assessment Questions:
1. Create a DataFrame with columns Name, Age, and Department. Add a new column
for Salary.
2. Write a program to filter rows where the age is greater than 30.
36
Chapter 15: Introduction to NumPy
Objective:
Perform efficient numerical operations on arrays using NumPy.
Explanation:
NumPy (Numerical Python) is a library for numerical computations. It provides the ndar-
ray object for efficient multi-dimensional array operations. Key features include:
Hands-on Examples:
1 # Importing NumPy
2 import numpy as np
3
7 # Basic operations
8 print ( array * 2) # Element - wise multiplication
9 print ( np . mean ( array ) ) # Calculate mean
10 print ( np . sqrt ( array ) ) # Element - wise square root
11
16 # Accessing elements
17 print ( matrix [0 , 1]) # Access element at row 0 , column 1
Common Errors:
• TypeError: Performing unsupported operations on NumPy arrays.
37
1 array = np . array ([1 , 2 , 3])
2 print ( array + " 1 " ) # TypeError : cannot concatenate ’ str ’
to ’ int ’
Assessment Questions:
1. Create a NumPy array of numbers from 1 to 10. Calculate the sum and standard
deviation.
38
Chapter 16: Introduction to Matplotlib
Objective:
Create data visualizations for exploratory data analysis and reporting.
Explanation:
Matplotlib is a versatile library for creating static, interactive, and animated visualizations
in Python. Key features include:
Hands-on Examples:
1 # Importing Matplotlib
2 import matplotlib . pyplot as plt
3
4 # Data
5 x = [1 , 2 , 3 , 4 , 5]
6 y = [2 , 4 , 6 , 8 , 10]
7
39
Common Errors:
• ValueError: Mismatch between the lengths of x and y data.
1 plt . plot ([1 , 2] , [1 , 2 , 3]) # ValueError : x and y must
have same first dimension
Assessment Questions:
1. Create a scatter plot to visualize the relationship between two variables.
3. Customize a line plot by changing its color, style, and adding markers.
40
Chapter 17: Introduction to scikit-learn
Objective:
Use machine learning algorithms for predictive modeling.
Explanation:
scikit-learn is a popular library for machine learning in Python. It provides tools for:
• Supervised learning (e.g., regression, classification).
Hands-on Examples:
1 # Import required libraries
2 from sklearn . linear_model import LinearRegression
3 import numpy as np
4 import matplotlib . pyplot as plt
5
41
22 # Plot the data points
23 plt . scatter (X , y , color = ’ blue ’ , label = ’ Randomized Data Points ’)
24
Common Errors:
• ValueError: Occurs when the input shape is incorrect.
1 model . fit ([1 , 2 , 3 , 4] , [2 , 4 , 6 , 8])
2 # ValueError : Expected 2 D array , got 1 D array
42
2 print ( model . predict ([[5]]) ) # NotFittedError
Assessment Questions:
1. Use scikit-learn to create and train a logistic regression model for binary classification.
43
Chapter 18: Hands-On Exercises
Objective:
Reinforce the concepts taught in the class through self-guided practice.
Exercises:
1. f-String Practice:
• Write a program that takes two numbers as input from the user and prints their
sum using an f-string.
• Example Output:
1 Enter the first number : 5
2 Enter the second number : 7
3 The sum of 5 and 7 is 12.
• Extension: Modify the program to calculate and display the product, difference,
and quotient of the two numbers.
2. Basic Operations:
• Write a program that calculates the area and perimeter of a rectangle given its
length and width.
• Example Output:
1 Enter length : 10
2 Enter width : 5
3 Area : 50
4 Perimeter : 30
44
• Extension: Create a function to search for a movie in the list and return its
index.
4. Dictionaries:
• Create a NumPy array with values [10, 20, 30, 40, 50].
• Perform the following operations:
(a) Multiply all elements by 3.
(b) Calculate the mean and standard deviation.
(c) Find the maximum and minimum values.
• Extension: Create a 2D NumPy array and calculate the sum of its rows and
columns.
6. Pandas DataFrame:
45
(b) Add a new column for Pass/Fail (Grade ¿= 80 is Pass).
(c) Filter the DataFrame to show only students who passed.
• Extension: Save the DataFrame to a CSV file and reload it using Pandas.
7. Matplotlib Visualization:
• Using scikit-learn, train a linear regression model with the following data:
1 X = [[1] , [2] , [3] , [4]]
2 y = [2 , 4 , 6 , 8]
Note:
Experiment and modify these examples to observe the effects of different inputs and param-
eters.
46