0% found this document useful (0 votes)
10 views35 pages

Cours Python

The document outlines an academic course on programming fundamentals and scientific computing using Python, aimed at first-year mathematics and computer science students at the University of Batna 2 for the academic year 2025-2026. It covers essential topics such as Python basics, syntax, control structures, and the use of Jupyter Notebook, along with practical exercises to reinforce learning. The course emphasizes the importance of Python in mathematical applications and includes a structured approach to learning programming concepts and tools.

Uploaded by

Abdoulaye Mbaye
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views35 pages

Cours Python

The document outlines an academic course on programming fundamentals and scientific computing using Python, aimed at first-year mathematics and computer science students at the University of Batna 2 for the academic year 2025-2026. It covers essential topics such as Python basics, syntax, control structures, and the use of Jupyter Notebook, along with practical exercises to reinforce learning. The course emphasizes the importance of Python in mathematical applications and includes a structured approach to learning programming concepts and tools.

Uploaded by

Abdoulaye Mbaye
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Z X

∇ ∂

Py
THON

FUNDAMENTALS OF
PROGRAMMING AND
SCIENTIFIC COMPUTING

WITH PYTHON

Dr. Nour El Houda GOLEA

Academic Course

1st YEAR COMMON CORE IN


MATHEMATICS & COMPUTER SCIENCE

MATHEMATICS
f (x) lim C R
2

University of Batna 2
Faculty of Mathematics and Computer Science

ACADEMIC YEAR
2025–2026

···

An introductory course to programming, algorithmic thinking,


and scientific computation for mathematics students,
using Python as the primary computational tool.

ACADEMIC EDITION
Contents

THEORETICAL COURSE 1

1 Introduction to Python for Mathematics 3


1.1 Why Python for Mathematics? . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 The Scientific Python Ecosystem . . . . . . . . . . . . . . . . . . . 4
1.2 The Anaconda Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.1 A Complete Scientific Platform . . . . . . . . . . . . . . . . . . . . 4
1.2.2 Installation Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Mastering Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 The Interactive Computing Paradigm . . . . . . . . . . . . . . . . . 5
1.3.2 Launching Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . 5
1.3.3 Cell Types and Operations . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 File Management in Windows . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.1 Essential Command-Line Navigation . . . . . . . . . . . . . . . . . 5
1.5 Your First Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Practice Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Basic Python Syntax 9


2.1 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.1 What are Variables? . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1.2 Basic Output with print() . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Basic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2.2 Comparison and Logical Operators . . . . . . . . . . . . . . . . . . 12
2.3 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3.1 Conditional Statements (if, elif, else) . . . . . . . . . . . . . . . . . 14
2.3.2 Loops: for and while . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.3 Loop Control Statements . . . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Practical Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

LABORATORY WORK 18

TP1: Getting Started with Python 21


1 Jupyter Notebook Installation . . . . . . . . . . . . . . . . . . . . . . . . . 21

3
CONTENTS Dr. N. GOLEA

2 Your First Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . . . . . 21


3 Basic Python Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5 Jupyter Notebook Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6 Notebook Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7 Submission Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
8 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
9 Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

TP2: Variables and Data Types 25


1 Basic Data Types in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2 Variable Declaration and Usage . . . . . . . . . . . . . . . . . . . . . . . . 25
3 Type Conversion Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4 User Input with input() Function . . . . . . . . . . . . . . . . . . . . . . . 27
5 Practical Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6 Notebook Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
7 Submission Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
8 Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

4
THEORETICAL COURSE
Python Programming Fundamentals

[ Chapter 1: Introduction to Programming


Overview of programming concepts, algorithms, and Python
basics
Ô Chapter 2: Basic Python Syntax
Variables, data types, operators, and basic input/output
Ð Chapter 3: Control Structures
Conditional statements, loops, and flow control
ò Chapter 4: Functions and Modules
Defining functions, parameters, return values, and modular
programming
õ Chapter 5: Data Structures
Lists, tuples, dictionaries, sets, and their operations
¢ Chapter 6: File Handling
Reading from and writing to files, data persistence
¨ Chapter 7: Object-Oriented Programming
Classes, objects, inheritance, and polymorphism
e Chapter 8: Error Handling and Debugging
Exceptions, debugging techniques, and testing
CONTENTS Dr. N. GOLEA

Learning Objectives
This theoretical course provides the foundation for understanding
programming concepts
and Python language features. Each chapter builds upon
previous knowledge to develop
a comprehensive understanding of Python for mathematical
applications.

Common Core in Mathematics & Computer Sci-


ence · Programming Fundamentals · Semester 2

Instructor: Dr. Nour El-Houda GOLEA


Contact: [Link]@[Link]

2
Chapter 1

Introduction to Python for Mathemat-


ics

ò INFORMATION
◎ Chapter Objectives
• Understand the fundamentals of Python and its ecosystem
• Install and configure the Anaconda scientific Python distribution
• Master Jupyter Notebook for interactive computing
• Write and execute your first Python program
• Organize your projects with effective file management

1.1 Why Python for Mathematics?


Python has emerged as the standard language for scientific computing and data science.
Created by Guido van Rossum in 1991, it combines simplicity with power, making
it ideal for mathematical exploration—from basic arithmetic to advanced computational
mathematics.
. IMPORTANT
Python’s Advantages for Mathematics:
• ¥ Readability: Clean syntax that reads like pseudocode
• ¥ Versatility: From simple scripts to complex simulations
• ¥ Ecosystem: Vast collection of scientific libraries
• ¥ Interactivity: Immediate feedback through Jupyter
• ¥ Community: Strong support from academia and industry

3
CHAPTER 1. INTRODUCTION TO PYTHON FOR MATHEMATICS Dr. N. GOLEA

1.1.1 The Scientific Python Ecosystem

NumPy SciPy Matplotlib


Numerical Computing Scientific Algorithms Visualization

3 Python
Core Language

pandas SymPy Jupyter


Data Analysis Symbolic Math Notebook

Figure 1.1: Scientific Python ecosystem: Essential libraries for mathematical


computing

1.2 The Anaconda Distribution


1.2.1 A Complete Scientific Platform

[ DEFINITION
Anaconda is a comprehensive distribution that includes:
• Ð Python 3.x - The core programming language
•  Jupyter Notebook - Interactive computing environment
• ò 250+ Packages - Pre-installed scientific libraries
• Ô Conda - Advanced package and environment manager

1.2.2 Installation Guide


1. Download: Visit  [Link]/download
2. Select: Choose Python 3.x for your operating system
3. Install: Run installer with recommended settings
4. Verify: Launch Anaconda Navigator from Start Menu
. IMPORTANT
Crucial Installation Steps:
• Check "Add Anaconda to my PATH environment variable"
• Select "Install for me only" (recommended)
• Verify installation by opening Anaconda Navigator

1.3 Mastering Jupyter Notebook

4
CHAPTER 1. INTRODUCTION TO PYTHON FOR MATHEMATICS Dr. N. GOLEA

1.3.1 The Interactive Computing Paradigm


Jupyter Notebook is an interactive environment that combines code, text, and visualizations
in a single document. Its cell-based structure allows you to execute Python code step by
step and see results immediately.

1.3.2 Launching Jupyter Notebook


1. Open Anaconda Navigator from Start Menu
2. Click Launch under Jupyter Notebook
3. Your web browser will open showing the Jupyter interface
4. Click New → Python 3 to create a new notebook

1.3.3 Cell Types and Operations

Table 1.1: Jupyter Notebook Cell Types and Operations


Cell Type Purpose Keyboard Shortcuts
Code Cell Execute Python code Shift+Enter (run)
Markdown Cell Formatted documentation Esc+M (convert)
# Navigation: Esc+A/B (insert above/below), Esc+D+D (delete cell)

1.4 File Management in Windows


1.4.1 Essential Command-Line Navigation

Table 1.2: Essential Windows Command Prompt Commands


Command Description Example
cd Display current directory cd
cd [path] Change directory cd Documents\Python
cd .. Move up one level cd ..
dir List directory contents dir
mkdir [name] Create new directory mkdir Project_Data

 EXAMPLE
Organized Project Structure Setup:
1 # Navigate to Desktop
2 cd Desktop
3

4 # Create organized project structure


5 mkdir " Py th on _M at he ma ti cs "
6 cd " Py th on _M at he ma ti cs "
7

8 # Launch Jupyter from working directory

5
CHAPTER 1. INTRODUCTION TO PYTHON FOR MATHEMATICS Dr. N. GOLEA

9 jupyter notebook

1.5 Your First Python Program

Figure 1.2: Jupyter Notebook interface with code execution and results.

1.6 Practice Exercise


X EXERCISE
Basic Calculator Program
• Create a new Jupyter Notebook
• Write a program that calculates:
– The sum of three numbers: 15, 27, and 42
– The product of 8 and 12
– The area of a rectangle with length 7 and width 4
– The average of the numbers 85, 92, and 78
• Display each result with a clear message

6
CHAPTER 1. INTRODUCTION TO PYTHON FOR MATHEMATICS Dr. N. GOLEA

Chapter Summary
. IMPORTANT
c Key Concepts Learned:
• 3 Python provides a powerful yet accessible platform for mathematical computing
• Ô Anaconda simplifies installation and dependency management
•  Jupyter Notebook enables interactive exploration and documentation
• i File Management is essential for productive workflow
• y Basic Programs can perform mathematical calculations

Next Chapter: Basic Python Syntax


• º Variables and Data Types: Integers, floats, strings, booleans
• y Basic Operations: Arithmetic, logical, and comparison operations
• Ñ Control Structures: Conditions (if, elif, else), loops (for, while)

End of
Chapter 1

7
CHAPTER 1. INTRODUCTION TO PYTHON FOR MATHEMATICS Dr. N. GOLEA

8
Chapter 2

Basic Python Syntax

ò INFORMATION
◎ Chapter Objectives
• Understand variables and data types
• Use arithmetic, comparison, and logical operators
• Write conditional statements (if, elif, else)
• Create loops (for, while) for repetition

2.1 Variables and Data Types


2.1.1 What are Variables?
A variable is a named storage location in memory that holds data.
[ DEFINITION
Variable Declaration:
• ù Use the assignment operator =
• U Choose a meaningful name
• Ö Store any type of data

2.1.2 Basic Output with print()


The print() function displays information on the screen.
 EXAMPLE
Example: Using print() function

Display text and variable values using the print() function.

1 # Basic print usage


2 print ( " Hello , Python ! " ) # Display text
3

4 # Print multiple items


5 name = " Ali "
6 age = 20
7 print ( " Name : " , name , " Age : " , age )
8

9 # Print with formatting


10 print ( f " Student : { name } , Age : { age } " )

9
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

_ OUTPUT
Output:

Hello, Python!
Name: Ali Age: 20
Student: Ali, Age: 20

[ DEFINITION
Data Types in Python:
• º int: Whole numbers: 5, -3, 0
• ÷ float: Decimals: 3.14, -0.5, 2.0
• k str: Text: "Hello", ’Python’
• § bool: True, False

Table 2.1: Python Data Types


Type Description Examples
int Whole numbers 42, -17, 0
float Decimal numbers 3.14, -0.5
str Text data "Hello", ’A’
bool Logical values True, False

 EXAMPLE
Example: Variable declaration and types

Declare variables of different types and display their values.

1 # Integer variable
2 students_count = 30
3 print ( " Students : " , students_count )
4 print ( " Type : " , type ( students_count ) )
5

6 # Float variable
7 average_grade = 15.5
8 print ( " Average : " , average_grade )
9 print ( " Type : " , type ( average_grade ) )
10

11 # String variable
12 course_name = " Mathematics "
13 print ( " Course : " , course_name )
14 print ( " Type : " , type ( course_name ) )
15

16 # Boolean variable
17 is_passed = True
18 print ( " Passed : " , is_passed )
19 print ( " Type : " , type ( is_passed ) )

10
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

_ OUTPUT
Output:

Students: 30
Type: <class 'int'>
Average: 15.5
Type: <class 'float'>
Course: Mathematics
Type: <class 'str'>
Passed: True
Type: <class 'bool'>

2.2 Basic Operations


2.2.1 Arithmetic Operators
Python supports standard mathematical operations.
Table 2.2: Arithmetic Operators
Operator Operation Example
+ Addition 7 + 3 = 10
- Subtraction 10 - 4 = 6
* Multiplication 5 * 6 = 30
/ Division 15 / 4 = 3.75
// Integer Division 15 // 4 = 3
% Modulo (Remainder) 15 % 4 = 3
** Exponentiation 2 ** 3 = 8

 EXAMPLE
Example: Arithmetic calculations

Perform basic arithmetic operations and display results.

1 # Define variables
2 a = 15
3 b = 4
4

5 # Perform calculations
6 addition = a + b
7 subtraction = a - b
8 multiplication = a * b
9 division = a / b
10 integer_division = a // b
11 remainder = a % b
12 power = a ** 2
13

14 # Display results
15 print ( f " { a } + { b } = { addition } " )

11
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

16 print ( f " { a } - { b } = { subtraction } " )


17 print ( f " { a } x { b } = { multiplication } " )
18 print ( f " { a } / { b } = { division } " )
19 print ( f " { a } // { b } = { integer_division } " )
20 print ( f " { a } % { b } = { remainder } " )
21 print ( f " { a }^2 = { power } " )

_ OUTPUT
Output:

15 + 4 = 19
15 - 4 = 11
15 x 4 = 60
15 / 4 = 3.75
15 // 4 = 3
15 % 4 = 3
152 = 225

2.2.2 Comparison and Logical Operators

Table 2.3: Comparison and Logical Operators


Operator Description Example
8 Comparison
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
> Greater than 5 > 3 → True
< Less than 5 < 3 → False
>= Greater or equal 5 >= 5 → True
<= Less or equal 3 <= 5 → True
¨ Logical
and Both conditions true True and False → False
or At least one true True or False → True
not Reverses the value not True → False

 EXAMPLE
Example: Comparison operations
Compare values and combine conditions with logical operators.

1 # Define variables
2 x = 10
3 y = 5
4 z = 10
5

6 # Comparison operations
7 print ( f " { x } == { y }: { x == y } " )

12
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

8 print ( f " { x } != { y }: { x != y } " )


9 print ( f " { x } > { y }: { x > y } " )
10 print ( f " { x } < { y }: { x < y } " )
11 print ( f " { x } >= { z }: { x >= z } " )
12 print ( f " { x } <= { z }: { x <= z } " )
13

14 # Logical operations
15 print ( f " ({ x } > 5) and ({ y } < 10) : {( x > 5) and ( y < 10) } " )
16 print ( f " ({ x } < 5) or ({ y } > 3) : {( x < 5) or ( y > 3) } " )
17 print ( f " not ({ x } == 10) : { not ( x == 10) } " )

_ OUTPUT
Output:

10 == 5: False
10 != 5: True
10 > 5: True
10 < 5: False
10 >= 10: True
10 <= 10: True
(10 > 5) and (5 < 10): True
(10 < 5) or (5 > 3): True
not (10 == 10): False

13
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

2.3 Control Structures


if-else Structure while Loop Structure

Start Loop Start

False
Condition? Condition? End

True False

True Code False Code True

Loop Body
Continue

Control Structures:
⋄ Condition - Checks a condition
Update
■ Process - Executes code
□ Update - Changes loop variable
Figure 2.1: Control structures in Python: if-else for decision making and while loop
for repetition

2.3.1 Conditional Statements (if, elif, else)


 EXAMPLE
Example: Grade classification
Classify a student’s grade into categories.

1 # Input grade
2 grade = 16.5
3

4 # Classify grade
5 if grade >= 16:
6 category = " Excellent "
7 elif grade >= 14:
8 category = " Very Good "
9 elif grade >= 12:
10 category = " Good "
11 elif grade >= 10:
12 category = " Satisfactory "
13 else :
14 category = " Fail "

14
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

15

16 # Display result
17 print ( f " Grade : { grade }/20 " )
18 print ( f " Category : { category } " )

_ OUTPUT
Output:

Grade: 16.5/20
Category: Excellent

2.3.2 Loops: for and while

 EXAMPLE
Example: for loop - display numbers
Use a for loop to display numbers from 1 to 5.

1 print ( " Numbers from 1 to 5: " )


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

_ OUTPUT
Output:

Numbers from 1 to 5:
1
2
3
4
5
 EXAMPLE
Example: while loop - countdown

Use a while loop for a countdown from 5 to 1.

1 count = 5
2 print ( " Countdown : " )
3 while count > 0:
4 print ( count )
5 count = count - 1
6 print ( " Go ! " )

_ OUTPUT
Output:

Countdown:
5
4
3
2

15
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

1
Go!

2.3.3 Loop Control Statements

 EXAMPLE
Example: break and continue
Use break to stop a loop and continue to skip iterations.

1 # Using break
2 print ( " Numbers until 5: " )
3 for i in range (1 , 10) :
4 if i == 6:
5 break
6 print ( i )
7

8 # Using continue
9 print ( " \ nEven numbers from 1 to 10: " )
10 for i in range (1 , 11) :
11 if i % 2 != 0: # Skip odd numbers
12 continue
13 print ( i )

_ OUTPUT
Output:

Numbers until 5:
1
2
3
4
5

Even numbers from 1 to 10:


2
4
6
8
10

2.4 Practical Exercise


X EXERCISE
Simple Calculator Create a program that:
1. Asks for two numbers
2. Asks for an operation (+, -, *, /)
3. Performs the calculation
4. Displays the result
Example execution:

16
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

First number: 10
Second number: 5
Operation (+, -, *, /): *
Result: 10 * 5 = 50

Chapter Summary
. IMPORTANT
c Key Concepts Learned:
• º Variables store data with meaningful names
• ¦ print() displays output to the screen
• ÷ Data types define what kind of data you’re working with
• y Operators perform calculations and comparisons
• Ñ Conditionals (if/elif/else) make decisions
• º Loops (for/while) repeat actions efficiently

Next Chapter: Functions and Modules


• Ð Functions: Definition, parameters, return values
• Ô Function Usage: Calls, arguments, modules
• g Modules: Import and create modules

End of
Chapter 2

17
LABORATORY WORK
Python Programming Laboratory

“ Lab 1: First Steps in Python


Introduction to programming environment, basic syntax, and
mathematical operations
õ Lab 2: Variables & Data Types
Mastering integers, floats, strings, and boolean types for
mathematical applications
Ñ Lab 3: Conditional Logic
Implementing decision-making structures for algorithm design
º Lab 4: Loops & Iteration
Automating repetitive tasks with for and while loops
Ô Lab 5: Functions & Modularity
Building reusable code blocks for complex calculations
¨ Lab 6: Data Structures
Organizing mathematical data efficiently with lists, tuples,
and dictionaries
CHAPTER 2. BASIC PYTHON SYNTAX Dr. N. GOLEA

Pedagogical Approach
This series of laboratory sessions is designed to develop
computational thinking
through incremental challenges, with each lab building upon
previous concepts.
 Learning by doing is our guiding principle.

Common Core in Mathematics & Computer Sci-


ence · Programming Fundamentals · Semester 2

Instructor: [Link] El Houda GOLEA


Contact: [Link]@[Link]

19
CONTINUOUS EVALUATION

Evaluation System
Continuous Assessment = Attendance (8pts) + Progress
Tracking
Progress Tracking per Lab:
⋆ Participation  Submission 4 Consultation
(star rating) (timely) (resources)

Œ Special Bonus Œ
Top 5 students in each group receive bonus on final exam

Submission Guidelines
Submit all work to your assigned instructor

Group Instructor Email


Group 15 & 16 Mr. Smail Raid [Link]@[Link]
Group 17 & 18 Mrs. Hadjazam Ouissam [Link]@[Link]
Group 19 & 20 Mrs. Touati Wahiba [Link]@[Link]

ò Important: Include name and group in subject


Format: GroupX_LastName_LabY

. Note: Late submissions will be penalized


TP1: Getting Started with Python

ò INFORMATION
Lab Objectives
• Install Anaconda and launch Jupyter Notebook
• Understand Jupyter Notebook interface and cells
• Write and execute Python code in Jupyter
• Learn basic Python syntax and operations

1 Jupyter Notebook Installation


 EXAMPLE
Installing Anaconda:
1. Download Anaconda from [Link]
2. Run the installer
3. Launch Jupyter Notebook from Anaconda Navigator

2 Your First Jupyter Notebook


 EXAMPLE
Creating Your First Notebook:
1. Open Jupyter Notebook
2. Click "New" → "Python 3"
3. In the first cell, write Python code
4. Press Shift+Enter to execute
1 # Try this in your first cell
2 print ( " Hello from Jupyter Notebook ! " )
3

4 # Simple calculation
5 result = 5 + 3
6 print ( " 5 + 3 = " , result )

3 Basic Python Operations


 EXAMPLE
Simple Calculations in Python:
1 # Basic arithmetic
2 x = 10
3 y = 3
4

5 print ( " Addition : " , x + y )


6 print ( " Subtraction : " , x - y )

21
TP1: GETTING STARTED WITH PYTHON Dr. N. GOLEA

7 print ( " Multiplication : " , x * y )


8 print ( " Division : " , x / y )

4 Exercises
X EXERCISE
Exercise 1: Personal Information
Create a Jupyter notebook with:
• Your name
• Your age
• Your university
• Your study program
Display each piece of information using the print() function.

X EXERCISE
Exercise 2: Simple Calculator
Create a notebook that calculates and displays:
• The sum of two numbers
• The difference between two numbers
• The product of two numbers
• The quotient of two numbers
Choose any numbers you like for the calculations.

X EXERCISE
Exercise 3: Temperature Converter
Create a program that converts:
• 25°C to Fahrenheit
• 77°F to Celsius
Use the formulas:
• Fahrenheit = (Celsius × 9/5) + 32
• Celsius = (Fahrenheit - 32) × 5/9

X EXERCISE
Exercise 4: Circle Calculator
Create a program that calculates:
• The area of a circle with radius 5
• The circumference of a circle with radius 5
Use the formulas:
• Area = pi × radius2
• Circumference = 2 × pi × radius
Use [Link] for pi.

22
TP1: GETTING STARTED WITH PYTHON Dr. N. GOLEA

5 Jupyter Notebook Tips


. IMPORTANT
Useful Shortcuts:
• Shift+Enter: Run current cell
• Ctrl+Enter: Run cell without moving to next
• Esc+A: Insert cell above
• Esc+B: Insert cell below
• Esc+M: Convert to Markdown cell
• Esc+Y: Convert to Code cell

. IMPORTANT
Common Operations:
• Restart Kernel: Kernel → Restart
• Save Notebook: File → Save or Ctrl+S
• Download as PDF: File → Download as → PDF
• Help: Type function_name? then run cell

6 Notebook Organization
 EXAMPLE
Suggested Notebook Structure:
# TP1: Getting Started with Python
[Your Name]
[Date]

## 1. Introduction
Brief description of what you will do

## 2. Exercise 1: Personal Information


[Your code here]

## 3. Exercise 2: Simple Calculator


[Your code here]

## 4. Exercise 3: Temperature Converter


[Your code here]

## 5. Exercise 4: Circle Calculator


[Your code here]

## 6. Conclusion
What you learned from this TP

23
TP1: GETTING STARTED WITH PYTHON Dr. N. GOLEA

7 Submission Requirements
. IMPORTANT
Á Submission Instructions:
• g Create folder: TP1_LastName_FirstName
• [ Save your notebook as: TP1_Exercises.ipynb
• P Export notebook as PDF: File → Download as → PDF
•  Compress folder: TP1_LastName_FirstName.zip
• # Submit by email to your instructor

8 Troubleshooting
• . Jupyter won’t start: Try jupyter notebook –no-browser
• º Kernel not responding: Kernel → Restart
• Ð Code not executing: Make sure cell type is "Code"
•  Import error: Make sure you have installed the package
• Ö Notebook not saving: Check file permissions

9 Additional Resources
• [ Jupyter Documentation: [Link]
• € Python Official Tutorial: [Link]
• ÷ Markdown Guide: [Link]
• ® Stack Overflow: [Link]

End of TP1

24
Lab 2: Variables and Data Types

ò INFORMATION
◎ Objectives
• Understand different data types in Python
• Learn to declare and use variables in Jupyter
• Practice type conversion operations
• Solve problems using variables and data types

1 Basic Data Types in Python


Table 2.4: Basic Python Data Types
Type Description Examples
int Integer (whole numbers) 5, -3, 0, 1000
float Floating-point (decimals) 3.14, -0.5, 2.0, 1.23e-4
str String (text) "Hello", ’Python’, "123"
bool Boolean (True/False) True, False

2 Variable Declaration and Usage


 EXAMPLE
Example: Working with Different Data Types
Declare variables of different types and explore their properties.

1 # Cell 1: Variable declaration


2 name = " Ahmed " # String
3 age = 21 # Integer
4 height = 1.75 # Float
5 is_student = True # Boolean
6 grades = [15.5 , 18.0 , 14.5] # List
7

8 # Cell 2: Display variables and types


9 print ( " Variable \ tValue \ t \ tType " )
10 print ( " -" * 40)
11 print ( f " name \ t \ t { name }\ t \ t { type ( name ) } " )
12 print ( f " age \ t \ t { age }\ t \ t { type ( age ) } " )
13 print ( f " height \ t \ t { height }\ t \ t { type ( height ) } " )
14 print ( f " is_student \ t { is_student }\ t { type ( is_student ) } " )
15 print ( f " grades \ t \ t { grades }\ t { type ( grades ) } " )

25
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

_ OUTPUT
Expected Output:

Variable Value Type


----------------------------------------
name Ahmed <class 'str'>
age 21 <class 'int'>
height 1.75 <class 'float'>
is_student True <class 'bool'>
grades [15.5, 18.0, 14.5] <class 'list'>

3 Type Conversion Operations


 EXAMPLE
Example: Type Conversion in Python
Convert between different data types using built-in functions.

1 # Cell 1: String to numeric conversion


2 num_str = " 123 "
3 num_int = int ( num_str ) # Convert to integer
4 num_float = float ( num_str ) # Convert to float
5

6 print ( f " Original string : '{ num_str } ' " )


7 print ( f " Converted to int : { num_int } , Type : { type ( num_int ) } " )
8 print ( f " Converted to float : { num_float } , Type : { type ( num_float ) } " )
9

10 # Cell 2: Numeric to string conversion


11 price = 99.99
12 quantity = 5
13 price_str = str ( price )
14 quantity_str = str ( quantity )
15

16 print ( f " \ nNumeric to string conversion : " )


17 print ( f " Price : { price } -> '{ price_str } ' ( type : { type ( price_str ) }) " )
18 print ( f " Quantity : { quantity } -> '{ quantity_str } ' ( type :
{ type ( quantity_str ) }) " )
19

20 # Cell 3: Boolean conversion


21 print ( f " \ nBoolean conversion : " )
22 print ( f " bool (0) = { bool (0) } " ) # False
23 print ( f " bool (1) = { bool (1) } " ) # True
24 print ( f " bool ( -1) = { bool ( -1) } " ) # True
25 print ( f " bool ( ' ') = { bool ( ' ') } " ) # False ( empty string )
26 print ( f " bool ( ' Hello ') = { bool ( ' Hello ') } " ) # True

_ OUTPUT
Expected Output:

Original string: '123'


Converted to int: 123, Type: <class 'int'>
Converted to float: 123.0, Type: <class 'float'>

26
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

Numeric to string conversion:


Price: 99.99 -> '99.99' (type: <class 'str'>)
Quantity: 5 -> '5' (type: <class 'str'>)

Boolean conversion:
bool(0) = False
bool(1) = True
bool(-1) = True
bool('') = False
bool('Hello') = True

4 User Input with input() Function


 EXAMPLE
Example: Interactive User Input
Get input from users and process different data types.

1 # Cell 1: Basic input with type conversion


2 print ( " === Student Information Form === " )
3 name = input ( " Enter your name : " )
4 age = int ( input ( " Enter your age : " ) )
5 height = float ( input ( " Enter your height ( m ) : " ) )
6 is_enrolled = input ( " Are you enrolled ? ( yes / no ) : " ) . lower () ==
' yes '
7

8 # Cell 2: Process and display information


9 print ( f " \ n === Student Profile === " )
10 print ( f " Name : { name } ( Type : { type ( name ) }) " )
11 print ( f " Age : { age } years ( Type : { type ( age ) }) " )
12 print ( f " Height : { height } m ( Type : { type ( height ) }) " )
13 print ( f " Enrolled : { is_enrolled } ( Type : { type ( is_enrolled ) }) " )
14

15 # Cell 3: Calculate year of birth


16 from datetime import datetime
17 current_year = datetime . now () . year
18 birth_year = current_year - age
19 print ( f " \ nEstimated birth year : { birth_year } " )

_ OUTPUT
Sample Output:
=== Student Information Form ===
Enter your name: Fatima
Enter your age: 22
Enter your height (m): 1.68
Are you enrolled? (yes/no): yes

=== Student Profile ===


Name: Fatima (Type: <class 'str'>)
Age: 22 years (Type: <class 'int'>)

27
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

Height: 1.68 m (Type: <class 'float'>)


Enrolled: True (Type: <class 'bool'>)

Estimated birth year: 2002

5 Practical Exercises
X EXERCISE
Exercise 1: Student Information System
Create a Jupyter notebook that:
1. Asks for student information: name, age, grade average, and major
2. Stores each piece of information in an appropriately typed variable
3. Displays the information in a formatted report
4. Calculates and displays:
• Year of birth
• Years until graduation (assuming 4-year program)
• Grade category (A: >=16, B: 14-15.9, C: 12-13.9, D: 10-11.9, F: <10)
Sample Output:

=== Student Information ===


Name: Mohamed
Age: 20 years
Major: Computer Science
Grade Average: 15.8/20
Grade Category: B

Calculations:
Year of Birth: 2004
Expected Graduation Year: 2026

X EXERCISE
Exercise 2: Unit Conversion Dashboard
Create a notebook with a unit conversion dashboard:
• Convert kilometers to miles (1 km = 0.621371 miles)
• Convert Celsius to Fahrenheit (F = C × 9/5 + 32)
• Convert kilograms to pounds (1 kg = 2.20462 lbs)
• Convert meters to feet (1 m = 3.28084 ft)
Requirements:
• Use input() to get values from user
• Perform conversions for all four units
• Display results in a table format
• Allow the user to choose which conversion to perform
Sample Output:

=== Unit Conversion Dashboard ===


1. Kilometers to Miles
2. Celsius to Fahrenheit

28
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

3. Kilograms to Pounds
4. Meters to Feet

Choose conversion (1-4): 2


Enter temperature in Celsius: 25
25.0°C = 77.0°F
X EXERCISE
Exercise 3: Geometric Calculator
Build a geometric calculator notebook that computes:
1. Rectangle area and perimeter
2. Circle area and circumference
3. Cylinder volume and surface area
4. Triangle area (using Heron’s formula for three sides)
Formulas:
• Circle area: A = πr2
• Circle circumference: C = 2πr
• Cylinder volume: V = πr2 h
p a+b+c
• Triangle area (Heron): A = s(s − a)(s − b)(s − c) where s = 2
Requirements:
• Use appropriate data types for each variable
• Include input validation
• Display results with units

X EXERCISE
Exercise 4: Statistics Calculator
Create a program that:
1. Asks for 5 numbers
2. Calculates and displays:
• Sum and average
• Minimum and maximum
• Range (max - min)
• Product of all numbers
• Data type statistics (how many integers, floats, etc.)
3. Converts all numbers to different types and displays the results
Advanced Challenge:
• Handle both integers and floats in input
• Detect and handle invalid input (non-numeric)
• Allow the user to choose how many numbers to enter

. IMPORTANT
 Jupyter Notebook Tips for TP2:
• Ð Use separate cells for different parts of each exercise
• × Add Markdown cells to explain your code
• O Use f-strings for formatted output
• ¥ Test type conversions in isolated cells
• . Handle potential errors with try-except blocks

29
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

6 Notebook Structure
 EXAMPLE
Recommended Notebook Structure for TP2:
Organize your TP2 notebook with clear sections

# TP2: Variables and Data Types


[Your Name]
[Date]

## 1. Exercise 1: Student Information


### 1.1 Code Implementation
[Code cells for input and processing]
### 1.2 Results
[Markdown with output explanation]

## 2. Exercise 2: Unit Conversion


### 2.1 Code Implementation
[Code cells for conversion functions]
### 2.2 Results
[Markdown with conversion examples]

## 3. Exercise 3: Geometric Calculator


[Similar structure...]

## 4. Exercise 4: Statistics Calculator


[Similar structure...]

## 5. Conclusion
[Summary and challenges faced]

7 Submission Requirements
. IMPORTANT
Á Submission Instructions:
• g Create folder: TP2_LastName_FirstName
• [ Save your notebook as: TP2_Exercises.ipynb
• P Export notebook as PDF: File → Download as → PDF
• D Include any additional Python files if needed
•  Compress folder: TP2_LastName_FirstName.zip
• # Submit by email to your TP instructor

8 Additional Resources
• [ Python Data Types: [Link]

30
TP2: VARIABLES AND DATA TYPES Dr. N. GOLEA

• € Type Conversion Tutorial: [Link]


asp
• Å Jupyter Input/Output: [Link]
• § Sample Notebooks: [Link]
source/examples/Notebook

End of TP2

31

You might also like