0% found this document useful (0 votes)
4 views60 pages

Chap 1

The document provides an overview of Python as a high-level programming language, emphasizing its readability, simplicity, and support for multiple programming paradigms. It covers fundamental syntax, data types, functions, and control flow statements, highlighting Python's unique features like indentation for block structure and built-in functions for data manipulation. Additionally, it discusses the importance of modules and packages for code organization and reuse.

Uploaded by

sakuraeve87
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)
4 views60 pages

Chap 1

The document provides an overview of Python as a high-level programming language, emphasizing its readability, simplicity, and support for multiple programming paradigms. It covers fundamental syntax, data types, functions, and control flow statements, highlighting Python's unique features like indentation for block structure and built-in functions for data manipulation. Additionally, it discusses the importance of modules and packages for code organization and reuse.

Uploaded by

sakuraeve87
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

1.

Introduction

A computer program is a set of clear, ordered instructions executed by a computer to


solve problems or perform tasks. Based on the stored-program model, programs are
essential for modern computing, enabling automation and complex applications. High-
level languages make programming easier to read, maintain, and apply across
paradigms such as procedural, object-oriented, and functional programming.
Introduction

Python is a high-level, interpreted, general-purpose programming language that


emphasizes readability, simplicity, and productivity. Its design promotes code that is
clear and easy to understand, utilizing an indentation-based syntax rather than braces.
It supports multiple paradigms, including procedural, object-oriented, and functional
programming. Unlike many other languages, Python prioritizes ease of use over
execution speed, making it particularly effective for rapid prototyping, research, and
applications.
Fundamentals of Python Syntax
 Case sensitivity : Python differentiates between uppercase and lowercase letters. For
example, Variable and variable are two different identifiers.
 Statements : By default, each line in Python represents a single statement.
 Colons (:) : A colon marks the beginning of a new block of code, such as after if, for,
while, def, or class.
 Line continuation:
 Implicitly: code can span multiple lines inside parentheses (), brackets [], or braces {},
For example:
Fundamentals of Python Syntax
 Explicitly: Two or more physical lines may be joined into logical lines using backslash
characters (\). When a physical line ends in a backslash that is not part of a string literal
or comment, it is joined with the following, forming a single logical line, deleting the
backslash and the following end-of-line character. For example:
Fundamentals of Python Syntax
• Blocks of code after control statements (if, for, while, def, class) must be indented.
• Indentation must be consistent within the block.
• Standard convention: 4 spaces per indentation level.
• Unlike other languages, Python uses indentation instead of braces to define block
structure.

The following identifiers are used as reserved words or keywords of the language and
cannot be used as ordinary identifiers. They must be spelled exactly as written here:
Fundamentals of Python Syntax

A comment starts with a hash character (#) that is not part of a string literal, and
ends at the end of the physical line. A comment signifies the end of the logical line
unless the implicit line joining rules are invoked.

1. Single-line comments start with the hash symbol. Python does not have
traditional multi-line comment syntax like /* ... */ in C/Java, but you can use
(#) on multiple lines.

2. A docstring is a special string used to document a module, function, class,


or method. Written inside triple quotes: ””” ... ””” or ”’ ... ”’.
Fundamentals of Python Syntax
Statement Type Example Description

Assignment x=5 Assigns a value to a variable.


Output print("Today is Tuesday.") Displays text or values.
Input name = input("Enter your name: ") Reads input from the user.
import math Imports a Python module to use
Import
its functions
del x Deletes a variable or an element
Deletion
from a data structure.
Return return x + y return x + y
assert x > 0 Checks a condition; raises an
Assert
error if it’s false.
Note ! : Python is a simple and expressive language that allows you to perform complex tasks with minimal code.
Compared to Java and C, it requires fewer lines and is easier to read and understand.

Language Example
Python

Java

C
Fundamentals of Python Syntax
A compound statement is a block of code composed of one or more clauses, each typically
starting with a keyword and ending with a colon(:). These statements group other
statements together and control the flow of execution. Examples include conditional
statements (if, elif, else), loops (for, while), and definition blocks (def, class). Each compound
statement introduces an indented block of code that must be written consistently. This
indentation replaces the use of braces in other programming languages.
Fundamentals of Python Syntax
Python provides several built-in functions that allow programmers to examine objects and
better understand how their code behaves:

 type(obj) → returns the type of the object.


Fundamentals of Python Syntax
 id(obj) → returns the unique identity of the object (its memory address).
Fundamentals of Python Syntax
 dir(obj) → lists all valid attributes and methods associated with the object.
Fundamentals of Python Syntax
 help(obj) → provides detailed documentation about the object.
Data Types
Python provides a rich collection of built-in data types that form the foundation for storing and
manipulating values. These types include numbers, strings, sequences, mappings, and sets,
along with the ability to convert values between them.

1. Integers (int): whole numbers without a fractional component.


2. float : numbers that contain decimals.
3. Complex : numbers with a real and an imaginary part, written with j for the imaginary
unit.
Data Types
Numeric Operations :

Arithmetic operations in Python can be applied to numeric data types such as integers, floating-
point numbers, and complex numbers.
These types support basic mathematical operations including addition, subtraction,
multiplication, division, and exponentiation.
Operator Description Example Result

() Parentheses (1 + 2) * 3 9
** Exponentiation 2 ** 4 16
+, - Positive, negative -[Link] -3.14159
*, / Multiplication, 2*3 6
division
+, - Addition, 1+2 3
subtraction
Data Types
Represent sequences of Unicode characters. Many operations can be applied on strings for
example :
• Modifying : Upper Case , Lower Case, Replace String

𝑛𝑎𝑚𝑒 = ”𝑎”
𝑝𝑟𝑖𝑛𝑡 ( 𝑛𝑎𝑚𝑒 . 𝑢𝑝𝑝𝑒𝑟 ( ) ) # 𝐴

𝑝𝑟𝑖𝑛𝑡 ( 𝑛𝑎𝑚𝑒 . 𝑙𝑜𝑤𝑒𝑟 ( ) ) # 𝑎

print([Link]("a", "b")) #b
Data Types
• Slicing
In Python is a technique used to extract a specific portion (substring, sublist, or
subsequence) from a sequence such as a string.

𝑏 = "𝐻𝑒𝑙𝑙𝑜, 𝑊𝑜𝑟𝑙𝑑! "


𝑝𝑟𝑖𝑛𝑡(𝑏[2: 5]) #output llo

𝑝𝑟𝑖𝑛𝑡(𝑏[: 5]) #output Hello


• Concatenation
To concatenate, or combine, two strings you can use the + operator.
𝑎 = "Hello"
𝑏 = "World"
𝑐 = 𝑎 + 𝑏
Data Types
A list object can be used to bundle elements together in Python. A list is defined by using
square brackets [] with comma-separated values within the square brackets. A tuple is a
sequence of comma-separated values that can contain elements of different types. A tuple
must be created with commas between values, and conventionally the sequence is
surrounded by parentheses.
Data Types
Some operations can be applied to lists, for example:

• Add List Items : To add an item to the end of the list, use the append () method.
• Insert specified index To insert a list item at a specified index, use the insert () method.
For example :
𝑡ℎ𝑖𝑠𝑙𝑖𝑠𝑡 = ["𝐴𝑙𝑔𝑖𝑒𝑟𝑠", "𝑂𝑟𝑎𝑛", "𝐶𝑜𝑛𝑠𝑡𝑎𝑛𝑡𝑖𝑛𝑒"]
𝑡ℎ𝑖𝑠𝑙𝑖𝑠𝑡. 𝑖𝑛𝑠𝑒𝑟𝑡 1, Bba
• Remove Specified Item :
𝑡ℎ𝑖𝑠𝑙𝑖𝑠𝑡 = ["𝐴𝑙𝑔𝑖𝑒𝑟𝑠", "𝑂𝑟𝑎𝑛", "𝐶𝑜𝑛𝑠𝑡𝑎𝑛𝑡𝑖𝑛𝑒"]
𝑡ℎ𝑖𝑠𝑙𝑖𝑠𝑡. 𝑟𝑒𝑚𝑜𝑣𝑒 "𝐴𝑙𝑔𝑖𝑒𝑟𝑠"
• Remove Specified Index :
𝑡ℎ𝑖𝑠𝑙𝑖𝑠𝑡 = ["𝐴𝑙𝑔𝑖𝑒𝑟𝑠", "𝑂𝑟𝑎𝑛", "𝐶𝑜𝑛𝑠𝑡𝑎𝑛𝑡𝑖𝑛𝑒"]
[Link](1)
print(thislist)
Data Types
Some operations can be applied to Tuples, for example:
Insert Item For example :
𝑚𝑦_𝑡𝑢𝑝𝑙𝑒 = ("𝐴𝑙𝑔𝑖𝑒𝑟𝑠", "𝑂𝑟𝑎𝑛", "Constantine")
𝑡𝑒𝑚𝑝_𝑙𝑖𝑠𝑡 = 𝑙𝑖𝑠𝑡(𝑚𝑦_𝑡𝑢𝑝𝑙𝑒)
𝑡𝑒𝑚𝑝_𝑙𝑖𝑠𝑡. 𝑎𝑝𝑝𝑒𝑛𝑑("Bba")
𝑚𝑦_𝑡𝑢𝑝𝑙𝑒 = 𝑡𝑢𝑝𝑙𝑒(𝑡𝑒𝑚𝑝_𝑙𝑖𝑠𝑡)
• Remove Item :
𝑚𝑦_𝑡𝑢𝑝𝑙𝑒 = Algiers, Oran, Constantine
𝑡𝑒𝑚𝑝𝑙𝑖𝑠𝑡 = 𝑙𝑖𝑠𝑡 𝑚𝑦𝑡𝑢𝑝𝑙𝑒
𝑡𝑒𝑚𝑝_𝑙𝑖𝑠𝑡. 𝑟𝑒𝑚𝑜𝑣𝑒("Bba")
𝑚𝑦_𝑡𝑢𝑝𝑙𝑒 = 𝑡𝑢𝑝𝑙𝑒(𝑡𝑒𝑚𝑝_𝑙𝑖𝑠𝑡)
Data Types
A set in Python is a container that stores unordered, unique elements. Unlike lists or tuples,
sets do not allow duplicates, and the order of items is not preserved. They are useful when
you need to test membership or remove duplicates from a collection. Sets are also created
using curly braces, for example:
Data Types
Some operations can be applied to Sets , for example
• Insert Item For example :

Myset = {"Algiers", "Oran", "Constantine"}


Myset. 𝑎𝑑𝑑 "bba"

• Remove Item For example :


Myset = {"Algiers", "Oran", "Constantine"}
Myset. 𝑎𝑑𝑑 Algiers
Data Types
Some operations can be applied to Dictionaries , for example
• Insert Item For example :

car = {
"brand": "Toyota",
"model": "Corolla",
"year": 2020
}
car["price"] = 20000
• Remove Item For example :
car = {
"brand": "Toyota",
"model": "Corolla",
"year": 2020
}
[Link](“year")
Data Types
Python provides built-in functions for converting between data types.
This is especially useful when working with user input or when combining
data from different sources.
Functions
A function is a block of organized, reusable code designed to perform a specific task.
It allows code reuse and improves program structure by avoiding repetition.
Functions
A function in Python is defined using the def keyword. The first line of a function
definition contains def, followed by the function name, and ends with a colon.
The indented body of the function may begin with a documentation string
(docstring) describing the function’s task, followed by the actual statements.
Functions
Functions
Functions often take arguments (inputs) and return values (outputs). Arguments
are specified inside the parentheses, and the return statement is used to send a
value back to the caller. For example :
Functions
• Default Arguments

A default argument is a parameter that assumes a default value if a value is not


provided in the function call for that argument.
Functions
• Keyword Arguments

In keyword arguments, values are passed by explicitly specifying the parameter


names, so the order doesn’t matter.
Functions
• Positional Arguments

In positional arguments, values are assigned to parameters based on their order


in the function call.
Functions
• Arbitrary Arguments (Using *args in Functions

If the number of arguments passed to a function is unknown, you can use *


before the parameter name in the function definition. This allows the function to
receive a tuple of all the arguments and access them as needed.
Functions
Recursion in Python refers to the ability of a function to call itself, allowing
problems to be solved through repeated self-invocation. This technique is widely
used in mathematics and programming to perform iterative operations in an
elegant and efficient manner. While recursion can simplify complex problems,
developers must use it carefully to avoid infinite loops and excessive memory
usage. When properly implemented, recursion offers a powerful and concise
approach to problem-solving in Python.
Functions
Statments
Conditional statements allow a program to execute different blocks of code
depending on whether a condition is true or false. Python uses the
keywords if, elif (else-if), and else to implement conditional logic.
Statments
Statments
Loops in Python allow the repetitive execution of code until a condition is
met. The for loop iterates over a sequence such as a list, tuple, string, or
range, while the while loop repeats a block
of code as long as the given condition remains true.
• For Loop
Statments
Iterating by Index of Sequences

The index and value of elements in a sequence can be accessed


simultaneously using the enumerate() function. This function adds a counter
to the iterable, allowing iteration through both the index and the
corresponding value in each loop.
Statments
• While Loop
Statments
Control flow statements allow finer control of loop execution.
1. break: Immediately exits the loop.
2. continue: Skips the current iteration and continues with the next.
3. pass: A placeholder statement that does nothing (often used to define empty blocks).
Modules, Packages and debugging

A module in Python is a file that contains definitions such as functions, variables, and classes
that are intended to be reused in other programs. Modules help organize code into separate files,
making it easier to maintain, debug, and reuse.
To create a module, simply write your Python code (for example, function or variable definitions)
in a file with a .py extension. You can then import this module into another Python program to
use its functionality. For example the file [Link] contains the code :

def greeting(name):
print("Hello, " , name)

Import the module named mymodule, and call the greeting function
import mymodule
[Link]("A")
Modules, Packages and debugging

In Python, the import statement is used to access functions, variables, and classes defined in
another module or in the Python standard library. The standard library includes many built-in
modules.
Modules, Packages and debugging

In Python, the import statement is used to access functions, variables, and classes defined in
another module or in the Python standard library. The standard library includes many built-in
modules.
Modules, Packages and debugging
• Import all Names

The * symbol used with the import statement is used to import all the names from a module to a
current namespace.
from module_name import *

Renaming the Python Module
We can rename the module while importing it using the keyword.
Modules, Packages and debugging
Some common Python modules and their main purpose :

Module Purpose Example


Name
math Provides basic mathematical functions [Link](25)
(square, sum, power, trigonometry).
random Generates random numbers and makes [Link](1, 100)
random selections.
datetime Handles dates and times. [Link]()
numpy Supports fast numerical computation [Link]([1,2,3])
and arrays.
matplotlib Used for plotting and data visualization. [Link]([1,2,3])
Modules, Packages and debugging

A package is a collection of related modules organized in directories with an [Link] file. Packages
allow developers to structure large projects logically. For example, a package shapes might contain
modules [Link] and [Link]. You can import them as:
Modules, Packages and debugging

Errors are inevitable in programming, and Python provides several simple yet effective debugging
tools to handle them. The print() function is the most common tool, allowing programmers to
display variable values and trace program flow. The assert statement checks whether a condition is
true and raises an AssertionError if it is not, helping catch mistakes early. Finally, the try/except
construct lets programmers catch and handle exceptions gracefully without crashing the program.
Classes
Python supports object-oriented programming (OOP) through the use of classes and objects. A
class acts as a blueprint for creating objects by combining both data and behavior, while an
object is a specific instance of a class.

Note !
__init__ method is the
constructor in Python,
automatically called when a new
object is created. It initializes the
attributes of the class.
Classes
• Self Parameter

Self parameter is a reference to the current instance of the class. It allows us to access the
attributes and methods of the object.
Classes
1. Attributes are variables that store data related to the object.
2. Methods are functions defined inside a class that describe the object’s behavior.
Classes
Inheritance allows a new class (child) to reuse the functionality of an existing class (parent). The
child class can add new features or override methods from the parent class.
Classes
Encapsulation restricts direct access to certain parts of an object, protecting its internal state.
In Python, this is achieved through naming conventions: public attributes (e.g., [Link]) are
accessible everywhere, protected attributes (e.g., balance) are indicated with a single underscore
and suggest limited access, while private attributes (e.g., password) use two underscores and are
name-mangled to prevent direct access.
Tasks
Write a Python program that asks the user to enter their name and then displays their name with a
welcome message!

Write a Python program that asks the user to enter two numbers, a and b, and then displays their
sum: a + b.

Write a Python program that asks the user to enter two numbers, a and b, and then displays the
larger (maximum) of the two.

Write a Python program that displays the first 100 integers.


Special Tasks
Write a Python program that asks the user to enter an integer and then displays whether the
number is even or odd.

Write a Python program that asks the user to enter an integer n and then displays the value of the
sum 1 + 2 + … + n =.

Write a Python program that asks the user to enter an integer n and then displays the factorial of
that number using a function.

Write a Python program that defines a base class called Person with private attributes for the name
and age. Then create a derived class Student that inherits from Person and adds a private attribute
for the student ID.
Special Tasks
The program should display the student’s details using methods that respect encapsulation.

You might also like