Lecture 1 — Introduction to Python#
🎯 Learning Objectives
By the end of this lecture, you will be able to:
- ✅ Understand what Python is and why it is popular in science
- ✅ Run Python code in Jupyter Notebooks
- ✅ Use basic Python syntax: expressions, statements, and comments
- ✅ Work with fundamental data types:
int,float,str,bool - ✅ Perform basic input/output with
print()andinput()
📑 Table of Contents
- ● 🐍 Lecture 1 — Introduction to Python
- 1. ● Only one function has been called. Prefer this method for large libraries.
- 2. ● Programming Structures
🎯 Our Learning Philosophy
Our primary goal is to spark interest in computer programming by making it accessible and engaging. Rather than focusing heavily on pure algorithmics, we emphasize practical, modern object-oriented programming that opens doors to diverse applications. We believe programming is a vast universe where everyone can find their unique area of interest and develop specialized skills.
We've chosen Python as our teaching language because of its modern design, growing popularity, and gentle learning curve — perfect for beginners while remaining powerful enough for professional development. The journey culminates in each student completing an original programming project that showcases their unique talents and contributions.
📚 What You'll Learn
- 🐍 Python Fundamentals — from basic syntax to advanced concepts
- 🛠️ Multiple Approaches — interactive commands, scripts, IDEs, and notebooks
- 🏗️ Data Structures — the backbone of all software development
- ⚡ Control Structures & Functions — building logical, reusable code
- 🎨 Classes & Modules — object-oriented programming and code organization
- 🚀 Final Project — creating something original and meaningful
🔗 Resources
- 🐍 Official Python Website: python.org
- 📓 Learning Materials: Comprehensive notebooks covering all topics in detail
- 💡 Practice Opportunities: Hands-on exercises and project guidance
📚 Course Sources & Contributors
This course synthesizes material from several outstanding educational initiatives and the work of dedicated educators in the scientific computing community. We're proud to build upon these foundational resources.
👥 Primary Contributors
- 🎓 Introduction to Programming using Python (2016) - African Institute for Mathematical Sciences (AIMS)
- Jordan Masakuna
- Yaé Gaba
- Jeff Sanders
- 📊 Data Science with Python by Moussa Keita (2017)
- 🛠️ Software Carpentry - Programming with Python curriculum
- 🐍 Programming with Python (2019) - AIMS
🔗 Resources
- 🌍 AIMS South Africa: aims.ac.za
- 📘 IPuP Repository: github.com/gabayae/scientific-computing
- 🛠️ Software Carpentry: software-carpentry.org
- 🐍 Python Course: python.aims.ac.za
🐍 0.0. Why Python?
Python is an excellent choice for both beginners and experienced programmers. It's a high-level language with syntax that encourages writing clear, high-quality code. Learning is made easier through interactive interfaces like Jupyter notebooks, and its popularity extends far beyond academia—it's trusted by major players like Google, YouTube, and NASA.
As a general-purpose, interpreted language, Python offers exceptional portability across platforms (Mac OS X, Unix, Windows). Its object-oriented approach and comprehensive library ecosystem make it ideal for web development (Django), scientific computing, data analysis, and Big Data applications.
✨ Key Features
- 📖 Simple & Readable syntax - easy to learn and use
- ⚡ Interpreted Language - interactive use with no compilation needed
- 🚀 High-Level - dynamic typing and automatic memory management
- 🔄 Multi-Paradigm - supports imperative and object-oriented programming
- 🆓 Free & Open-Source - strong community support across platforms
- 📚 Rich Libraries - comprehensive standard and external libraries
🎯 0.1. Prerequisites
This notebook introduces Python and covers essential commands for getting started. The content is accessible to both beginners and experienced users, making it suitable for learning programming fundamentals or getting acquainted with data analysis.
For deeper exploration, we recommend:
- 📘 Official Python Tutorial: Python 3.4 Documentation
- 📊 Sheppard's Book: Python for Econometrics, Statistics, and Data Analysis
- 🐼 Mac Kinney's Book: Essential guide to pandas library (covered later)
🔧 0.2. Installation & Key Libraries
Install Python from the official site. Essential scientific libraries include:
- 🐍 IPython: Interactive Python shell - Documentation
- 🔢 NumPy: Vectors and arrays - Documentation
- ⚗️ SciPy: Numerical algorithms - Documentation
- 📊 Matplotlib: Data visualization - Documentation
- 🐼 Pandas: Data structures & analysis - Documentation
- 📈 Statsmodels: Statistical modeling - Documentation
- 🤖 Scikit-learn: Machine learning - Documentation
- ∫ SymPy: Symbolic computation - Documentation
🔄 0.3. Python 2.7 vs 3.5+
While Python 2.7 was the final 2.x version, all future development focuses on Python 3. Key differences include:
- Print Function:
print "text"(2.7) vsprint("text")(3+) - Division:
9/5 = 1(2.7) vs9/5 = 1.8(3+) - Range:
xrange(2.7) vsrange(3+) - Unicode: ASCII default (2.7) vs Unicode default (3+)
Use from __future__ import ... for compatibility features in Python 2.7.
🔗 Additional Resources
- 🌐 Official Python: python.org
- 📖 Python 2 vs 3 Guide: Key Differences
- 🚀 Beginner's Choice: Python 2 or 3?
🚀 1. Using Python
Python executes programs or scripts, and can run interactively using a command interpreter (IDLE) or IPython. In educational settings, we prefer using Jupyter notebooks (formerly IPython notebooks) through a web browser (avoiding Internet Explorer).
💻 Python Environments & IDEs
- 🛠️ PyCharm: Popular IDE with code analysis, debugger, and web development tools
- 🔬 Spyder: Scientific computing IDE with interactive console and variable explorer
- ⚡ PyDev: Eclipse plugin with code completion and debugging
- 📊 Rodeo: Data science IDE with RStudio-like interface
- 📝 Sublime Text: Versatile editor with Python plugin support
- 🔧 LiClipse: Enhanced Eclipse IDE with Python support
- 🥷 Ninja IDE: Cross-platform IDE with debugger and code completion
- 🐉 Komodo IDE: Multi-language IDE with debugging and version control
We'll primarily use Jupyter Notebook - allowing you to save commands, do complex development, and maintain complete analysis history.
📓 Jupyter Notebook Features
Commands are grouped into cells with results displayed after execution. Notebooks are saved as .ipynb files and support:
- 📝 LaTeX integration for mathematical formulas
- 🎨 HTML tags and Markdown for layout
- 💾 Export to
.pyfiles for pure Python code extraction - 📄 Multiple formats: HTML, PDF, or slideshow presentations
- 🔧 Extensions: Available via jupyter-contrib-nbextensions
According to the Jupyter project, this environment supports multiple programming languages and is essential for ensuring reproducible analyses.
🎯 Getting Started
Open a Jupyter notebook by running this command in your terminal:
This will launch the notebook interface in your default web browser.
📝 Guidelines for Effective Notebook Use
While Jupyter notebooks are intuitive with self-explanatory tabs, here are some essential tips. For comprehensive tutorials, visit the Jupyter project site.
⌨️ Basic Workflow
- 📝 Enter Python commands in a cell
- ⚡ Execute with:
Shift + Enter- runs current cell and moves to nextCtrl + Enter- runs current cell and stays in place
- 📋 Add documentation using comment cells with HTML or Markdown
- 🔄 Iterate by adding cells as needed
💾 Export & Save Options
- 💾 Save the original
.ipynbnotebook file - 🌐 Export to HTML for web page sharing
- 🐍 Export to
.pyfor operational Python scripts
📁 Executing External Files
Run Python scripts (.py files) directly from within Jupyter using the magic command:
💡 Note: The script must be in the same directory as your current notebook.
# Run an external Python script
%run hello.py
🆘 Getting Help
Python provides built-in help features to explore functions, types, and modules. Use the help() function to get detailed information about any Python object.
📚 Using the Help Function
To get help on the int type in Python, use the following command in a Jupyter notebook or Python environment:
This displays comprehensive information about the int type, including its methods, attributes, and usage examples.
🔍 Other Help Methods
- ❓ Use
?after an object in Jupyter:int? - 📖 Use
??for source code:int?? - 📋 Use
dir()to list available methods:dir(int) - 📝 Use
.__doc__for documentation string:print(int.__doc__)
# Get help documentation
help(int)
# Inspect object details (Jupyter feature)
int?
🔄 Resetting Jupyter
The magic command %reset clears all variables from the current notebook session, giving you a fresh start without restarting the kernel.
⚡ Reset Commands
To reset the notebook with confirmation prompt:
To force reset without confirmation:
⚠️ Note: This clears all variables but keeps the kernel running with imported libraries intact.
🎯 When to Use Reset
- 🧹 Starting a fresh analysis with clean workspace
- 🔄 Testing code without previous variable interference
- 📊 Debugging variable-related issues
- 🚀 Preparing to demonstrate code from scratch
my_char1 = "Let's do the necessary."
print(my_char1)
# Reset all variables in the namespace
%reset
# Display the result
print(my_char1)
my_char2 = "Have we done it?"
print(my_char2)
# Reset all variables in the namespace
%reset -f
# Display the result
print(my_char2)
🔢 2. Data Types
2.0 Scalars and Strings
Variable declaration is implicit in Python (integer, float, boolean, string).
b = 2. # is a float
# Note:
a/2 # the result is 1.5 in Python 3.4
# but 1 in 2.7
a = 4 # is an integer
b = 2. # is a float
# Note:
a/2 # the result is 1.5 in Python 3.4
# but 1 in 2.7
⚖️ Comparison Operators
Comparison operators: ==, >, <, != return a boolean result (True or False).
a == b checks if the value of a is equal to the value of b.
b = 10
print(a == b) # This will print False because 5 is not equal to 10
# Comparison
a == b
🔍 Checking Variable Types
In Python, type(a) is used to determine the type of the variable a.
print(type(a)) # This will print <class 'int'>
b = 3.14
print(type(b)) # This will print <class 'float'>
c = "Hello"
print(type(c)) # This will print <class 'str'>
# Check the variable type
type(a)
🔗 String Concatenation
In Python, concatenating strings is straightforward using the + operator.
b = 'tout le '
c = 'monde'
d = 'la famille'
result = a + b + c
print(result) # This will print 'bonjour tout le monde'
# String concatenation
a = 'bonjour '
b = 'tout le '
c = 'monde'
d = 'la famille'
a + b + c
a + d
📋 2.1 Basic Structures
Lists
Lists allow combinations of different types.
📝 Note: The first element of a list is indexed by 0, not by 1.
liste_B = [0, 3, 209, 4025, 554, 6, 1]
liste_C = [0, 53, 562, 'rdv', [17, "l", 298, 43]]
### Initializing Lists
liste_A = [1, 34, 52, 'Slt']
liste_B = [0, 3, 209, 4025, 554, 6, 1]
liste_C = [0, 53, 562, 'rdv', [17, "l", 298, 43]]
📍 Accessing List Elements
Access elements in a list using indexing:
liste_A[1]
This returns 34, as indexing starts from 0.
# Entry of a list
liste_A[1]
liste_C[-1] # last entry
liste_C[3] = 45 # Modify an entry of the list
liste_C
🔄 Accessing Nested Lists
To access elements within a nested list, use multiple indices:
liste_C[-1][0]
This returns 17, as list_C[-1] refers to [17, "l", 298, 43].
# Access elements by index
liste_C[-1][0]
✂️ List Slicing
The expression liste_B[0:2] is used to create a sublist from liste_B, including elements from index 0 up to but not including index 2. In Python, slicing is performed using the format list[start:end], where start is the index to begin the slice (inclusive) and end is the index to end the slice (exclusive).
Creating a sublist from index 0 to 2 (not including 2)#
sous_liste = liste_B[0:2] print(sous_liste) # Output: [0, 3]
Here, sous_liste will contain the elements [0, 3], which are the elements at indices 0 and 1 of liste_B.
liste_B[0:2] # Sublist, runs throuh liste_B at the indices 0 and 1.
🎯 Slicing with Step
The expression liste_B[0:5:2] is used for slicing with a step. It extracts elements from liste_B starting at index 0, up to but not including index 5, with a step of 2.
In this case:
0is the starting index (inclusive).5is the ending index (exclusive).2is the step, meaning every second element is selected.
Slicing with start=0, end=5, and step=2#
sous_liste = liste_B[0:5:2] print(sous_liste) # Output: [0, 209, 554]
In this example, sous_liste contains [0, 209, 554], which are the elements at indices 0, 2, and 4 of liste_B.
liste_B[0:5:2] # start:end:step
What is happening here ?#
liste_B[::-1]# Understand what is happening here
🔄 Reversing a List
The expression liste_B[::-1] creates a reversed copy of the list.
liste_B = [0, 3, 209, 4025, 554, 6, 1]
# Reversing the list
reversed_list = liste_B[::-1]
print(reversed_list) # Output: [1, 6, 554, 4025, 209, 3, 0]
How it works:
start:omitted - defaults to beginning:endomitted - defaults to end::-1step of -1 reverses the order
# Methods on lists
List = [333,276,4827,187,984]
List.sort()
print(List)
List.append('hi') # Add an entry an the end
print(List)
List.count(3) # "Counts the number of times the entry '3' appears"
Observe the difference between the two methods .append() and .extend().#
List.extend([7,8,9])
print(List)
List.append([10,11,12])
print(List)
📦 Tuple
A tuple is similar to a list but cannot be modified; it is defined by parentheses.
MyTuple = (2020,34,42,'h')
MyTuple[1]
MyTuple[1] = 10 # TypeError: "tuple" object
# You cannot modify an entry in a tuple, unlike lists
📚 Dictionary
A dictionary is similar to a list, but each entry is assigned by a key/name and is defined with curly braces. This object is used for constructing column indexes (variables) of the DataFrame type in the pandas library.
months = {'Jan':31 , 'Feb': 29, 'Mar':31, 'Apr':30}
months['Apr']
🔑 Dictionary Methods
The methods .values(), .keys(), and .items() are very useful for working with dictionaries.
months.values()
months.keys()
months.items()
📊 Create a DataFrame with Pandas
To create a DataFrame with pandas, you can follow these steps:
1. Import pandas: First, ensure that you have pandas installed and import it into your Python environment.
2. Create a DataFrame: You can create a DataFrame using various methods such as from a dictionary, list of lists, or other data structures.
- From a dictionary:
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C']
}
df = pd.DataFrame(data)
- From a list of lists:
[1, 'A'],
[2, 'B'],
[3, 'C']
]
df = pd.DataFrame(data, columns=['Column1', 'Column2'])
- From a CSV file:
3. Inspect the DataFrame: Use methods to view the DataFrame and understand its structure.
print(df.info()) # Get a summary of the DataFrame
print(df.describe()) # Get statistical summaries of numerical columns
4. Manipulate the DataFrame: Perform operations such as filtering, sorting, and aggregating.
filtered_df = df[df['Column1'] > 1]
# Sorting by a column
sorted_df = df.sort_values(by='Column1')
# Adding a new column
df['NewColumn'] = df['Column1'] * 10
This basic overview should help you get started with creating and manipulating DataFrames in pandas.
import pandas as pd # Importing the pandas library with the alias "pd"
# Using lists and dictionaries.
# Gender and the number of hours spent in front of the TV.
# m = male; f = female
data = pd.DataFrame({
'Gender': ['f', 'f', 'm', 'f', 'm', 'm', 'f', 'm', 'f', 'f'],
'TV': [3.4, 3.5, 2.6, 4.7, 4.1, 4.0, 5.1, 4.0, 3.7, 2.1]})
data
🐍 3. Python Syntax
Here's an overview of basic Python syntax:
🔤 3.1 Variables and Data Types
- Variables: Store values. Python uses dynamic typing
- Data Types: Includes integers (
int), floating-point numbers (float), booleans (bool), and strings (str)
⚡ 3.2 Operators
- Arithmetic:
+,-,*,/,//,%,** - Comparison:
==,!=,>,<,>=,<= - Logical:
and,or,not
🔄 3.3 Control Flow
Conditional Statements:
# code block
elif another_condition:
# code block
else:
# code block
Loops:
# code block
while condition:
# code block
📞 3.4 Functions
# code block
return result
result = function_name(arguments)
🗂️ 3.5 Lists and Dictionaries
my_dict = {'key1': 'value1', 'key2': 'value2'}
🛡️ 3.6 Exception Handling
# code that might raise an exception
except ExceptionType as e:
# handle the exception
💬 3.7 Comments
'''
This is a multi-line comment
'''
📐 3.8 Indentation
Python uses indentation to define code blocks. Consistent indentation is crucial for defining scope in control flow statements and function definitions.
🔄 Conditional Structure
a = -23
if a > 0:
b = 0
print(b)
else:
b = -1
print(b)
# **If-Then-Else**
a = -23
if a > 0:
b = 0
print(b)
else:
b = -1
print(b)
🔄 Iterative Structure
print(i)
print(i)
# Loop through the sequence
for i in range(4):
print(i)
# Loop through the sequence
for i in range(1,8,2):
print(i)
📞 Functions
def pythagorus(x,y):
""" "Calculate the hypotenuse of a triangle" """
r = pow(x**2+y**2,0.5)
return x,y,r
pythagorus(5,6)
# Define the pythagorus() function
def pythagorus(x,y):
""" "Calculate the hypotenuse of a triangle" """
r = pow(x**2+y**2,0.5)
return x,y,r
pythagorus(5,6)
# Example of a call
pythagorus(x=5,y=7)
# integrated help
help(pythagorus)
pythagorus.__doc__
📦 Modules
A module is a file containing Python functions and commands, saved with a .py extension. You can import and use these functions in other scripts using the import command.
🧑🏫 Tutorial Steps:
Step 1: Create the Module File
Create a new text file and add the following functions:
print("Bonjour")
def DivPar2(x):
return x/2
Step 2: Save the Module
Save the file as testM.py in your current working directory.
Step 3: Import and Use
Now you can import all functions from this module in another Python script using:
testM.DitBonjour() # Output: Bonjour
result = testM.DivPar2(10) # Returns 5.0
import testM # import the module
testM.DitBonjour()
testM.DivPar2(7)
# Display the result
print(testM.DivPar2(10))
# We can also do
from testM import *
DitBonjour()
# Display the result
print(DivPar2(10))
# Or
import testM as tm
tm.DitBonjour()
print(tm.DivPar2(10))
# deletion of objects
# deletion of objects
%reset
from testM import DitBonjour
## Only one function has been called. Prefer this method for large libraries.
DitBonjour()
print(DivPar2(10)) # error
🔬 4. Scientific Computing
Here are three of the main libraries essential for scientific computing. Two other libraries: pandas and scikit-learn, are covered in detail in specific notebooks.
📦 4.0 Packages
🔢 NumPy
This library defines the array data type and the associated computation functions. It also includes some linear algebra and statistical functions. However, numerical functions are much more extensive in SciPy.
⚗️ SciPy
This library is a very comprehensive collection of modules for linear algebra, statistics, and other numerical algorithms. The documentation site provides a complete list.
📊 Matplotlib
This library offers visualization/graph functions with commands similar to those in Matlab. It is also known as pylab. The gallery of this library features a wide range of example plots with Python code to generate them.
# Import
import numpy as np
from pylab import *
gaussian = lambda x: np.exp(-(0.5-x)**2/1.5)
x=np.arange(-2,2.5,0.01)
y=gaussian(x)
plot(x,y)
xlabel("x values")
ylabel("y values")
title("Gaussian function")
show()
📊 4.1 Array Type
This is by far the most commonly used data structure for scientific computing in Python. It describes arrays or multi-index matrices of dimension \( n = 1, 2, 3, \ldots, 40 \). All elements are of the same type (boolean, integer, real, complex).
Data tables (data frames), which are the basis for statistical analysis and aggregate objects of different types, are described using the pandas library.
Definition of the array Type
# Import
import numpy as np
array_1d = np.array([44,33,22])
print(array_1d )
array_2d = np.array([[1,0,0],[0,2,0],[0,0,3]]) # rows & columns
print(array_2d)
my_list = [121,245,398,872]
my_array = np.array(my_list)
print(my_array)
a = np.array([[0,1],[2,3],[4,5]])
a[2,1]
# Access elements by index
a[:,1]
# Check the variable type
type(a[:,1])
Methods of type array#
np.arange(21)
np.ones(5)
np.ones((7,5))
np.eye(4)
np.linspace(3, 7, 3)
np.mgrid[0:3,0:2]
D = np.diag([111,202,904])
print(D)
print(np.diag(D))
M = np.array([[10*n+m for n in range(3)]
for m in range(2)])
print(M)
🎲 Random Matrix Generation
The numpy.random module provides a whole range of functions for generating random matrices.
from numpy import random
random.rand(7,3) # uniform sampling
random.randn(8,5) # **Sampling from the N(0,1) Distribution**
v = random.randn(1000)
import matplotlib.pyplot as plt
h = plt.hist(v,30) # **histogram with 30 Bins**
show()
Other functions#
a = np.array([[0,1],[2,3],[4,5]])
np.ndim(a) # Number of dimensions)
🔧 Array Functions
There are many functions you can test, including:
np.size(a)for the number of elementsnp.shape(a)which returns a tuple containing the dimensions ofanp.transpose(a)ora.Tfor the transposea.min()ornp.min(a)for the minimum valuea.sum()ornp.sum(a)for the sum of the values
and many other functions.
Operations on arrays#
# Sum
a = np.arange(6).reshape(3,2)
b = np.arange(3,9).reshape(3,2)
c = np.transpose(b)
a + b
a * b # term-by-term product (element-wise product)
np.dot(a,c) # matrix product (or dot product)
np.power(a,2)
In other notebooks that are fully developed on this topic, we will discuss the NumPy and SciPy libraries in more detail (should time permit). We conclude this introductory notebook with what we call programming structures, which form the backbone of this course.
Programming Structures#
Blocks are defined by indentation (usually by 4 spaces);
One statement per line generally (or statements separated by
;);Comments start with
#and extend to the end of the line;Boolean Expression: a condition is an expression that evaluates to
TrueorFalse:False: false logical test (e.g., 3 == 4), null value, empty string (‘’), empty list ([]), etc.,True: true logical test (e.g., 2 + 2 == 4), any non-null value or object (and thus evaluating to True by default except exceptions);Logical Tests:
==,!=,>,>=, etc.;Logical Operators:
and,or,not;Ternary Operator:
value **if** condition **else** value;
Conditional Expression:
**if** condition1 : ... [**elif** condition2 : ...] [**else**: ...];For Loop:
**for** element **in** iterable, executes on each element of an iterable object:continue: interrupts the current iteration and resumes the loop at the next iteration,break: completely interrupts the loop;
While Loop:
while condition: repeats as long as the condition is true, or after an explicit exit withbreak.
These structures will be discussed in detail in upcoming notebooks.
🏗️ Programming Structures
In other notebooks that are fully developed on this topic, we will discuss the NumPy and SciPy libraries in more detail (should time permit). We conclude this introductory notebook with what we call programming structures, which form the backbone of this course.
📐 Basic Syntax Rules
- Blocks are defined by indentation (usually by 4 spaces)
- One statement per line generally (or statements separated by
;) - Comments start with
#and extend to the end of the line
⚡ Boolean Expressions
False: false logical test (e.g., 3 == 4), null value, empty string (''), empty list ([]), etc.True: true logical test (e.g., 2 + 2 == 4), any non-null value or object- Logical Tests:
==,!=,>,>=, etc. - Logical Operators:
and,or,not - Ternary Operator:
value if condition else value
🔄 Control Structures
- Conditional Expression:
if condition1 : ... [elif condition2 : ...] [else: ...] - For Loop:
for element in iterable, executes on each element of an iterable object:continue: interrupts current iteration and resumes loopbreak: completely interrupts the loop
- While Loop:
while condition: repeats as long as condition is true, or after explicit exit withbreak
These structures will be discussed in detail in upcoming notebooks.
🎯 Key Takeaways
- Python is a high-level, interpreted language ideal for scientific computing and data science.
- Jupyter Notebooks provide an interactive environment combining code, text, and visualizations.
- Python supports multiple data types: integers, floats, strings, lists, tuples, and dictionaries.
- Functions are defined with
defand can accept arguments and return values. - NumPy and Matplotlib are essential libraries for numerical computing and plotting.
—
—