02 - Introduction To Python
02 - Introduction To Python
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.
© 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.
"""
# 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
# 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)
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
© Dataque Academy
Python Collections
There are four collection data types in the Python programming language:
*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’}
© 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}!")
© 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
© 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