0% found this document useful (0 votes)
13 views26 pages

Poly

The document outlines a course on Foundations of Programming and Scientific Computing with Python, led by Prof. Toufik Messaoud Maarouk. It covers topics such as Python installation, basic syntax, control structures, functions, modules, and essential scientific libraries. The course includes practical examples and exercises to reinforce learning.

Uploaded by

yassine9999.dz
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)
13 views26 pages

Poly

The document outlines a course on Foundations of Programming and Scientific Computing with Python, led by Prof. Toufik Messaoud Maarouk. It covers topics such as Python installation, basic syntax, control structures, functions, modules, and essential scientific libraries. The course includes practical examples and exercises to reinforce learning.

Uploaded by

yassine9999.dz
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

Foundations of Programming and Scientific Computing with

Python

Prof. Toufik Messaoud Maarouk

March 7, 2026
Contents

1 Introduction 3
1.1 Installing Python and Development Environments . . . . . . . . . . . . . . . . . 3
1.1.1 Standard Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Anaconda Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 Development Environments . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Basic Python Syntax 5


2.1 First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.1 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.2 Floating Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.3 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.4 Boolean Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.5 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.6 Logic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4.1 The Print Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4.2 The Input Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.1 The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.2 The If-Else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.3 Multiple Conditions (If-Elif-Else) . . . . . . . . . . . . . . . . . . . . . . . 9
2.5.4 Logical Operators in Conditions . . . . . . . . . . . . . . . . . . . . . . . 9
2.6 Loops and Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.6.1 The For Loop and the range() Function . . . . . . . . . . . . . . . . . . . 10
2.6.2 Practical Example: Calculating Squares . . . . . . . . . . . . . . . . . . . 10
2.6.3 Cumulative Loops (Summation) . . . . . . . . . . . . . . . . . . . . . . . 10
2.6.4 Practice Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.6.5 The While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6.6 Advanced Loop Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.7 Data Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.8 Data Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.9 Comprehensive Exercise: Control Structures . . . . . . . . . . . . . . . . . . . . . 13

3 Functions and Modules 14


3.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.1.1 Defining Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.1.2 Functions Without Return Values . . . . . . . . . . . . . . . . . . . . . . 14
3.1.3 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1.4 Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1
3.1.5 Keyword (Named) Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1.6 Mixing Positional and Keyword Arguments . . . . . . . . . . . . . . . . . 16
3.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.1 Importing Standard Modules . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.2 Using Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.3 Creating and Importing Custom Modules . . . . . . . . . . . . . . . . . . 17
3.3 Practical Example: Creating a Scientific Module . . . . . . . . . . . . . . . . . . 17
3.3.1 The Module: scientific_tools.py . . . . . . . . . . . . . . . . . . . . . 17
3.3.2 The Main Program: [Link] . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.4 Essential Scientific Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.4.1 The math Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.4.2 The numpy Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.4.3 The scipy Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4.4 The matplotlib Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5 Exercise 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.6 Exercise 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.7 Exercise 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.8 Exercise 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.9 Exercise 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.10 Exercise 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.11 Exercise 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.12 Exercise 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.13 Exercise 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.14 Exercise 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.15 Solution 1: Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.16 Solution 2: Fibonacci Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.17 Solution 3: Mean of a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.18 Solution 4: Prime Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.19 Solution 5: Count Vowels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.20 Solution 6: Reverse String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.21 Solution 7: Celsius to Fahrenheit . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.22 Solution 8: Max and Min in a List . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.23 Solution 9: Even Numbers 1 to 100 . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.24 Solution 10: Simple Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2
Chapter 1

Introduction

Python is one of the most widely used programming languages in scientific computing, artificial
intelligence, and data analysis. Its clear syntax and extensive ecosystem of scientific libraries
make it ideal for students beginning programming.
This course introduces the fundamental concepts of programming using Python and demon-
strates how Python can be used to solve mathematical and scientific problems.
Main objectives:

• Understand the basic principles of programming

• Learn Python syntax and programming structures

• Apply programming to mathematical problems

• Use scientific libraries such as NumPy and Matplotlib

1.1 Installing Python and Development Environments


Python can be downloaded from:
[Link]
Two main installation methods exist:

1.1.1 Standard Installation


Download the installer for your operating system and follow the installation steps.
Important: during installation, check the option:
"Add Python to PATH"

1.1.2 Anaconda Distribution


Anaconda includes:

• Python

• NumPy

• SciPy

• Matplotlib

• Jupyter Notebook

This distribution is commonly used in scientific computing.

3
1.1.3 Development Environments
Several IDEs can be used:

• IDLE

• Visual Studio Code

• Spyder

• PyCharm

• Jupyter Notebook

4
Chapter 2

Basic Python Syntax

2.1 First Program


A simple Python program prints text to the console. This is usually the first program beginners
write.
1 # Print a message to the screen
2 print ( " Hello ␣ World " )

2.2 Variables
Variables are used to store values in memory. You can use them later in calculations or other
operations.
1 # Assign values to variables
2 a = 5 # integer
3 b = 10 # integer
4
5 # Perform arithmetic operation
6 c = a + b # add a and b
7
8 # Display the result
9 print ( c ) # output : 15

2.3 Data Types


Python supports multiple data types. Understanding data types is important because operations
can behave differently depending on the type.

2.3.1 Integers
Integers are whole numbers without a fractional part.
1 x = 10
2 print ( x ) # output : 10
3 print ( type ( x ) ) # shows the type of x , output : < class ’ int ’>

2.3.2 Floating Point Numbers


Floating point numbers are numbers with decimal points.

5
1 y = 3.14
2 print ( y ) # output : 3.14
3 print ( type ( y ) ) # output : < class ’ float ’>

2.3.3 Strings
Strings are sequences of characters, used to represent text.
1 name = " Alice "
2 print ( name ) # output : Alice
3 print ( type ( name ) ) # output : < class ’ str ’>

2.3.4 Boolean Values


Boolean values are either True or False, often used in conditions and logical operations.
1 a = True
2 b = False
3
4 print ( a ) # output : True
5 print ( b ) # output : False
6 print ( type ( a ) ) # output : < class ’ bool ’>

2.3.5 Arithmetic Operations


Python provides standard arithmetic operators.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
% Modulus

Example:
1 a = 5
2 b = 2
3
4 print ( a + b )
5 print ( a * b )
6 print ( a ** b )

2.3.6 Logic Operators


Python provides standard comparison/logic operators.

6
Operator Meaning Example Result
== Equals 5+3 == 8 True
!= Does not equal 3.2 != 2.5 True
< Less than 10 < 5 False
> Greater than 10 > 5 True
<= Less or equal 126 <= 100 False
>= Greater or equal 5.9 >= 5.0 True
and Conjunction 9 != 6 and 2 < 3 True
or Disjunction 2 == 3 or -1 < 5 True
not Negation not 7 > 0 False

2.4 Input and Output


Interaction between the user and the program is fundamental in programming. Python provides
built-in functions to display data to the console and to retrieve information from the user.

2.4.1 The Print Function


The print() function is used to output data to the standard output device (usually the screen).
It can take multiple arguments of different types, separating them by spaces by default.
1 # Displaying a string literal
2 print ( " Foundations ␣ of ␣ Programming " )
3
4 # Displaying a numeric value
5 print (1024)
6
7 # Displaying multiple items ( automatically separated by a space )
8 course_name = " Python "
9 version = 3.12
10 print ( " Course : " , course_name , " Version : " , version )

• Text strings must be enclosed in quotes (" ").

• Variables are passed directly without quotes to display their stored value.

2.4.2 The Input Function


To allow users to provide data to a program, we use the input() function. This function pauses
the program’s execution, displays an optional prompt message, and waits for the user to type
something and press Enter.
1 # The prompt is displayed to the user
2 name = input ( " Enter ␣ your ␣ name : ␣ " )
3
4 # The value entered is stored in the variable ’ name ’
5 print ( " Welcome ␣ to ␣ the ␣ course , " , name )

Important Note: Data Types

By default, the input() function always returns data as a String (str). If you need
to perform mathematical operations on the input, you must convert it using int() or
float().

7
1 # Reading a number and converting it to an integer
2 age = int ( input ( " Enter ␣ your ␣ age : ␣ " ) )
3
4 # Now we can perform calculations
5 next_year = age + 1
6 print ( " Next ␣ year ␣ you ␣ will ␣ be : " , next_year )

2.5 Control Structures


Control structures allow a program to make decisions and execute different blocks of code based
on specific conditions. In Python, these blocks are defined by indentation (usually 4 spaces or
one tab).

2.5.1 The If Statement


The if statement is the simplest control structure. It executes a block of code only if the
specified condition evaluates to True.

General Syntax
if condition:
# block of code executed if True

1 age = int ( input ( " Enter ␣ age : ␣ " ) ) # Let ’s assume the user enters 20
2
3 if age >= 18:
4 # This line only runs if age is 18 or more
5 print ( " You ␣ are ␣ an ␣ Adult " )
6
7 # Output :
8 # You are an Adult

2.5.2 The If-Else Statement


The if-else structure provides an alternative path. It ensures that one of two blocks will
always be executed.

General Syntax
if condition:
# block if True
else:
# block if False

1 # Assuming age is 15
2 if age >= 18:
3 print ( " Status : ␣ Adult " )
4 else :
5 # This runs if age is less than 18
6 print ( " Status : ␣ Minor " )
7
8 # Output :
9 # Status : Minor

8
2.5.3 Multiple Conditions (If-Elif-Else)
When you have more than two possible paths, use the elif keyword. Python checks conditions
from top to bottom.

General Syntax
if condition1:
# block 1
elif condition2:
# block 2
else:
# final fallback block

1 grade = float ( input ( " Enter ␣ your ␣ grade ␣ (0 -20) : ␣ " ) ) # Let ’s assume 14.5
2
3 if grade >= 16:
4 print ( " Result : ␣ Excellent " )
5 elif grade >= 12:
6 print ( " Result : ␣ Good " )
7 elif grade >= 10:
8 print ( " Result : ␣ Pass " )
9 else :
10 print ( " Result : ␣ Fail " )
11
12 # Output :
13 # Result : Good

Syntax Reminder

Don’t forget the colon (:) at the end of every if, elif, and else line. Forgetting this
is a very frequent syntax error for beginners!

2.5.4 Logical Operators in Conditions


You can combine multiple conditions using logical operators:
• and: True if both conditions are true.
• or: True if at least one condition is true.
• not: Reverses the result of the condition.

1 age = 20
2 has_license = True
3
4 if age >= 18 and has_license :
5 print ( " You ␣ are ␣ allowed ␣ to ␣ drive . " )
6
7 # Output :
8 # You are allowed to drive .

2.6 Loops and Iteration


In scientific computing, we often need to repeat a specific calculation multiple times. Python
provides two main types of loops: for and while.

9
2.6.1 The For Loop and the range() Function
The for loop is used to iterate over a sequence.

General Syntax
for variable in sequence:
# block of code to repeat

1 # Iterates from 0 to 4 (5 is excluded )


2 for i in range (5) :
3 print ( i )
4
5 # Output :
6 # 0
7 # 1
8 # 2
9 # 3
10 # 4

2.6.2 Practical Example: Calculating Squares

1 # range (1 , 6) generates numbers : 1 , 2 , 3 , 4 , 5


2 for x in range (1 , 6) :
3 print (x , " squared ␣ is " , x * x )
4
5 # Output :
6 # 1 squared is 1
7 # 2 squared is 4
8 # 3 squared is 9
9 # 4 squared is 16
10 # 5 squared is 25

2.6.3 Cumulative Loops (Summation)

1 sum_total = 0
2 # Calculating the sum of integers from 0 to 10
3 for i in range (11) :
4 sum_total += i # Equivalent to sum_total = sum_total + i
5
6 print ( " The ␣ final ␣ sum ␣ is : " , sum_total )
7
8 # Output :
9 # The final sum is : 55

Coding Tip

Always initialize your accumulator (sum = 0 or product = 1) outside and before the
loop.

2.6.4 Practice Exercises


Exercise: Calculating the Factorial
Write a Python program that calculates the product of the first 20 integers (i.e., 20!).

10
Exercise Challenge

Try to solve this using two different approaches:

1. A standard for loop with an accumulator variable.

2. A compact approach using the built-in library math.

Solution 1: Standard Loop Approach


In this approach, we initialize an accumulator variable to 1 and multiply it by each integer in
the range.
1 product = 1
2
3 # We use range (1 , 21) because the stop value is exclusive
4 for i in range (1 , 21) :
5 product *= i # Equivalent to : product = product * i
6

7 print ( " The ␣ product ␣ of ␣ the ␣ first ␣ 20 ␣ values ␣ is : " , product )


8
9 # Output :
10 # The product of the first 20 values is : 24 3 2 90 2 0 08 1 7 66 4 0 0 00

Solution 2: Compact Approach


Python’s standard library provides highly optimized functions for common mathematical oper-
ations, such as [Link]().
1 import math
2
3 # Using the optimized math . prod function
4 result = math . prod ( range (1 , 21) )
5
6 print ( " The ␣ product ␣ of ␣ the ␣ first ␣ 20 ␣ values ␣ is : " , result )
7
8 # Output :
9 # The product of the first 20 values is : 24 3 2 90 2 0 08 1 7 66 4 0 0 00

2.6.5 The While Loop


The while loop repeats a block as long as a condition remains True.

General Syntax
while condition:
# block of code to repeat
# (must include a step to change the condition)

1 n = 1
2 # This loop doubles n until it reaches or exceeds 100
3 while n < 100:
4 print ( n )
5 n = n * 2 # Update step
6
7 # Output :

11
8 # 1
9 # 2
10 # 4
11 # 8
12 # 16
13 # 32
14 # 64

Warning: Infinite Loops

In a while loop, you must ensure that the condition eventually becomes False.

2.6.6 Advanced Loop Control


Sometimes, you need to modify the normal behavior of a loop. Python provides three specific
keywords for this purpose:

• break: Immediately terminates the loop.

• continue: Skips the current iteration and jumps to the next one.

• pass: A null statement; it does nothing and is used as a placeholder.

2.7 Data Type Conversion


Often, the data you receive (like user input) must be converted to a specific format for calcula-
tion.

General Syntax
int(value) – Converts to integer
float(value) – Converts to floating point

1 # Conversion examples
2 print ( int (2.5347) ) # Output : 2
3 print ( float (2) ) # Output : 2.0

2.8 Data Formatting


To present data cleanly, Python uses formatting operators (the modulo symbol %) within strings.

• %d: Used for integers.

• %s: Used for strings.

• %.nf: Used for floats, where n is the number of decimal places.

1 age = 10
2 print ( " Ali ␣ is ␣ % d ␣ years ␣ old " % age )
3 # Output : Ali is 10 years old
4
5 name = " Ali "
6 print ( " Applicant : ␣ % s " % name )

12
7 # Output : Applicant : Ali
8

9 a = 179.49599
10 print ( " %.2 f " % a ) # Output : 179.50
11 print ( " %.4 f " % a ) # Output : 179.4960

2.9 Comprehensive Exercise: Control Structures


Challenge

Write a program that:

1. Requests a positive integer n (validating with a while loop).

2. Creates a list of numbers from 1 to n.

3. Calculates the total sum and counts even/odd numbers.

4. Categorizes each number as Zero, Even, or Odd.

1 n = int ( input ( " Enter ␣ a ␣ positive ␣ integer : ␣ " ) )


2
3 # 1. Validation loop
4 while n <= 0:
5 n = int ( input ( " Invalid . ␣ Please ␣ enter ␣ a ␣ positive ␣ integer : ␣ " ) )
6
7 # 2. Preparation
8 numbers = list ( range (1 , n + 1) )
9 sum_values =0
10 even_count =0
11 odd_count =0
12
13 # 3. Iteration and logic
14 for x in numbers :
15 sum_values += x
16 if x == 0:
17 print (x , " = ␣ Zero " )
18 elif x % 2 == 0:
19 print (x , " = ␣ Even " )
20 even_count += 1
21 else :
22 print (x , " = ␣ Odd " )
23 odd_count += 1
24
25 # 4. Display results
26 print ( " \ nSum ␣ = " , sum_values )
27 print ( " Even ␣ numbers ␣ = " , even_count )
28 print ( " Odd ␣ numbers ␣ = " , odd_count )

13
Chapter 3

Functions and Modules

3.1 Functions
A function is a reusable block of code designed to perform a specific task. By breaking a complex
program into smaller functions, your code becomes easier to read, test, and maintain.

3.1.1 Defining Functions


To define a function, we use the def keyword.

General Syntax
def function_name(param1, param2, ...):
# block of instructions
return value

Parameters and Return Values


Parameters act as local variables that receive values passed into the function when it is called.
1 def addition (a , b ) :
2 result = a + b
3 return result
4
5 # Calling the function
6 sum_result = addition (5 , 3)
7 print ( sum_result )
8

9 # Output :
10 # 8

3.1.2 Functions Without Return Values


Sometimes a function performs an action (like printing to the console) rather than returning a
value. In Python, if a function does not have a return statement, it implicitly returns None.
1 def greet ( name ) :
2 print ( f " Hello ␣ { name }! " )
3
4 greet ( " Alice " )
5
6 # Output :
7 # Hello Alice !

14
3.1.3 Calling Functions
Once defined, a function remains inactive until it is called by its name, followed by parentheses
containing the necessary arguments.
1 def greet ( name ) :
2 print ( f " Hello ␣ { name }! " )
3
4 greet ( " Alice " )
5 greet ( " Bob " )
6

7 # Output :
8 # Hello Alice !
9 # Hello Bob !

3.1.4 Default Arguments


Python offers flexible ways to pass arguments to functions, which is highly useful in scientific
computing.

• Default Arguments: Used when a caller doesn’t provide a value.

• Keyword (Named) Arguments: Passed by parameter name, allowing you to change


the order.

You can assign default values to parameters in a function definition. This allows the function
to be called with fewer arguments than it has parameters.

General Syntax
def func(param1=default_value):
# block of code

1 def greet ( name = " Guest " ) :


2 print ( f " Hello ␣ { name }! " )
3
4 greet () # Uses default " Guest "
5 greet ( " Alice " ) # Uses " Alice "
6
7 # Output :
8 # Hello Guest !
9 # Hello Alice !

3.1.5 Keyword (Named) Arguments


Arguments can be passed by explicitly naming the parameter. This enhances readability and
allows you to call arguments in any order.
1 def describe_person ( name , age , city ) :
2 print ( f " { name } ␣ is ␣ { age } ␣ years ␣ old ␣ and ␣ lives ␣ in ␣ { city }. " )
3
4 # Arguments passed by name
5 describe_person ( age =30 , city = " Paris " , name = " Alice " )
6
7 # Output :
8 # Alice is 30 years old and lives in Paris .

15
3.1.6 Mixing Positional and Keyword Arguments
When combining both, positional arguments must always come before keyword argu-
ments.
1 def add_numbers (a , b , c =0) :
2 return a + b + c
3
4 print ( add_numbers (5 , 3) ) # c defaults to 0 -> 8
5 print ( add_numbers (5 , 3 , c =2) ) # c is specified -> 10
6 print ( add_numbers ( a =2 , b =3) ) # positional a , b as keywords -> 5
7
8 # Output :
9 # 8
10 # 10
11 # 5

Syntax Rule

If you pass a keyword argument before a positional argument (e.g., add_numbers(a=2,


3)), Python will raise a SyntaxError. Always follow: Positional → Keyword.

3.2 Modules
A module is simply a file containing Python code (definitions and functions) that can be reused
in other scripts. Python’s power lies in its massive library ecosystem, allowing you to extend
the language’s capabilities significantly.

3.2.1 Importing Standard Modules


To use functionality from a module, you must import it using the import keyword.

General Syntax
import module_name
from module_name import function_name

1 import math
2
3 print ( math . sqrt (16) ) # Output : 4.0
4 print ( math . pi ) # Output : 3.14 15926 535897 93
5

6 # Importing only a specific function


7 from math import factorial
8 print ( factorial (5) ) # Output : 120

3.2.2 Using Aliases


For modules with long names or those used frequently (like NumPy), we use aliases to make the
code more concise.
1 import numpy as np
2

3 # We use ’ np ’ instead of typing ’ numpy ’ every time


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

16
5 print ( arr ) # Output : [1 2 3]

3.2.3 Creating and Importing Custom Modules


You can organize your own code by saving functions in a separate file (e.g., [Link]). This
helps keep your main script clean and modular.
Step 1: Create the module ([Link])
1 def greet ( name ) :
2 print ( f " Hello ␣ { name }! " )
3
4 def add (a , b ) :
5 return a + b

Step 2: Use the module in your main script ([Link])


1 import mymodule
2
3 mymodule . greet ( " Alice " ) # Output : Hello Alice !
4 result = mymodule . add (5 , 3)
5 print ( result ) # Output : 8

Important Note

For the import to work, [Link] must be in the same directory as your main
script. If you move your module, Python will raise a ModuleNotFoundError.

3.3 Practical Example: Creating a Scientific Module


To fully understand the benefits of modularity, we will create a reusable scientific tool named
scientific_tools.py containing frequently used mathematical functions.

3.3.1 The Module: scientific_tools.py


This file contains five distinct functions that we can call from any other script.
1 def calculate_mean ( data_list ) :
2 # """ Calculates the mean of a list of numbers ."""
3 return sum ( data_list ) / len ( data_list )
4
5 def is_even ( n ) :
6 # """ Returns True if the number is even , False otherwise ."""
7 return n % 2 == 0
8
9 def power (n , p =2) :
10 # """ Calculates n to the power of p ( default is 2) ."""
11 return n ** p
12
13 def is_prime ( n ) :
14 """ Checks if a number is prime . """
15 if n < 2: return False
16 for i in range (2 , int ( n **0.5) + 1) :
17 if n % i == 0:
18 return False
19

20 return True

17
21
22 def c e l s i u s _ t o _ f a h r e n h e i t ( c ) :
23 # """ Converts Celsius degrees to Fahrenheit ."""
24 return ( c * 9/5) + 32

3.3.2 The Main Program: [Link]


Here is how to import and use this module in your main program using an alias.
1 import scientific_tools as st
2
3 # Using functions via the ’ st ’ alias
4 data = [10 , 20 , 30 , 40]
5 print ( " Mean : " , st . calculate_mean ( data ) ) # Output : 25.0
6
7 print ( " Is ␣ 7 ␣ even ? " , st . is_even (7) ) # Output : False
8 print ( " 5 ␣ squared : " , st . power (5) ) # Output : 25
9 print ( " Is ␣ 17 ␣ prime ? " , st . is_prime (17) ) # Output : True
10 print ( " 20 C ␣ in ␣ Fahrenheit : " , st . c e l s i u s _ t o _ f a h r e n h e i t (20) ) # Output : 68.0

Why use this structure?

• Readability: Your main code ([Link]) stays clean and lightweight.

• Reusability: You can copy scientific_tools.py into all your future projects.

• Organization: Business logic is separated from tests and user interface.

3.4 Essential Scientific Libraries


Python is a premier language for scientific computing because of its vast ecosystem of specialized
libraries. Below are the four most fundamental modules for any scientist or engineer.

3.4.1 The math Module


The math module is part of Python’s standard library. It provides access to mathematical
functions defined by the C standard.
1 import math
2
3 print ( math . sqrt (25) ) # Square root -> 5.0
4 print ( math . log10 (100) ) # Logarithm base 10 -> 2.0
5 print ( math . sin ( math . pi /2) ) # Trigonometry ( in radians ) -> 1.0
6 print ( math . factorial (4) ) # Factorial (4*3*2*1) -> 24

3.4.2 The numpy Module


NumPy is the cornerstone of numerical computing. It introduces the array object, which allows
for high-performance mathematical operations on entire datasets at once (vectorization).
1 import numpy as np
2
3 arr = np . array ([1 , 2 , 3 , 4])
4
5 # Vectorized operation

18
6 print ( arr * 2) # Multiplies all elements -> [2 , 4 , 6 , 8]
7 print ( np . mean ( arr ) ) # Mean -> 2.5

3.4.3 The scipy Module


Built on top of NumPy, SciPy provides advanced scientific algorithms like integration, optimiza-
tion, and signal processing.
1 from scipy import integrate
2
3 # Integrate f ( x ) = x ^2 from 0 to 1
4 result , error = integrate . quad ( lambda x : x **2 , 0 , 1)
5 print ( result ) # Output : 0.3333

3.4.4 The matplotlib Module


Mathematical results are best understood when visualized. [Link] is the standard
library for plotting graphs and charts.
1 import matplotlib . pyplot as plt
2 import numpy as np
3
4 x = np . linspace (0 , 10 , 100) # 100 points between 0 and 10
5 y = np . sin ( x )
6
7 plt . plot (x , y , label = ’ Sine ␣ Wave ’)
8 plt . title ( " Mathematical ␣ Function ␣ Plot " )
9 plt . show ()

19
The following table summarizes 15 key modules commonly used in academic and practical
projects. Each module is listed with its primary purpose and typical use cases to help students
and practitioners quickly understand their role in Python programming.

Module Purpose Use Case


math Scalar Math Basic constants and functions
numpy Arrays Matrix operations, Data processing
scipy Algorithms Integration, Optimization
matplotlib Visualization Plotting curves and data
pandas Data Analysis Data manipulation and analysis
sympy Symbolic Math Algebraic computations and calculus
statistics Statistics Mean, median, variance calculations
random Random Generation Random numbers and simulations
seaborn Statistical Visualization Advanced statistical plots
sklearn Machine Learning Classification and regression models
networkx Graph Theory Graph and network analysis
cv2 Computer Vision Image processing and computer vision
tensorflow Deep Learning Neural networks and AI models
torch Deep Learning Machine learning with tensors
jupyter Interactive Computing Notebook-based coding and experiments

20
Exercises

3.5 Exercise 1
Write a program computing the factorial of an integer.

3.6 Exercise 2
Write a program generating the Fibonacci sequence up to a given number of terms.

3.7 Exercise 3
Compute the mean of a list of numbers entered by the user.

3.8 Exercise 4
Write a program that checks if a given number is prime or not.

3.9 Exercise 5
Create a program that counts how many vowels are in a given string.

3.10 Exercise 6
Write a program to reverse a string entered by the user.

3.11 Exercise 7
Write a function that converts temperatures from Celsius to Fahrenheit.

3.12 Exercise 8
Write a program that finds the maximum and minimum values in a list of numbers.

3.13 Exercise 9
Create a program that prints all even numbers between 1 and 100 using a loop.

21
3.14 Exercise 10
Write a program that simulates a simple calculator using functions and ‘if-else‘ statements.
Operations: addition, subtraction, multiplication, division.

22
Solutions

3.15 Solution 1: Factorial

1 n = int ( input ( " Enter ␣ an ␣ integer : ␣ " ) )


2 factorial = 1
3 for i in range (1 , n +1) :
4 factorial *= i
5 print ( " Factorial : " , factorial )

3.16 Solution 2: Fibonacci Sequence

1 n_terms = int ( input ( " Number ␣ of ␣ terms : ␣ " ) )


2 a, b = 0, 1
3 for _ in range ( n_terms ) :
4 print (a , end = ’␣ ’)
5 a, b = b, a + b

3.17 Solution 3: Mean of a List

1 numbers = input ( " Enter ␣ numbers ␣ separated ␣ by ␣ spaces : ␣ " ) . split ()


2 numbers = [ float ( num ) for num in numbers ]
3 mean = sum ( numbers ) / len ( numbers )
4 print ( " Mean : " , mean )

3.18 Solution 4: Prime Check

1 num = int ( input ( " Enter ␣ a ␣ number : ␣ " ) )


2 if num > 1:
3 for i in range (2 , int ( num **0.5) +1) :
4 if num % i == 0:
5 print ( " Not ␣ prime " )
6 break
7 else :
8 print ( " Prime " )
9 else :
10 print ( " Not ␣ prime " )

23
3.19 Solution 5: Count Vowels

1 text = input ( " Enter ␣ a ␣ string : ␣ " )


2 vowels = " aeiouAEIOU "
3 count = sum (1 for char in text if char in vowels )
4 print ( " Number ␣ of ␣ vowels : " , count )

3.20 Solution 6: Reverse String

1 text = input ( " Enter ␣ a ␣ string : ␣ " )


2 print ( " Reversed : " , text [:: -1])

3.21 Solution 7: Celsius to Fahrenheit

1 def c e l s i u s _ t o _ f a h r e n h e i t ( c ) :
2 return ( c * 9/5) + 32
3
4 c = float ( input ( " Temperature ␣ in ␣ Celsius : ␣ " ) )
5 f = celsius_to_fahrenheit (c)
6 print ( " Temperature ␣ in ␣ Fahrenheit : " , f )

3.22 Solution 8: Max and Min in a List

1 numbers = input ( " Enter ␣ numbers ␣ separated ␣ by ␣ spaces : ␣ " ) . split ()


2 numbers = [ float ( num ) for num in numbers ]
3 print ( " Maximum : " , max ( numbers ) )
4 print ( " Minimum : " , min ( numbers ) )

3.23 Solution 9: Even Numbers 1 to 100

1 for i in range (2 , 101 , 2) :


2 print (i , end = ’␣ ’)

3.24 Solution 10: Simple Calculator

1 def add (a , b ) : return a+b


2 def sub (a , b ) : return a-b
3 def mul (a , b ) : return a*b
4 def div (a , b ) : return a / b if b != 0 else " Undefined "
5
6 a = float ( input ( " Enter ␣ first ␣ number : ␣ " ) )
7 b = float ( input ( " Enter ␣ second ␣ number : ␣ " ) )
8 op = input ( " Enter ␣ operation ␣ (+ , - ,* ,/) : ␣ " )
9
10 if op == ’+ ’:
11 print ( add (a , b ) )
12 elif op == ’ - ’:

24
13 print ( sub (a , b ) )
14 elif op == ’* ’:
15 print ( mul (a , b ) )
16 elif op == ’/ ’:
17 print ( div (a , b ) )
18 else :
19 print ( " Invalid ␣ operation " )

25

You might also like