0% found this document useful (0 votes)
22 views62 pages

Chapter 01 Introduction to Python_part2_2

Uploaded by

Aya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
22 views62 pages

Chapter 01 Introduction to Python_part2_2

Uploaded by

Aya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

Ministry of Higher Education and Scientific Research

University of Oum El Bouaghi


Faculty of Exact Sciences and Natural and Life Sciences
Department of Mathematics and Computer Science

Advanced
Python
Language 1
1st Master - AI & Data Science
Course Content
▪ Chapter 1: Introduction to Python (Week 1-2)

▪ Chapter 2: Advanced Data Structures (Week 3-5)

▪ Chapter 3: Object-Oriented Programming (OOP) (Week 6-8)

▪ Chapter 4: Advanced Use of Python Libraries for AI and Data Science (Week 9-12)

2
Course Goals
▪ This subject aims to empower students to develop complex, efficient and well-structured

Python applications, with emphasis on the specific requirements of the fields of artificial
intelligence and data science.

3
Chapter 01:
Introduction to Python
4
Chapter 01: Introduction to Python
What is Python ?
Python is a powerful, versatile, and widely-used programming language that
emphasizes simplicity and readability, making it accessible to beginners while still
being robust enough for professionals.

It was created by Guido van Rossum and first released in 1991, and over the decades, it
has become one of the most popular languages in the world due to its clean syntax,
cross-platform compatibility, and vast ecosystem of libraries and frameworks.

5
Why Python?
Open source

python
1)
2) Clear and Readable Syntax print('Hello, World!')
3) Interpreted and Dynamically Typed
4) Versatility Across Domains:
A. Web Development:
B. Data Science and Machine Learning
C. Automation/Scripting public class Hello{
D. Game Development public static void main(String argv[]){

java
E. Artificial Intelligence system.out.println('Hello, World!');
5) Extensive Standard Library and Ecosystem }
6) Cross-Platform Compatibility }
7) Object-Oriented and Functional

C language
8) Scalability #include <stdio.h>
9) Massive Community and Support int main(){
printf('Hello, World!');
return 0;
}
6
Why Python?
Use Cases of Python:

▪ Web development (Django, Flask)


▪ Data science and analysis (Pandas, NumPy)
▪ Machine learning and AI (TensorFlow, PyTorch)
▪ Automation and scripting ( Selenium, beautiful soup, scrapy)
▪ Cybersecurity and hacking (ethical hacking tools, penetration testing)
▪ Game development (Pygame)
▪ Scientific computing (SciPy)
▪ Finance (quantitative analysis, financial modeling)

7
Installing Python
Windows users

Step 1: Select Version of Python to


Install

8
Installing Python
Windows users
Step 1: Select version of Python to
install

Step 2: Download Python


executable installer

9
Installing Python
Windows users
Step 1: Select version of Python to
install

Step 2: Download Python 2


executable installer

Step 3: Run executable installer 1

10
Installing Python
Windows users
Step 1: Select version of C:\Users\Username\AppData\Local\Programs\Python\Python38
Python to install

Step 2: Download Python


executable installer
Python prompt
Step 3: Run executable
installer

Step 4: Verify Python is


installed successfully

Interactive mode -> Command line Interactive(CLI) 11


Installing Python
Windows users
Step 1: Select version of Open 'Start' menu and type 'cmd'
Python to install

Step 2: Download Python


executable installer

Step 3: Run executable


installer
pip -V

Step 4: Verify Python is


installed successfully

Step 5: Verify pip is installed

12
Python IDE
Integrated Development Environment (Text Editor)

PyCharm Eclipse Spyder

13
Anaconda

14
Basic Syntax and Output
Python has a clean and simple syntax that differs significantly from other
programming languages like C, Java, or C++. Some key aspects include:
1- Indentation:
❖ Python uses indentation ( 04 whitespace) to define code blocks (e.g., for
loops, functions, if-statements), rather than curly braces {} or keywords.
❖ Proper indentation is critical; a mismatch in indentation will cause an error.

if True:
print("This is inside the block")

15
Basic Syntax and Output
2- Comments:
•Single-line comments begin with the # symbol.
•Multi-line comments can be written using triple quotes """ or '''.

# This is a single-line comment


"""
This is a multi-line comment. It spans multiple lines.
"""

16
Basic Syntax and Output
3- Case Sensitivity:
Python is case-sensitive, meaning that myVariable, MyVariable,
and MYVARIABLE are all considered different variables.
myVariable = 10
MyVariable = 20
print(myVariable) # Output: 10
print(MyVariable) # Output: 20

17
Using print() for Output
The print() function is used to display output in Python.
It can output strings, variables, and formatted text.

print("Hello, World!")
name = "Alice"
print("Hello, " + name)
print(f"Hello, {name}") # Using f-string formatting (Python 3.6+)

18
String Manipulation Basics
Strings in Python are sequences of characters enclosed in single
(' ') or double (" ") quotes.
Strings can be concatenated, sliced, and manipulated using built-
in methods.
greeting = "Hello"
name = "John"
# Concatenation
full_greeting = greeting + " " + name print(full_greeting) # Output: Hello John
# String slicing
print(greeting[1:4]) # Output: ell
# Changing case
print(name.upper()) # Output: JOHN

19
Interactive Exercise: Write a Simple Program

Write a Python program that asks the user for their name and
then displays a personalized greeting message.

# Asking for the user's name


name = input("Enter your name: ")

# Displaying a personalized greeting message


print(f"Hello, {name}! Welcome to Python programming.")

20
Variables and Data Types
Variables are used to store data values in Python. Unlike some languages, you don't need to declare a
variable's type explicitly; Python determines the type based on the value assigned.

Naming conventions:

▪ Variable names must start with a letter or an underscore (_), followed by letters, numbers, or

underscores.

▪ Variable names are case-sensitive (myVar is different from MyVar).

▪ It’s recommended to use meaningful names and follow snake_case for variable naming in Python

(e.g., user_age, total_score).

21
Variables and Data Types
# Valid variable names
name = "Alice"
age = 25
_is_valid = True

# Invalid variable name (starts with a number)


2cool = 50 # This will cause a syntax error

22
Variables and Data Types
Data Types:
Python supports several built-in data types. The most common ones
include:
1. int (integer): Whole numbers, positive or negative, without
decimals. age = 30 year = 2024
2. float (floating-point): Numbers with decimals. price = 19.99 pi =
3.14159
3. str (string): Text data enclosed in single or double quotes. name =
"Alice" greeting = 'Hello'
4. bool (boolean): True or False values. is_valid = True is_active =
False
23
Variables and Data Types
Type Conversion:
Sometimes you need to convert a variable from one type to another. Python allows explicit type
conversion using functions like:
• int(): Converts to integer
• float(): Converts to float
• str(): Converts to string
• bool(): Converts to boolean:

# Convert string to integer


num_str = "123"
num_int = int(num_str)
print(num_int) # Output: 123
#Convert integer to string
age = 25
age_str = str(age)
print("I am " + age_str + " years old.") # Output: I am 25 years old. 24
Variables and Data Types
Type Checking:
You can use the type() function to check the type of a variable.
This is useful to verify the type of a variable at runtime, especially when debugging.

name = "Alice"
age = 25 price = 19.99
is_valid = True
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
print(type(price)) # Output: <class 'float'>
print(type(is_valid)) # Output: <class 'bool'>

25
Variables and Data Types
Once Python has decided b = 3
c = 'word'
what type a variable is, it trace = False
will flag up a TypeError if d = b + c
Traceback (most recent call last):
you try to perform an File '<stdin>', line 1, in <module>
inappropriate operation on TypeError: unsupported operand type(s) for +:
'int' and 'str'
that data.

26
Basic Input and Output
1. Using input() to Get User Input:
The input() function is used to take input from the user in Python. It always returns the
user input as a string, so if you're expecting a different data type (like an integer or
float), you'll need to convert it manually.

name = input("Enter your name: ")


print(f"Hello, {name}!")

27
Basic Input and Output
Formatting Output: You can use f-strings (formatted string literals) to easily
format and insert variables into strings. It's very handy when outputting
multiple values.

name = "Alice"
age = 25 height = 5.6
print(f"My name is {name}, I am {age} years old and my height is {height}
feet.")

28
Basic Input and Output
2. Converting and Formatting Input:

Since input() returns a string by default, you'll often need to convert the input to other
types using int(), float(), etc.

age = input("Enter your age: ") # Input is treated as a string


age = int(age) # Convert to integer
print(f"Next year, you will be {age + 1} years old.")

Type Conversion

29
Basic Input and Output
'''
Get a value from the user and
Problem: Get a value from the user and display it.
display it. '''

name = input('Enter your name: ')


print('Your name is:', name)
print('and it has\t', len(name), '\t charachters')

Use the different sequences


and see what happens.

30
Operators
Symbol Operation '''
** exponent Problem: try different operators.
'''
% modulo
// integer division a = 9
/ division b = 10.5
* multiplication print('sum is:', a + b)
- subtraction print(‘Subtraction is:', a - b)
+ addition print('multiplication is:', a * b)
print('division is:', a / b)
Symbol Operation print('power is:', a ** b)
>, < Greater than, less than
print(a > b)

>=, <= Greater or equal,


less or equal
== equal
!= Not equal 31
Operators
'''
Logical operators: Problem: apply all logical operators.
'''
(expression1) and (expression2)
a = 2
(expression1) or (expression2) b = 8
c = 4
d = 6
not (expression2)
print((a >= b) and (c < d))

false true
print((a >= b) or (c < d))

false true
print(not a)

false

32
Understanding and Applying Control
Structures - Conditionals and Loops

33
At the end of this session, students will
understand the concept of conditional
statements (if, else, elif), (match-case) and
34 loops (for, while) in Python, enabling them to
write more dynamic and interactive
programs.

Objective
Conditional Statements
How to make decisions based on different conditions ?

• A conditional statement allows you to execute certain pieces of


code based on whether a condition is true or false.
• The basic conditional structure involves if, followed by a condition.
If the condition evaluates to True, the associated block of code is
executed.
• The else block provides an alternative path if the condition is
False.
• elif (short for “else if”) allows you to check multiple conditions,
executing the first true condition.

35
Conditional Statements
Even and Odd numbers

number = int(input("Enter a number: "))


if number % 2 ==0:
print("Even")
else:
print("Odd")

36
Conditional Statements
Example 2: Positive, Negative, or Zero
Problem: Write a program that checks if a number is positive, negative,
or zero.
number = int(input("Enter a number: "))

if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

37
Conditional Statements
Example 3: Age Classification
Problem: Write a program to classify a person based on his age.

age = int(input("Enter your age: "))

if age < 13:


print("You are a child.")
elif 13 <= age < 18:
print("You are a teenager.")
elif 18 <= age < 65:
print("You are an adult.")
else:
print("You are a senior.") 38
Conditional Statements
Ternary conditional operator
Python offers a ternary conditional operator (also called a
conditional expression) that provides a short syntax for writing
simple if-else statements on a single line.

syntax
value_if_true if condition else value_if_false

39
Conditional Statements
Ternary conditional operator
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Output: Even
x = -5
result = "Positive" if x > 0 else "Negative" if x < 0 else "Zero"
print(result) # Output: Negative

40
Conditional Statements
Ternary conditional operator

Tuple Indexing for Simple Conditions


x = 7
result = ("Odd", "Even")[x % 2 == 0]
print(result) # Output: Odd

41
Conditional Statements
Using and with or for Conditional Assignment
You can use the combination of and and or to achieve a similar effect as a
conditional expression, but this approach works best for simple, binary
choices.
x = 5
result = (x > 0 and "Positive") or "Negative"
print(result) # Output: Positive

A non-empty string is considered True in Python


None is False
Variables with 0 value are False (example f=0)
42
Conditional Statements
Using and with or for Conditional Assignment
You can use the combination of and and or to achieve a similar effect as a
conditional expression, but this approach works best for simple, binary
choices.
x = 5
result = (x > 0 and "Positive") or "Negative"
print(result) # Output: Positive
In Python, the and operator returns the second operand if
the first one is True
The or operator works by returning the first True value it
encounters. If both operands are False, it returns the second
43
operand.
Conditional Statements
Problem: Write a program that determines whether a person qualifies for a credit
card based on income, credit score, and whether they have any debts.
Conditions:
• To qualify, the person must have an income of at least $50,000 and a credit
score above 700.
• If they have any existing debts, the income requirement is raised to $80,000.

?
44
Conditional Statements
income = int(input("Enter your annual income: "))
credit_score = int(input("Enter your credit score: "))
has_debt = input("Do you have any debts? (yes/no): ").lower()

if has_debt == "yes":
if income >= 80000 and credit_score > 700:
print("You qualify for the credit card.")
else:
print("You do not qualify for the credit card.")
else:
if income >= 50000 and credit_score > 700:
print("You qualify for the credit card.")
else:
print("You do not qualify for the credit card.")
45
Conditional Statements
match-case (Python 3.10+)
value=2
match value:
case 1:
result= "Case 1"
case 2:
result= "Case 2"
case 3:
result= "Case 3"
case _:
result= "Default case"
print(result)

46
Loops - For Loop
Objective: Learn to iterate over sequences like lists or ranges
using for loops.

A for loop is used to iterate over a sequence (such as a


list, tuple, dictionary, or range) and execute a block
of code for each element in the sequence.
The most common use case is looping through a list
or a sequence of numbers using range().
You can also loop through characters in a string.
47
Loops - For Loop
Example 1: Looping through a Range
Problem: Print numbers from 1 to 10 using a for loop.
All elements in the same line then each one in a new line
for i in range(1, 11): for i in range(1, 11):
print(i, end=" ") print(i)

48
Loops - For Loop
The range() function:
range(stop) for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4

range(start, stop) for i in range(2, 7):


print(i) # Output: 2, 3, 4, 5, 6

49
Loops - For Loop
The range() function with a step:
range(start, stop, step) (Positive Step)
for i in range(1, 10, 2):
print(i) # Output: 1, 3, 5, 7, 9

range(start, stop, step) (Negative Step)


for i in range(10, 0, -2):
print(i) # Output: 10, 8, 6, 4, 2

Zero Step is Invalid (Error) 50


Loops - For Loop
range() with Unpacking:
You can unpack values generated by range()
directly into variables. This is often useful when
dealing with multiple variables in loops or function
calls
x, y, z = range(3)
print(x, y, z) # Output: 0 1 2

51
Loops - For Loop

Example 2: Looping through a List


Problem: Write a program that prints each element of a
list.
my_list = ['apple', 'banana', 'cherry']

for fruit in fruits:


print(fruit)

52
Loops - For Loop
range() in Combination with zip()

letters = ['a', 'b', 'c', 'd'] Index 1: a


for i, letter in zip(range(1, 5), letters): Index 2: b
print(f"Index {i}: {letter}") Index 3: c
Index 4: d

When you want to loop over two sequences simultaneously,


zip() can be used alongside range() to pair elements from both
sequences.
53
Loops - For Loop
The enumerate() function
It returns both the index and the element in each iteration.

my_list = ['apple', 'banana', 'cherry']

for index, value in enumerate(my_list, start=1):


print(f"{index}: {value}")

54
Loops - For Loop
List Comprehension with Conditionals
Example: Write a program that filters out even numbers from a list
and squares the remaining odd numbers in a single line.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

squared_odds = [num ** 2 for num in numbers if num % 2 != 0]


print(squared_odds)

55
Loops - For Loop
Nested for Loops
Example: Perform a grid search to find pairs (x, y) where
both numbers are divisible by 3 and 5, respectively, within
the range of 1 to 50.
for x in range(1, 51):
for y in range(1, 51):
if x % 3 == 0 and y % 5 == 0:
print(f"Valid pair: (x={x}, y={y})")

56
Loops - For Loop
Exercise: Write a Python program to calculate and print
the sum of all integer numbers from 5 to 15.

total = 0
for num in range(5,16):
total += num
print(f"The total sum is: {total}")

57
Loops – While Loop
A while loop repeats as long as the condition is True.
count = 5

while count > 0:


print(count)
count -= 1

count = 5

while count in range(1,6) :


print(count)
count -= 1 58
Loops – While Loop
Input Validation
Problem: Ask the user for a valid age (must be between 1 and 120).

while True:
age = int(input("Enter your age: "))

if 1 <= age <= 120: Break ?


print(f"Your age is {age}.")
break
else:
print("Please enter a valid age.")

59
Loops – While Loop
Break ? and Continue ?
Combining Loops and Conditions
Conditionals and loops often work together in more
complex programs. You can use conditionals inside loops to
create interactive and responsive programs.

The control statements (break and continue) are especially


useful for managing the flow within loops.

60
Loops – While Loop
i = 1
Break ? and Continue ?
The program prints only even
while i <= 30: numbers between 1 and 30, but if
i += 1
the number is 14, it skips printing
if i == 14: and continues. If the number
continue # Skip printing the number 14 reaches 20, the loop ends.

if i % 2 == 0:
print(i) # Print only even numbers This demonstrates the use of
break to exit a loop early and
if i == 20: continue to skip over certain
break # Stop the loop when the number
reaches 20
iterations while still continuing the
loop execution.

61
Thank you

62

You might also like