0% found this document useful (0 votes)
5 views

Python_Course_book

The document is a beginner's guide to Python programming, covering essential topics such as Google Colab, variables, data types, and basic operations. It includes hands-on examples, common errors, and assessment questions to reinforce learning. The content is structured into chapters, each focusing on different aspects of Python, making it suitable for newcomers to the language.

Uploaded by

Carlos Barbosa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python_Course_book

The document is a beginner's guide to Python programming, covering essential topics such as Google Colab, variables, data types, and basic operations. It includes hands-on examples, common errors, and assessment questions to reinforce learning. The content is structured into chapters, each focusing on different aspects of Python, making it suitable for newcomers to the language.

Uploaded by

Carlos Barbosa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Python - Beginners - CAI1001C

Carlos Barbosa
January 2025

Contents

1 Introduction to Google Colab 3

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

11 Putting It All Together 27

12 Importing Libraries and Files 30

13 Popular Libraries for AI and Data Science 33

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.

What is Google Colab?


Google Colab is a cloud-based platform for running Python code in an interactive notebook
format. It is free to use and provides access to resources such as GPUs and TPUs, making
it ideal for data analysis, machine learning, and more.

Key Features:
• Interactive notebook environment for writing and executing Python code.

• Free access to GPUs/TPUs for machine learning tasks.

• Integration with Google Drive for saving and sharing notebooks.

• Pre-installed libraries like NumPy, Pandas, and Matplotlib.

Getting Started:
1. Open Google Colab.

2. Sign in with your Google account.

3. Create a new notebook: File ¿ New Notebook.

4. Rename the notebook by clicking on the default title (e.g., Untitled0.ipynb) in the
top-left corner.

Running Code in Colab:


• Each cell in Colab is an executable block of Python code or markdown.

• 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 ! " )

Asking for Help in Colab:


Google Colab provides several ways to get help:
• Using the help() function: Call help() on any Python function or object to see its
documentation.
1 # Example : Get help on the print function
2 help ( print )

• Using the ? or ?? shortcuts: Add ? or ?? after a function or object name to display


its documentation.
1 # Example : View documentation for the len () function
2 len ?
3 # View source code ( if available )
4 len ??

• Using Google Colab’s built-in documentation: Hover over a function name in


the code to see a brief description and its parameters.

• 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 )

Exploring Library Functions:


Here are a few ways to explore functions and their usage:
• Check available functions in a library: Use dir() to see all functions and at-
tributes in a library.
1 # Example : Explore available functions in NumPy
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 ?

• Example Usage: Practice calling library functions:


1 # Example : Calculate the mean of an array
2 array = [1 , 2 , 3 , 4 , 5]
3 mean_value = np . mean ( array )
4 print ( " Mean : " , mean_value )

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

Installing Additional Libraries:


Use the !pip install command to install additional libraries.
1 # Install a library
2 ! pip install seaborn
3 # Import the installed library
4 import seaborn as sns

Integration with Google Drive:


• Mount your Google Drive to access files directly:
1 from google . colab import drive
2 drive . mount ( ’/ content / drive ’)

• Navigate to the mounted drive using:


1 ! ls / content / drive / MyDrive

5
Using GPUs and TPUs:
Enable hardware accelerators for better performance:

1. Go to Runtime ¿ Change runtime type.

2. Select GPU or TPU under Hardware accelerator.

3. Click Save.

Pro Tips for Using Google Colab:


• Use keyboard shortcuts for efficiency:

– Ctrl + M + B: Add a new cell below.


– Ctrl + M + D: Delete the current cell.
– Ctrl + M + Enter: Run the current cell.

• Save your notebook frequently to Google Drive.

• Share your notebook using Share in the top-right corner.

Example Code Cell:


1 # Example : End - to - End Code in Google Colab
2 import numpy as np
3

4 # Create an array and calculate mean


5 array = [10 , 20 , 30 , 40 , 50]
6 print ( " Original Array : " , array )
7 print ( " Mean of Array : " , np . mean ( array ) )

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

2. Which of the following is a valid variable name in Python?

• 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

7 # Expressions inside f - strings


8 print ( f " In five years , I will be { age + 5} years old . " )
9 # Output : In five years , I will be 35 years old .
10

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 }

• NameError: Using undefined variables inside the braces.


1 print ( f " My name is { firstname } " ) # NameError : name ’
firstname ’ is not defined

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

2. How would you include a literal brace character {} in an f-string?

• a) Use double braces: {{}}


• b) Use escape character: \{\}
• c) It’s not possible to include literal braces.
• d) Use single braces: {}

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

• Multiplication and Division

• Addition and Subtraction

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.

Examples Demonstrating Precedence:


1 # Without parentheses
2 result = 10 + 3 * 2
3 print ( result ) # Output : 16
4

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

• TypeError: Mixing incompatible types without explicit conversion.


1 print ( a + " 5 " ) # TypeError : unsupported operand type ( s )
for +: ’ int ’ and ’ str ’

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

10 fruits . remove ( " banana " ) # Remove an item


11 print ( fruits )
12

13 fruits . sort () # Sort the list


14 print ( fruits )
15

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

• TypeError: Using unsupported operations on lists.

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

14 # Iterating over a dictionary


15 for key , value in student . items () :
16 print ( f " { key }: { value } " )
17

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 ’

• TypeError: Using mutable objects (e.g., lists) as keys.


1 student [[1 , 2 , 3]] = " Test " # TypeError : unhashable type :
’ list ’

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 " ]

2. What does the .get() method do in dictionaries?

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

9 # Single - element tuple


10 single = ( " hello " ,) # Note the trailing comma
11 print ( type ( single ) ) # Output : < class ’ tuple ’>
12

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

• ValueError: Unpacking a tuple with mismatched length.


1 a , b = colors # ValueError : too many values to unpack

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:

• if: Executes a block of code if the condition is true.

• elif: Checks additional conditions if the previous ones are false.

• else: Executes a block of code if all conditions are false.

Hands-on Examples:
1 # Basic conditional statements
2 age = 20
3

4 if age < 18:


5 print ( " Minor " )
6 elif age == 18:
7 print ( " Just turned adult " )
8 else :
9 print ( " Adult " )
10

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

• Logical Errors: Using incorrect operators or conditions.


1 if age = 18: # SyntaxError : Use == for comparison
2 print ( " Just turned adult " )

Assessment Questions:
1. Write a program to determine if a number is positive, negative, or zero.

2. What is the output of the following code?


1 x = 10
2 if x > 5:
3 if x < 15:
4 print ( " A " )
5 else :
6 print ( " B " )
7 else :
8 print ( " C " )

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).

• While Loop: Repeats as long as a condition is true.

Hands-on Examples:
1 # For loop
2 for i in range (5) :
3 print ( i )
4

5 # Iterating over a list


6 colors = [ " red " , " green " , " blue " ]
7 for color in colors :
8 print ( color )
9

10 # While loop
11 count = 0
12 while count < 5:
13 print ( count )
14 count += 1
15

16 # Using break and continue


17 for i in range (10) :
18 if i == 5:
19 break # Exit the loop
20 if i % 2 == 0:
21 continue # Skip even numbers
22 print ( i )

Common Errors:
• Infinite Loops: Forgetting to update the loop variable.

22
1 count = 0
2 while count < 5:
3 print ( count ) # Infinite loop

• TypeError: Using a non-iterable object in a for loop.


1 for i in 10: # TypeError : ’ int ’ object is not iterable
2 print ( i )

Assessment Questions:
1. Write a program to calculate the factorial of a number using a while loop.

2. What is the output of the following code?


1 for i in range (3) :
2 for j in range (2) :
3 print (i , j )

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

5 greet () # Output : Hello , World !


6

7 # Example 2: Function with Parameters


8 def greet_user ( name ) :
9 print ( f " Hello , { name }! " )
10

11 greet_user ( " Alice " ) # Output : Hello , Alice !


12

13 # Example 3: Function with Return Value


14 def add (a , b ) :
15 return a + b
16

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

24 print ( multiply (4) ) # Output : 8


25 print ( multiply (4 , 3) ) # Output : 12

Common Errors:
• TypeError: Calling a function without the required number of arguments.
1 def subtract (a , b ) :
2 return a - b
3

4 print ( subtract (5) ) # TypeError : missing 1 required


positional argument

• NameError: Referring to a variable outside the function’s scope.


1 def test () :
2 x = 10
3

4 print ( x ) # NameError : name ’x ’ is not defined

• Logical Errors: Returning incorrect results due to misplaced logic.


1 def average (a , b ) :
2 return a + b / 2 # Missing parentheses causes
incorrect calculation

Best Practices:
• Use meaningful function names that describe their purpose.

• Write a docstring at the beginning of the function to explain its functionality.

• Avoid using global variables; pass parameters explicitly.

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.

3. Write a function to check whether a given string is a palindrome.

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.

Project: Student Information Manager


Step 1: Collecting Input

• Use variables to store user input.

• Validate input using conditional statements (e.g., ensure the age is a positive integer).

1 # Collecting basic student information


2 name = input ( " Enter your name : " )
3 age = int ( input ( " Enter your age : " ) )
4 if age <= 0:
5 print ( " Age must be a positive number ! " )
6 major = input ( " Enter your major : " )
7

8 # Store data in a dictionary


9 student = { " name " : name , " age " : age , " major " : major }
10 print ( student )

Step 2: Using Functions

• Write a reusable function to collect student information.

• Return a dictionary containing the data.

1 # Function to collect student data


2 def get_student_info () :
3 name = input ( " Enter your name : " )
4 age = int ( input ( " Enter your age : " ) )
5 if age <= 0:
6 print ( " Age must be a positive number ! " )

27
7 major = input ( " Enter your major : " )
8 return { " name " : name , " age " : age , " major " }
9

10 # Call the function


11 student = get_student_info ()
12 print ( student )

Step 3: Handling Multiple Students


• Use a loop to collect data for multiple students.
• Store each student’s data in a list.

1 # Collect information for multiple students


2 students = []
3 for i in range (3) : # Collect data for 3 students
4 print ( f " --- Student { i + 1} ---" )
5 students . append ( get_student_info () )
6

7 # Print all student data


8 print ( " Student Details : " )
9 for student in students :
10 print ( " ----- " )
11 for key , value in student . items () :
12 print ( f " { key . capitalize () }: { value } " )

Step 4: Adding Advanced Features


• Search for a student by name.
• Add functionality to update or delete student data.

1 # Search for a student by name


2 search_name = input ( " Enter the name of the student to search : " )
3 found = False
4 for student in students :
5 if student [ " name " ]. lower () == search_name . lower () :
6 print ( " Student Found : " )
7 for key , value in student . items () :
8 print ( f " { key . capitalize () }: { value } " )
9 found = True
10 break
11 if not found :
12 print ( " Student not found ! " )

28
Additional Ideas for Enhancement:
• Save student data to a file (e.g., CSV or JSON).

• Load existing data from a file at the start of the program.

• Implement error handling for invalid inputs.

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

5 # Importing with an alias


6 import numpy as np
7 array = np . array ([1 , 2 , 3])
8 print ( array )
9

10 # Reading a CSV file


11 import pandas as pd
12 data = pd . read_csv ( ’ example . csv ’) # Ensure the file exists in your
working directory
13 print ( data . head () ) # Display the first 5 rows
14

15 # Reading a JSON file


16 import json
17 with open ( ’ example . json ’ , ’r ’) as file :
18 data = json . load ( file )
19 print ( data )
20

21 # Reading an Excel file


22 excel_data = pd . read_excel ( ’ example . xlsx ’ , sheet_name = ’ Sheet1 ’) #
Specify the sheet name

30
23 print ( excel_data . head () )
24

25 # Loading and displaying an image


26 from PIL import Image
27 image = Image . open ( ’ example . jpg ’) # Replace with your image path
28 image . show ()
29

30 # Listing files in a directory


31 import os
32 files = os . listdir ( ’. ’) # List all files in the current directory
33 print ( files )
34

35 # Filtering files of a specific type


36 csv_files = [ file for file in files if file . endswith ( ’. csv ’) ]
37 print ( " CSV Files : " , csv_files )
38

39 # Working with multiple CSV files


40 for csv_file in csv_files :
41 data = pd . read_csv ( csv_file )
42 print ( f " Data from { csv_file }:\ n " , data . head () )
43

44 # Reading an Excel file with multiple sheets


45 excel_sheets = pd . ExcelFile ( ’ example . xlsx ’)
46 print ( " Sheet names : " , excel_sheets . sheet_names ) # List all sheet
names
47 sheet_data = excel_sheets . parse ( sheet_name = ’ Sheet1 ’) # Read
specific sheet
48 print ( sheet_data . head () )

31
Common Errors:
• FileNotFoundError: Occurs if the specified file path is incorrect.
1 data = pd . read_csv ( ’ missing . csv ’) # Fi leNotF oundEr ror

• ModuleNotFoundError: Occurs if the library is not installed or the name is mis-


spelled.
1 import panda # Mo d u l eN o t Fo u n dE r r or : No module named ’ panda

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.

• scikit-learn: For implementing machine learning algorithms.

• Matplotlib: For data visualization with plots and charts.

• TensorFlow/PyTorch: For deep learning and neural networks.

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

6 # NumPy : Array creation and manipulation


7 import numpy as np
8 array = np . array ([1 , 2 , 3 , 4])
9 print ( np . mean ( array ) ) # Output : 2.5
10

11 # scikit - learn : Implementing a simple linear regression


12 from sklearn . linear_model import LinearRegression
13 X = [[1] , [2] , [3]]
14 y = [1 , 2 , 3]
15 model = LinearRegression () . fit (X , y )
16 print ( model . predict ([[4]]) ) # Predict value for X =4
17

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

28 # TensorFlow : Defining and running a simple computation graph


29 import tensorflow as tf
30 a = tf . constant (2)
31 b = tf . constant (3)
32 print ( tf . add (a , b ) ) # Output : 5 ( TensorFlow computation )

Common Errors:
• ImportError: Using the wrong import syntax for a library.

• AttributeError: Accessing a non-existent attribute in a library.


1 import pandas as pd
2 pd . read_csv ( " file . csv " ) . head (0) # Works
3 pd . n o n e x i s t e n t _ f u n c t i o n () # AttributeError

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:

• Series: A one-dimensional array-like object.

• DataFrame: A two-dimensional table-like structure with labeled rows and columns.

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

13 # Selecting a single column ( returns a Series )


14 print ( df [ " Age " ]) # Output : Series with Age values
15

16 # Basic operations
17 print ( df [ " Age " ]. mean () ) # Calculate the average age
18 print ( df [ df [ " City " ] == " Miami " ]) # Filter rows by city
19

20 # Adding a new column


21 df [ " Salary " ] = [70000 , 80000 , 90000]
22 print ( df )
23

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 ’

• ValueError: Mismatched dimensions when adding a column.


1 df [ " NewColumn " ] = [1 , 2] # ValueError : Length of values
does not match length of index

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.

3. Calculate the median salary of the DataFrame created above.

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:

• Vectorized operations for high performance.

• Functions for linear algebra, statistics, and more.

• Broadcasting for operations on arrays of different shapes.

Hands-on Examples:
1 # Importing NumPy
2 import numpy as np
3

4 # Creating a NumPy array


5 array = np . array ([1 , 2 , 3 , 4 , 5])
6

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

12 # Multi - dimensional array


13 matrix = np . array ([[1 , 2] , [3 , 4]])
14 print ( matrix )
15

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 ’

• ValueError: Operating on arrays with incompatible shapes.


1 array1 = np . array ([1 , 2 , 3])
2 array2 = np . array ([1 , 2])
3 print ( array1 + array2 ) # ValueError : operands could not be
broadcast together

Assessment Questions:
1. Create a NumPy array of numbers from 1 to 10. Calculate the sum and standard
deviation.

2. Write a program to create a 3x3 identity matrix using NumPy.

3. Perform element-wise addition and multiplication of two 2x2 matrices.

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:

• Line plots, bar charts, scatter plots, and more.

• Customization options for labels, legends, and titles.

• Integration with NumPy and pandas for data visualization.

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

8 # Create a simple line plot


9 plt . plot (x , y , label = " y = 2 x " , color = " blue " , marker = " o " )
10 plt . xlabel ( "X - axis " )
11 plt . ylabel ( "Y - axis " )
12 plt . title ( " Simple Line Plot " )
13 plt . legend ()
14 plt . grid ( True )
15 plt . show ()
16

17 # Creating a bar chart


18 categories = [ " A " , " B " , " C " , " D " ]
19 values = [5 , 7 , 3 , 8]
20 plt . bar ( categories , values , color = " orange " )
21 plt . title ( " Bar Chart Example " )
22 plt . show ()

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

• AttributeError: Using incorrect methods or misspelled attributes.


1 plt . plt (x , y ) # AttributeError : module ’ matplotlib . pyplot ’
has no attribute ’ plt ’

Assessment Questions:
1. Create a scatter plot to visualize the relationship between two variables.

2. Generate a histogram to show the distribution of data points.

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).

• Unsupervised learning (e.g., clustering, dimensionality reduction).

• Preprocessing (e.g., scaling, encoding).

• Model evaluation and hyperparameter tuning.

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

6 # Generate randomized data with a linear trend


7 np . random . seed (100) # For reproducibility
8 X = np . random . randint (1 , 20 , size =(20 , 1) ) # Random integers
between 1 and 20
9 y = 2 * X . flatten () + np . random . normal (0 , 2 , size =20) # Linear
relation with noise
10

11 # Reshape X for scikit - learn


12 X = X . reshape ( -1 , 1)
13

14 # Create and train a Linear Regression model


15 model = LinearRegression ()
16 model . fit (X , y )
17

18 # Generate predictions for the regression line


19 X_line = np . linspace ( min ( X ) , max ( X ) , 100) . reshape ( -1 , 1)
20 y_line = model . predict ( X_line )
21

41
22 # Plot the data points
23 plt . scatter (X , y , color = ’ blue ’ , label = ’ Randomized Data Points ’)
24

25 # Plot the regression line


26 plt . plot ( X_line , y_line , color = ’ red ’ , label = ’ Regression Line ’)
27

28 # Customize the plot


29 plt . title ( " Linear Regression with Randomized Data " )
30 plt . xlabel ( " X " )
31 plt . ylabel ( " y " )
32 plt . legend ()
33 plt . grid ( True )
34

35 # Show the plot


36 plt . show ()
37

38 # Extract coefficients and intercept


39 slope = model . coef_ [0] # Coefficient ( slope of the line )
40 intercept = model . intercept_ # Intercept (y - axis intercept )
41

42 # Make predictions for specific values


43 predicted_y = model . predict ( X )
44

45 # Print model values


46 print ( f " Slope ( Coefficient ) : { slope } " )
47 print ( f " Intercept : { intercept } " )
48 print ( " Predicted Values : " , predicted_y )
49

50 # Calculate R - squared value


51 r_squared = model . score (X , y )
52 print ( f "R - squared : { r_squared :.2 f } " )

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

• NotFittedError: Trying to make predictions before fitting the model.


1 model = LinearRegression ()

42
2 print ( model . predict ([[5]]) ) # NotFittedError

Assessment Questions:
1. Use scikit-learn to create and train a logistic regression model for binary classification.

2. Apply scaling to features using StandardScaler before training a model.

3. Implement k-means clustering using scikit-learn with a given dataset.

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

• Extension: Add functionality to calculate the diagonal length of the rectangle.

3. Working with Lists:

• Create a list of 5 favorite movies and perform the following:


(a) Print the first and last movie in the list.
(b) Add a new movie to the list.
(c) Remove the second movie from the list.
(d) Sort the list alphabetically and print it.

44
• Extension: Create a function to search for a movie in the list and return its
index.

4. Dictionaries:

• Create a dictionary with the following structure:


1 student = {
2 " name " : " John Doe " ,
3 " age " : 20 ,
4 " major " : " Computer Science "
5 }

Perform the following tasks:


(a) Add a key-value pair for GPA.
(b) Update the age to 21.
(c) Print all keys and values in the dictionary.
• Extension: Write a function that accepts a dictionary and adds a new key-value
pair.

5. NumPy Array Operations:

• 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:

• Create a DataFrame with the following data:


1 Name Age Grade
2 Alice 24 85
3 Bob 22 90
4 Charlie 23 78

Perform the following tasks:


(a) Calculate the average grade.

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:

• Create a bar chart to show the following data:


1 Categories : A , B , C , D
2 Values : 4 , 7 , 1 , 8

Add labels, a title, and color the bars.


• Extension: Create a line plot with random data and customize its color, style,
and markers.

8. scikit-learn Simple Regression:

• Using scikit-learn, train a linear regression model with the following data:
1 X = [[1] , [2] , [3] , [4]]
2 y = [2 , 4 , 6 , 8]

Predict the output for X = [[5]] and print the result.


• Extension: Plot the data points and regression line using Matplotlib.

Note:
Experiment and modify these examples to observe the effects of different inputs and param-
eters.

46

You might also like