Chapter 01 Introduction to Python_part2_2
Chapter 01 Introduction to Python_part2_2
Advanced
Python
Language 1
1st Master - AI & Data Science
Course Content
▪ Chapter 1: Introduction to Python (Week 1-2)
▪ 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:
7
Installing Python
Windows users
8
Installing Python
Windows users
Step 1: Select version of Python to
install
9
Installing Python
Windows users
Step 1: Select version of Python to
install
10
Installing Python
Windows users
Step 1: Select version of C:\Users\Username\AppData\Local\Programs\Python\Python38
Python to install
12
Python IDE
Integrated Development Environment (Text Editor)
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 '''.
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.
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.
▪ It’s recommended to use meaningful names and follow snake_case for variable naming in Python
21
Variables and Data Types
# Valid variable names
name = "Alice"
age = 25
_is_valid = True
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:
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.
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.
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. '''
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)
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 ?
35
Conditional Statements
Even and Odd numbers
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.
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
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
?
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.
48
Loops - For Loop
The range() function:
range(stop) for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
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
51
Loops - For Loop
52
Loops - For Loop
range() in Combination with zip()
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]
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
count = 5
while True:
age = int(input("Enter your 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.
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