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

Lecture 4 EDGE Python Data Science

This lecture covers the basics of Python, including variables, data types, and data structures such as lists, tuples, and dictionaries. It also discusses string manipulation, casting, and the differences between lists and arrays. Practical examples and exercises are provided to reinforce the concepts learned.

Uploaded by

nikantoroy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture 4 EDGE Python Data Science

This lecture covers the basics of Python, including variables, data types, and data structures such as lists, tuples, and dictionaries. It also discusses string manipulation, casting, and the differences between lists and arrays. Practical examples and exercises are provided to reinforce the concepts learned.

Uploaded by

nikantoroy1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Lecture 4

Python Basics
2
Learning Objectives Today
 Python Variables
 Data Types
 String
 Casting
 List
 Tuple
 Dictionary
 Operators

Atanu Shome, CSE, KU


3
Python Variables

 age = 30
 name = "Alice"
 pi = 3.14159

 Variables are often described as boxes you can


store values in.

Atanu Shome, CSE, KU


4
Variable Features
 Redeclaration
 Multiple Assignment

num1 = 5
num1 = 3.45

num1, num2, stri = 4, 5, "okay"


num1 = num2 = num3 = 10

print(num1, num2, num3)

Atanu Shome, CSE, KU


5
Delete Variable

Num1 = 10
print(id(num1)) #Shows the RAM location where
this is saved

del num1
print(num1)

Atanu Shome, CSE, KU


Python Data Types
6
Numeric Types:
Set Types:
Integers (int): Represent whole numbers,
positive or negative (e.g., age = 30, score = - Sets (set): Unordered collections of
10). unique items enclosed in curly braces
{}. Useful for checking membership
Floats (float): Represent decimal numbers and removing duplicates (e.g.,
(e.g., pi = 3.14159, temperature = 25.5). unique_numbers = {1, 2, 2, 3, 4}).
Complex Numbers (complex): (e.g., z = 3+5j). Frozen Sets (frozenset): Immutable
versions of sets (e.g., frozen_numbers
Text Types: = frozenset({1, 2, 3})).
Strings (str): Represent sequences of Mapping Types:
characters, enclosed in single or double
Dictionaries (dict): Unordered
quotes (e.g., name = "Alice", message =
collections of key-value pairs enclosed
'Hello, world!'). in curly braces {}. Keys must be
Sequence Types: unique and immutable (e.g., person =
{"name": "Bob", "age": 30}).
Lists (list): Ordered, mutable collections of
Other Types:
items (e.g., fruits = ["apple", "banana", 10]).
Boolean (bool): Represent logical
Tuples (tuple): Ordered, immutable collections values, True or False (e.g., is_running
of items (e.g., coordinates = (10, 20)) = True).
Atanu Shome, CSE, KU
7
Data Types

Atanu Shome, CSE, KU


8
Try Out
 Input a number and print

 Input a number 1451.1545 into the variable and output


only two decimal values

 Take two strings and an integer. Print a single string.

 Multiple Variable Assignment

 Delete a variable
Atanu Shome, CSE, KU
9
Casting
x = int(1) x = float(1) # x will be 1.0 x = str("s1") # x will be 's1'
y = int(2.8) y = float(2.8) # y will be y = str(2) # y will be '2'
2.8
z = int("3") z = str(3.0) # z will be '3.0'
z = float("3") # z will be
print(x) 3.0 print(x)
print(y) w = float("4.2") # w will be print(y)
print(z) 4.2 print(z)
print(x)
print(y)
print(z)
print(w) Implicit Type Casting (Automatic Conversion)
Explicit Type Casting (Manual)

Atanu Shome, CSE, KU


10
String Formatting and Functions
message = 'Hello, world!' # Single quotes
name = "Alice" # Double quotes
multiline_text = """This is a string
that spans multiple lines.""" # Triple quotes

print(multiline_text)

Atanu Shome, CSE, KU


11
String
Accessing Characters
first_letter = message[0] # 'H'
last_letter = message[-1] # '!’
print(first_letter, last_letter)

Slicing
Extract substrings using colon (:) notation within square brackets.
Syntax: [start:end:step].
message1 = "PythonClass"
substring = message[7:12] # "world" (extracts characters from index 7 to 11)
print(substring)
substring = message1[1:8:2] # “yhnl" (extracts characters at indices 1, 3, 5 and 7)
print(substring)
Atanu Shome, CSE, KU
12
Try Out

 A Dataset contains strings in a column. The


last character of the sentence contains the
currency type. And 5th,6th, and 7th letters
contain the amount of money. Can you
extract it?

Atanu Shome, CSE, KU


13
String
 Strings provide various built-in methods for manipulation:
 upper(): Convert to uppercase (e.g., message.upper()).
 lower(): Convert to lowercase (e.g., message.lower()).
 strip(): Remove leading and trailing whitespaces (e.g.,
message.strip()).
 find(substring): Find the index of the first occurrence of a substring
(returns -1 if not found).
 replace(old, new): Replace all occurrences of a substring with
another substring.
 Many more! (Refer to Python documentation for the full list)

Atanu Shome, CSE, KU


14
Try Out

 Apply the functions and see what happens


to the string.

Atanu Shome, CSE, KU


15
String Formatting

name = "Bob"
age = 30
formatted_text = f"Hello, {name}! You are {age} years old."
print(formatted_text) # Output: Hello, Bob! You are 30 years
old.

Try OUT

Atanu Shome, CSE, KU


16
String Space Removal
message = " Hello, World! "

# Remove all leading/trailing whitespaces


stripped_message = message.strip()
print(stripped_message) # Output: Hello, World!

# Remove leading whitespaces


left_stripped_message = message.lstrip()
print(left_stripped_message) # Output:Hello, World!

# Remove trailing whitespaces


right_stripped_message = message.rstrip()
print(right_stripped_message) # Hello, World!
Atanu Shome, CSE, KU
17
String Search
message = "Hello, brave new world!"

# Find the index of the first occurrence of "world"


world_index = message.find("world")
print(world_index) # Output: 7

# Find the index of the last occurrence of "world" (if it appears multiple
times)
last_world_index = message.rfind("world")
print(last_world_index) # Output: 7

Atanu Shome, CSE, KU


18
String Split and Join
message = "Hello, how are you today?"

# Split the string into words using spaces as separator


words = message.split(" ")
print(words) # Output: ['Hello,', 'how', 'are', 'you', 'today?']

message2 = "I am Atanu $ I'm taking your class"


words = message2.split("$")
print(words) # Output: ['Hello,', 'how', 'are', 'you', 'today?']

# Join the words back into a string with underscores


joined_message = "_".join(words)
print(joined_message) # Output: Hello,_how,_are,_you,_today?
Atanu Shome, CSE, KU
19
String Replacement
message = "Hi, this is a test string."

# Replace all occurrences of "is" with "was"


replaced_message = message.replace("is", "was")
print(replaced_message) # Output: Hi, this was a test string.

# Replace only the first occurrence


replaced_message = message.replace("is", "was", 1)
print(replaced_message) # Output: Hi, this was a test string.

Atanu Shome, CSE, KU


20
Try Out
 You are given a list of strings representing words. Your task is to write a Python program that
performs the following operations:
 Join all the words in the list into a single string, separated by a specific delimiter.
 Split the resulting string back into individual words using the same delimiter.
 Write a Python function join_split_words(words_list, delimiter) that takes a list of words and
a delimiter as input and returns the list of words obtained after joining and splitting the
original list.
 Input:
 words_list: A list of strings representing words (e.g., ["Hello", "World", "Python"])
 delimiter: A string representing the delimiter to use for joining and splitting (e.g., ",")
 Output:
 A list of strings obtained after joining and splitting the original list using the
specified delimiter.

Atanu Shome, CSE, KU


21
Try Out
 Example
words_list = ["Hello", "World", "Python"]
delimiter = ","
result = join_split_words(words_list, delimiter)
print(result)

Expected Output:
['Hello', 'World', 'Python’]

Lets t
okay lets try formating Hello, can you see World ry formatted
output????????????
Atanu Shome, CSE, KU
22
Lists vs Array in Python
 The main differences are:
 Arrays can only store elements of the same data type, while
lists can store mixed data types.
 Arrays are more memory-efficient and faster for numerical
operations, while lists consume more memory but are more
flexible.
 Arrays require explicitly importing the array module, while
lists are a built-in data structure in Python.
 Arrays have limited functionality compared to the extensive
list of built-in methods available for lists.
 Modifying the size of an array is more difficult than modifying
a list, which can be done dynamically.

Atanu Shome, CSE, KU


23
Lists vs Array in Python
 Choosing Between Lists and Arrays:
• General purpose collection: Use lists for general-purpose data
storage where you might have different data types and need flexibility
in adding, removing, or modifying elements.
• Numerical computations: If you're working with large amounts of
numerical data and need efficient operations, consider using arrays
from NumPy. NumPy arrays offer a powerful set of functions for
numerical computations and vectorized operations.
 Additional Considerations:
• For simple numerical arrays, the array module can be an
option, but NumPy provides a richer set of features and optimizations.
• If you don't need the performance benefits of arrays for numerical
data, lists are generally more convenient due to their built-in nature
and flexibility.
Atanu Shome, CSE, KU
24
List
 List is one of the built-in data types in Python. A Python list is a
sequence of comma separated items, enclosed in square brackets [ ].
The items in a Python list need not be of the same data type.

list1 = ["Rohan", "Physics", 21, 69.75]


list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list4 = [25.50, True, -55, 1+2j]

Atanu Shome, CSE, KU


25
List
#Access
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

#Update
list = ['physics', 'chemistry', 1997, 2000];
print ("Value available at index 2 : ")
print (list[2])
list[2] = 2001;
print ("New value available at index 2 : ")
print (list[2])
Atanu Shome, CSE, KU
26
List
#Delete
list1 = ['physics', 'chemistry', 1997, 2000];
print (list1)
del list1[2];
print ("After deleting value at index 2 : ")
print (list1)

Negative Access??
bicycles = ['trek', 'cannondale', 'redline', 'specialized’]
print(bicycles[-1])

Atanu Shome, CSE, KU


27
List
 Insert vs Append

bicycles.append("Duranta")
print(bicycles)

bicycles.insert(3, "Racer")
print(bicycles)

Atanu Shome, CSE, KU


28
Try Out

 Insert, Append in a Python List


 Delete values from a list

 Search and delete a value from a Python list

 Search and delete all occurances of a value


from the list

Solutions are in the python scripts of lecture 5


Atanu Shome, CSE, KU
29
List
 Slice and PoP

fruits = ["apple", "banana", "cherry"]


sublist = fruits[1:3] # ["banana", "cherry"] (extracts elements at index 1
and 2, excluding index 3)

print(sublist)

removed_fruit = fruits.pop(2) # removed_fruit is "cherry" and fruits


becomes ["apple", "orange", "mango"]
print(removed_fruit)

Atanu Shome, CSE, KU


30
List Functions
 Sort

my_list = [66, 33, 22, 44, 88, 77, 99, 11]


my_list2 = sorted(my_list)
print(my_list2)

my_list.sort()
print(my_list)

Atanu Shome, CSE, KU


31
List Functions
 Sort

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]

numbers.sort(reverse=True)
print(numbers) # Output: [4, 3, 2, 1]

# Sorting by length of strings


strings = ["aa", "bbbbb", "ccc"]
strings.sort(key=len)
print(strings) # Output: ["aa", "ccc", "bbbbb"]
Atanu Shome, CSE, KU
32
List Functions
 Reverse, Length and Extend

my_list.reverse()
print(my_list)
print(len(my_list))

fruits = ["apple", "banana"]


fruits.append("cherry")
print(fruits) # Output: ["apple", "banana", "cherry"]
vegetables = ["potato", "tomato"]
fruits.extend(vegetables)
print(fruits) # Output: ["apple", "orange", "banana", "cherry", "potato", "tomato"]

Atanu Shome, CSE, KU


33
List Functions
 Min, max, in, copy
new_fruits = fruits.copy()
new_fruits.append("mango")
print(fruits) # Output: ["apple", "banana", "cherry"] (original list is not modified)
print(new_fruits) # Output: ["apple", "banana", "cherry", "mango"]
is_mango_in_fruits = "mango" in fruits
print(is_mango_in_fruits) # Output: False
numbers = [5, 1, 8, 2]
smallest = min(numbers)
print(smallest) # Output: 1
numbers = [5, 1, 8, 2]
largest = max(numbers)
print(largest) # Output: 8

Atanu Shome, CSE, KU


34
List Access
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

magicians = ['alice', 'david', 'carolina']


for magician in magicians:
print(f"{magician.title()}, that was a great trick!")

Atanu Shome, CSE, KU


35
Numerical List

for value in range(1, 5):


print(value)

print("Append to list")
list = []
for value in range(1, 5):
list.append(value)
print(list)

Atanu Shome, CSE, KU


36
List
 Looping through a slice or sublist

players = ['charles', 'martina', 'michael', 'florence', 'eli', 'atanu', 'jacob']


print("Here are the first three players on my team:")

for player in players[2:5]:


print(player.title())

Atanu Shome, CSE, KU


37
Try Out

 Python program to find unique numbers in a given


list.
 Python program to create a list of 5 random
integers.
 Write a Python program that takes a list of
numbers as input and returns a new list containing
only the even numbers.
 Imagine, one list contains fruit names [‘banana’,
‘mango’] and another one contains number of
fruits [10,25]. Arrange them in a new list such a
way that [‘banana’,
Atanu Shome, CSE, KU
10, ‘mango’, ‘25’]
38
Try Out

 Write a Python program that takes a list containing


duplicate elements and returns a new list with the
duplicates removed, sorted in ascending order.
 Write a Python program that takes a list and an
element as input and returns the index of the first
occurrence of the element in the list, or -1 if the
element is not present.

Atanu Shome, CSE, KU


39
Tuple

 In Python, a tuple is an ordered collection of items


that are similar to lists. However, unlike lists,
tuples are immutable, which means you cannot
modify their elements after they are created.

my_tuple = ("apple", "banana", "cherry")

Atanu Shome, CSE, KU


40
Tuple

 Ordered: Tuples maintain the order in which you


add elements.
 Immutable: Once created, you cannot change the
elements within a tuple.
 Heterogeneous: Tuples can store elements of
different data types.
 Duplicates: Tuples allow duplicate elements within
the collection.

Atanu Shome, CSE, KU


41
Tuple
#Creation
my_tuple = ("apple", "banana", "cherry")
print(my_tuple)

# List to Tuple
my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(my_tuple)

Atanu Shome, CSE, KU


42
Tuple
 Access

my_tuple = ("apple", "banana", "cherry")


first_fruit = my_tuple[0] # first_fruit will be "apple"
print("Single Element",first_fruit)

for fruit in my_tuple:


print(fruit)

Atanu Shome, CSE, KU


43
Tuple
 Can’t modify

dimensions = (200, 50)


dimensions[0] = 250 #Error

Reassign is possible

dimensions = (400, 33)

Atanu Shome, CSE, KU


44
Tuple Functions

 Min, Max,
Length,
Sorted, In,
Concatena
tion

Atanu Shome, CSE, KU


45
Dictionary
 Python dictionaries are another fundamental data structure used to
store collections of data. Unlike lists that use numerical indexes,
dictionaries use key-value pairs for accessing elements.

 Properties of Dictionaries:
 Unordered: The order in which you add key-value pairs to a
dictionary is not preserved.
 Changeable: You can modify or remove elements after creating a
dictionary.
 Heterogeneous Keys: Keys can be of various data types (strings,
numbers, tuples). Keys must be unique within a dictionary.
 Values can be Duplicated: Values can have duplicate data within the
dictionary.
Atanu Shome, CSE, KU
46
Dictionary
#Declare
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
my_dict = dict(name="Bob", age=25)
print(my_dict)

Atanu Shome, CSE, KU


47
Dictionary
#Access
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
name = my_dict["name"] # name will be "Alice"

#Add or modify
my_dict = {"name": "Alice", "age": 30}
my_dict["city"] = "New York" # Adding a new key-value pair
my_dict["age"] = 31 # Modifying an existing value
print(my_dict)

Atanu Shome, CSE, KU


48
Dictionary Usage

if my_dict["age"]<31:
print("Not too old")
elif my_dict["age"] == 31:
print("About to be to buira")
else:
print("Definitely Buro manush")

Atanu Shome, CSE, KU


49
Dictionary
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'php',
}
print(favorite_languages['jen'])
del favorite_languages['jen']
print(favorite_languages)

Atanu Shome, CSE, KU


50
Dictionary
 Not found

var1 = favorite_languages.get("sarah")
print(var1)
var1 = favorite_languages.get("atanu", "not found")
print(var1)

Atanu Shome, CSE, KU


51
Dictionary

 Looping through data

for k, v in favorite_languages.items():
stri = f"Key {k} and value is {v}"
print(stri)

#Only keys
for k in favorite_languages.keys():
print(k)
Atanu Shome, CSE, KU
52
Dictionary
Sorted Access

for k in sorted(favorite_languages.keys()):
print(k)

List in dictionary?

pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
for k, v in pizza.items():
print(f"Key is {k} and value is {v}")
Atanu Shome, CSE, KU
53
Try Out
 Write a Python program that takes a dictionary as input and returns a
new dictionary where the keys and values are swapped. If there are
duplicate values, the new key should be the first occurrence of the
value.

input_dict = {"name": "Alice", "age": 30, "city": "New York"}

# Potential Output: {30: 'age', 'New York': 'city', 'Alice': 'name'}

Atanu Shome, CSE, KU


54
Try Out
 Create a phonebook application using dictionaries. The
dictionary can store contact information where keys are
names (strings) and values are dictionaries containing
details like phone number (string) and email address
(string, optional). Write functions to:
• Add a new contact to the phonebook.
• Search for a contact by name and display their details.
• Update the contact information for an existing contact.
• Delete a contact from the phonebook.

Atanu Shome, CSE, KU


55
Python Operators (Arithmatic)

Atanu Shome, CSE, KU


56
Python Operators (Comparison)

Atanu Shome, CSE, KU


57
Python Operators (Assignment)

Atanu Shome, CSE, KU


58
Python Operators (Bitwise)

Atanu Shome, CSE, KU


59
Python Operators (Logical)

Atanu Shome, CSE, KU


60
Python Operators (In and Not-in)

Atanu Shome, CSE, KU

You might also like