0% found this document useful (0 votes)
21 views

02 - Introduction To Python

This document provides an introduction to basic Python concepts for machine learning. It outlines key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It also covers Python variables, operators, conditional statements, functions, loops, comments, and input/output. The goal is to cover basic Python syntax and structures to prepare readers for machine learning applications.

Uploaded by

iknowthissabrina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

02 - Introduction To Python

This document provides an introduction to basic Python concepts for machine learning. It outlines key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It also covers Python variables, operators, conditional statements, functions, loops, comments, and input/output. The goal is to cover basic Python syntax and structures to prepare readers for machine learning applications.

Uploaded by

iknowthissabrina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction to

Python
Machine Learning
Slides by Ihsanul Haque Asif

© Dataque Academy
Basic Python Outline
• Python variables
• Python Casting
• Python Data Types
• Python Comments
• Python Strings
• Python Operators
• Python Lists
• Python Loops
• Python Tuples
• Python Sets
• Python Dictionaries
• Python Conditional Statements
• Python Functions

© Dataque Academy
Python Variables # Assigning values to variables
age = 25
name = "Alice"
is_student = True
Rules for Naming Variables: pi_value = 3.14
• Must start with a letter (a-z, A-Z_ or an underscore `_`.
• Can include letters, numbers, and underscores.
• Case-sensitive `my_var`, `My_Var`, and MY_VAR` are different.

Good Practices:
• Use descriptive names (age, name, total_count) for better readability.
• Avoid using Python reserved keywords (‘if’, ‘for’, ‘while’, etc.) as variables names.

# Multiple Assignments x = "John" # Case-Sensitive


a, b, c = 1, 2, 3 # Single or Double Quotes a=4
print(a) # Output: 1 # are the same A = "Sally"
print(b) # Output: 2 x = 'John' #A will not overwrite a
print(c) # Output: 3

© Dataque Academy
Python Comments
#This is a comment """
print("Hello, World!") This is a multi-line comment or a docstring.
It can span multiple lines and is typically used
#print("Hello, World!") to describe the purpose of a module, function,
print("Cheers, Mate!") class, or method.
"""

#This is a comment def my_function():


#written in """
#more than just one line This is a docstring for a function.
print("Hello, World!") It describes what the function does,
its parameters, and return values.
""" """
This is a comment # Function code here
written in
more than just one line
# Best Descriptive, Make clear comments, Avoid Redundancy,
"""
Maintain Consistency and Update comments
print("Hello, World!")
© Dataque Academy
Python Data Types # Integer type
num = 10
print(type(num)) # Output: <class 'int'>
Python has the following data types built-in
by default, in these categories: # Float type
pi = 3.14
• Text Types: str print(type(pi)) # Output: <class 'float'>
• Numeric Types: int, float
• Sequence Types: list, tuple # String type
• Mapping Type: dict name = 'Alice'
• Set Type: set print(type(name)) # Output: <class 'str'>
• Boolean Type: bool
# List type
my_list = [1, 2, 3]
print(type(my_list)) # Output: <class 'list'>

# Boolean type
is_true = True
print(type(is_true)) # Output: <class 'bool'>

© Dataque Academy
Python Casting
# Specify a variable type # Converting integer to float # Converting string to integer
# Integers num_int = 10 num_str = "25"
x = int(1) # x will be 1 num_float = float(num_int) num_int = int(num_str)
y = int(2.8) # y will be 2 print(num_float) # Output: 10.0 print(num_int) # Output: 25
z = int("3") # z will be 3
# Converting float to integer # Converting string to float
float_num = 15.75 float_str = "3.14"
# Floats int_num = int(float_num) float_num = float(float_str)
x = float(1) # x will be 1.0 print(int_num) # Output: 15 print(float_num) # Output: 3.14
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0 # integer/float to string
w = float("4.2") # w will be 4.2 # Non-Boolean to boolean
zero = 0 num = 42
non_zero = 10 num_str = str(num)
# Strings bool_zero = bool(zero) print(num_str) # Output: '42'
x = str("s1") # x will be 's1' bool_non_zero = bool(non_zero)
y = str(2) # y will be '2' print(bool_zero) # Output: False
z = str(3.0) # z will be '3.0' print(bool_non_zero) # Output: True

© Dataque Academy
Python Input/Output
# Taking user input # Formatting output
name = input("Enter your product = "Laptop"
name: ") price = 1200.50
print(f"Hello, {name}!") quantity = 3

print(f"Product: {product}\nPrice: ${price}\nQuantity: {quantity}")


# Displaying output
age = 25
# Taking multiple inputs in a single line
print(f"I am {age} years old.")
x, y = input("Enter two numbers separated by space: ").split()
print(f"First number: {x}\nSecond number: {y}")

# Reading numeric input Python using the input() function for user input and the print()
num = float(input("Enter a number: ")) function for displaying output. You can also format output using
result = num * 2 f-strings ({}) to include variables within strings for more dynamic
print(f"Twice the number is: {result}") output.
© Dataque Academy
Python Strings
Creating Strings:
# Single quotes a = """Lorem ipsum dolor sit amet,
single_quoted = 'Hello, world!' consectetur adipiscing elit,
sed do eiusmod tempor incididunt
# Double quotes ut labore et dolore magna aliqua."""
double_quoted = "Python is awesome!" print(a)

String Operations: a = '''Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
• String Concatenation sed do eiusmod tempor incididunt
• String Length ut labore et dolore magna aliqua.'''
• Accessing Char by index print(a)
• String Slicing
• String Methods:
upper(), lower(), find(‘data’), strip()
• String Formatting
© Dataque Academy
Python Arithmetic Operators
a=5
b=3
result = a + b # Addition # Output: 8
result = a - b # Subtraction # Output: 2
result = a * b # Multiplication # Output: 15

a = 10
b=3
result = a / b # Division # Output: 3.3333333333333335
result = a // b # Floor Division (rounds down to the nearest whole number) # Output: 3
result = a % b # Modulus (remainder of the division) # Output: 1

a=2
b=3
result = a ** b # Exponentiation (a raised to the power of b) # Output: 8

© Dataque Academy
Python Assignment Operators
x = 5 # Assigning 5 to variable x x = 15
x //= 4 # Equivalent to x = x // 4
x=5 # Now x = 3
x += 3 # Equivalent to x = x + 3
# Now x = 8 x = 15
x %= 4 # Equivalent to x = x % 4
x=5 # Now x = 3
x -= 3 # Equivalent to x = x - 3
# Now x = 2 x=2
x **= 3 # Equivalent to x = x ** 3
x=5 # Now x = 8
x *= 3 # Equivalent to x = x * 3
# Now x = 15

x = 15
x /= 3 # Equivalent to x = x / 3
# Now x = 5.0
© Dataque Academy
Python Lists
# Creating an empty list # Slicing
empty_list = []
print(numbers[1:4]) # Output: [2, 3, 4]
# Creating a list with elements print(names[:2]) # Output: ['Alice', 'Bob']
numbers = [1, 2, 3, 4, 5] print(mixed_list[::2]) # Output: [1, 3.14] (every second element)
names = ['Alice', 'Bob', 'Charlie']
mixed_list = [1, 'hello', 3.14, True]

# Indexing
print(numbers[0]) # Output: 1 List Operations:
print(names[2]) # Output: Charlie • numbers.append(6)
• numbers.extend([7,8,9])
print(mixed_list[-1]) • numbers[0] = 10
# Output: True (last element) • numbers.remove(3)
• Popped_item = numbers.pop()
• len(numbers), numbers.sort(), numbers.reverse()

© Dataque Academy
For Loop
for i in range(5): # 0 to 4 fruits = ["apple", "banana", "cherry"]
print(i)
for fruit in fruits:
for x in range(2, 6): # 2 to 5 print(fruit)
print(x)
# Using Enumerate with a for Loop
The range() function defaults to increment fruits = ['apple', 'banana', 'cherry']
the sequence by 1, however it is possible
to specify the increment value in thirds for index, fruit in enumerate(fruits):
parameter: print(index,fruit)
for x in range(2, 30, 3):
print(x) numbers = [1, 2, 3, 4, 5]
# Doubling each element in the list

Note: for i in range(len(numbers)):


range(6) values 0 to 5 numbers[i] *= 2
Range(2,6) values 2 to 5
© Dataque Academy
While Loop
# Simple while loop example # Creating an infinite loop with a break condition
i=1 while True:
while i <= 5: user_input = input("Enter a number (type 'exit' to quit): ")
print(i) if user_input.lower() == 'exit':
i += 1 break
else:
print(f"You entered: {user_input}")
# Using break to exit the while loop
i=1 # Using continue to skip iterations
while i <= 5: i=0
print(i) while i < 5:
if i == 3: i += 1
break if i == 3:
i += 1 continue
print(i)

© Dataque Academy
Python Collections
There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate members.


• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

© Dataque Academy
Python Tuples
# Creating an empty tuple # Immutable Nature of Tuples
empty_tuple = () my_tuple = (1, 2, 3)
# Trying to change an element (throws an error)
# Creating a tuple with elements # my_tuple[0] = 10 # This will raise a TypeError
my_tuple = (1, 2, 3, 'hello', True) # Trying to add an element (throws an error)
# my_tuple.append(4) # This will raise an AttributeError
# Accessing Tuple Elements
my_tuple = (1, 2, 3, 'hello', True) • Tuple items are ordered, unchangeable, and allow
print(my_tuple[0]) # Output: 1 duplicate values
print(my_tuple[3]) # Output: 'hello' • To determine how many items a tuple has, use the len()
function
• Tuple items can be of any data type
# Unpacking Tuples
• A tuple can contain different data types
my_tuple = (1, 2, 3)
• From Python's perspective, tuples are defined as objects
x, y, z = my_tuple
with the data type 'tuple'
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3 © Dataque Academy
Python Set
• Set items are unordered, unchangeable, and do not allow
duplicate values.
• Unordered means that the items in a set do not have a
# Creating a set defined order.
my_set = {1, 2, 3, 4, 3, 'apple', 'orange', • Set items can appear in a different order every time you
'apple'} use them, and cannot be referred to by index or key.
print(my_set) • Set items are unchangeable, meaning that we cannot
# Output: {1, 2, 3, 4, 'apple', 'orange'} change the items after the set has been created.
• Duplicates Not Allowed
• Sets cannot have two items with the same value.
# Adding elements to a set
my_set.add('banana')
my_set.add(2) # Removing elements from a set
print(my_set) my_set.remove(3)
# Output: {1, 2, 3, 4, 'apple', 'orange', print(my_set)
'banana'} # Output: {1, 2, 4, 'apple', 'orange',
'banana'}

© Dataque Academy
Python Dictionary
• Dictionaries are used to store data values in key:value
thisdict = {
pairs.
"brand": "Ford",
• A dictionary is a collection which is ordered*, changeable
"model": "Mustang",
and do not allow duplicates.
"year": 1964
• As of Python version 3.7, dictionaries are ordered. In
}
Python 3.6 and earlier, dictionaries are unordered.
print(thisdict)
• Dictionaries are changeable, meaning that we can change,
add or remove items after the dictionary has been
thisdict = { created.
"brand": "Ford",
"model": "Mustang",
"year": 1964 thisdict = {
} "brand": "Ford",
print(thisdict["brand"]) "electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

© Dataque Academy
Python Dictionary
# Creating a dictionary # Dictionary methods
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} keys = my_dict.keys() # Get keys
print(my_dict) values = my_dict.values() # Get values
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York’} items = my_dict.items() # Get key-value pairs as
tuples
# Accessing elements in a dictionary
print(my_dict['name']) # Output: 'Alice' print(keys)
print(my_dict['age']) # Output: 30 # Output: dict_keys(['name', 'age', 'occupation'])
print(values)
# Adding elements to a dictionary # Output: dict_values(['Alice', 35, 'Engineer'])
my_dict['occupation'] = 'Engineer' print(items)
print(my_dict) # Output: dict_items([('name', 'Alice'), ('age', 35),
# Output: {'name': 'Alice', 'age': 35, 'city': 'New York', ('occupation', 'Engineer')])
'occupation': 'Engineer’}

# Removing elements from a dictionary


del my_dict['city']

© Dataque Academy
Python Conditional Statements
# if-elif-else statement # Nested if statements
z=8 num = 15
if z > 10: if num > 10:
print("z is greater than 10") print("Number is greater than 10")
elif z > 5: if num % 2 == 0:
print("z is greater than 5 but not greater than 10") print("Number is also even")
else: else:
print("z is not greater than 5") print("Number is odd")
# Output: z is greater than 5 but not greater than 10 # Output: Number is greater than 10, Number is
also even
# Conditional expression (ternary operator)
# if-else statement
condition = True
y=3
result = "Condition is True" if condition else "Condition is
if y > 5:
False"
print("y is greater than 5")
print(result)
else:
# Output: Condition is True
print("y is not greater than 5")
# Output: y is not greater than 5
© Dataque Academy
# Function with default parameter
Python Functions def greet_person(name="there"):
print(f"Hello, {name}!")

# Defining a function # Calling the function without an argument


def greet(): greet_person()
print("Hello, there!") # Output: Hello, there!

# Calling the function # Calling the function with an argument


greet() greet_person("Bob")
# Output: Hello, there! # Output: Hello, Bob!

# Function with parameters # Function with return statement


def greet_person(name): def add_numbers(a, b):
print(f"Hello, {name}!") return a + b

# Calling the function with an argument result = add_numbers(5, 3)


greet_person("Alice") print(result)
# Output: Hello, Alice! # Output: 8

© Dataque Academy
Python Functions | Variable Scope
# Global variable
Variables defined within a function have
global_var = 10
local scope, and those outside have global
scope.
# Function accessing global variable
def my_function():
local_var = 5
print(f"Local variable: {local_var}")
print(f"Global variable: {global_var}")

my_function()
# Output: Local variable: 5, Global variable: 10

# Accessing local_var outside the function will raise a


NameError
# print(local_var)

© Dataque Academy
Python Notebook
Please note that this presentation has an accompanying Interactive Python Notebook.

Suggested Readings
• W3schools.com
https://www.w3schools.com/python/
• GeeksForGeeks
https://www.geeksforgeeks.org/
• Tutorials Point
https://www.tutorialspoint.com/python/

© Dataque Academy
Thank you

© Dataque Academy

You might also like