ML and AI: Module 3:
Python basics
Madhusoodanan M.R
GEC Thrissur
Variable
• In Python, a variable is a container for storing a value. You can create a variable
by assigning a value to it using the “=” operator. The value can be of any data
type, such as a string, integer, or floating-point number. Once a variable is
assigned a value, it can be used throughout your program.
For example:
x=5
y = “Hello”
z = 3.14
Data Types
• Python has several built-in data types, including strings, integers, and
floating-point numbers. In Python, data types refer to the type of value a variable
holds. Python has several built-in data types.
1. Numbers: This includes integers (e.g. 1, 2, 3) and floating-point numbers (e.g.
3.14, 1.23)
2. Strings: A string is a sequence of characters (e.g. “hello”, “world”). Strings can be
enclosed in single or double quotes
3. Lists: A list is a collection of items that are ordered and changeable. Lists are
written with square brackets and items are separated by commas
4. Tuples: A tuple is similar to a list, but it’s immutable (i.e. its items cannot be
changed). Tuples are written with round brackets and items are separated by
commas
5. Dictionaries: A dictionary is a collection of key-value pairs.
Dictionaries are written with curly braces and keys and values are
separated by colons
6. Boolean: A Boolean data type is either True or False
7. None: None is a special constant used to represent the absence of a
value or a null value
You can check the data type of a variable using the built-in type()
function
Data type-examples
•x = 5
print(type(x))
# Output: <class ‘int’>;
y = “Hello”
print(type(y))
# Output: <class ‘str’>;
z = [1, 2, 3]
print(type(z))
# Output: <class ‘list’>;
• In this example, x is an integer, y is a string, and z is a list.
Operators
• Python supports various operators for performing mathematical and
logical operations, such as +, -, *, /, and %.
• In Python, operators are special symbols that perform specific
operations on one or more operands (i.e. the variables or values being
operated on).
• Here are some common operators in Python:
Operators
Arithmetic operators:
These operators perform basic mathematical operations, such as addition (+), subtraction (-),
multiplication (*), division (/), and modulus (%).
Comparison operators:
These operators compare two values and return a Boolean value (True or False) based on the
comparison. Examples include equal to (==), not equal to (!=), greater than (>), less than (<),
greater than or equal to (>=), and less than or equal to (<=).
Logical operators:
These operators are used to combine multiple conditions. Examples include and (and), or
(or), and not (not).
Assignment operators:
These operators are used to assign a value to a variable. Examples include =, +=, -=, *=, /=,
and %=.
• For example:
•
x=5
y = 10
# Using the + operator to add x and y
result = x + y
print(result) # Output: 15
# Using the < operator to check if x is less than y
result = x < y
print(result) # Output: True
# Using the *= operator to multiply x by 2
x *= 2
print(x) # Output: 10
Conditional statements
• It is used to execute different codes depending on certain conditions. The
most common type of conditional statement is the if-else statement. The
basic syntax of an if-else statement is as follows:
• if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
• The ‘condition’ in the if statement is a Boolean expression that evaluates to
either True or False. If the condition is True, the code in the if block will be
executed, otherwise, the code in the else block will be executed.
Conditional statement
• For example:
x=5
if x > 0:
print(“x is positive”)
else:
print(“x is not positive”)
In this example, the condition ‘x > 0’ evaluates to True, so the code in
the if block is executed and the output will be “x is positive”.
Loops
• Python has two types of loops: for loops and while loops. These allow you
to repeatedly execute a block of code. In Python, loops are used to
repeatedly execute a block of code. There are two types of loops: for loops
and while loops.
1. For loops: A for loop is used to iterate over a sequence of items (e.g. a list,
string, or tuple) and execute a block of code for each item. The basic syntax
of a for loop is as follows: for variable in sequence:
# code to be executed for each item in the sequence For example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
While loop
• A while loop is used to repeatedly execute a block of code as long as a
certain condition is true. The basic syntax of a while loop is as
follows: while condition:
# code to be executed as long as the condition is
x=0
while x < 5:
print(x)
x += 1
Loops in Python
• It’s important to note that if the condition in the while loop never
becomes false, the loop will run indefinitely, causing an infinite loop.
To avoid this, make sure the condition will eventually be false.
• You can also use ‘break’ and ‘continue’ statements inside the loop to
control the flow of the loop, ‘break’ statement is used to exit a loop
and ‘continue’ statement is used to skip the current iteration and move
on to the next one.
Functions
• Python Functions is a block of statements that return the specific
task.
• The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Some Benefits of Using Functions
•Increase Code Readability
•Increase Code Reusability
Declaration of function
Function
• Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
To call a function, use the function name followed by
parenthesis:
def my_function():
print("Hello from a function")
my_function()
Function: example
def greet():
print('Hello World!')
# call the function
greet()
print('Outside function’)
Output will be as follows:
Hello World!
[Link] the function greet() is called, the program's control
Outside function transfers to the function definition.
[Link] the code inside the function is executed.
[Link] control of the program jumps to the next statement
after the function call.
Function: Arguments
• Arguments are inputs given to the function.
• Example:
def greet(name):
print("Hello", name)
# pass argument
greet("John")
Output will be
Hello John
Example: Function to add two numbers
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)
# function call with two values
add_numbers(5, 4)
Out put will be
Sum:9
Retun statement: Function
Return statement returns a value form the function.
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:', square)
Python libraries
• A library is a collection of pre-written code that you can use to perform
various tasks.
• Libraries provide a way to add functionality to your program without having
to write the code yourself.
• There are many libraries available for Python, some of the most popular
ones include:
1. NumPy: A library for working with numerical data in Python. It provides
tools for working with arrays, matrices, and mathematical functions.
2. Pandas: A library for working with data in Python. It provides tools for data
manipulation, data analysis, and data visualization.
..Python libraries
Matplotlib: A library for creating visualizations in Python. It provides
tools for creating charts, plots, and other types of graphics.
Scikit-learn: A library for machine learning in Python. It provides tools
for classification, regression, clustering, and more.
TensorFlow: A library for building and training machine learning
models in Python. It’s widely used for deep learning, computer vision,
natural language processing, and more.
OpenCV: A library for computer vision in Python. It provides tools for
image and video processing, feature detection and extraction, and more.
..python libraries
• To use a library in Python, you first need to install it, then you can
import it into your program