Lecture 4 EDGE Python Data Science
Lecture 4 EDGE Python Data Science
Python Basics
2
Learning Objectives Today
Python Variables
Data Types
String
Casting
List
Tuple
Dictionary
Operators
age = 30
name = "Alice"
pi = 3.14159
num1 = 5
num1 = 3.45
Num1 = 10
print(id(num1)) #Shows the RAM location where
this is saved
del num1
print(num1)
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)
print(multiline_text)
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
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
# 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
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.
#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])
bicycles.append("Duranta")
print(bicycles)
bicycles.insert(3, "Racer")
print(bicycles)
print(sublist)
my_list.sort()
print(my_list)
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]
my_list.reverse()
print(my_list)
print(len(my_list))
print("Append to list")
list = []
for value in range(1, 5):
list.append(value)
print(list)
# List to Tuple
my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(my_tuple)
Reassign is possible
Min, Max,
Length,
Sorted, In,
Concatena
tion
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)
#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)
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")
var1 = favorite_languages.get("sarah")
print(var1)
var1 = favorite_languages.get("atanu", "not found")
print(var1)
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.