Python is a versatile and powerful programming language widely used in data science, machine learning, and scientific computing. This lab manual covers fundamental concepts and hands-on exercises to help you develop proficiency in Python for data analysis and problem-solving.
On Windows, start Python with writing in command window:
python
To exit Python:
Windows: Press CONTROL-Z + Enter
Use exit()
Run a Python script in command window:
python script.py
Example script (fact.py):
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
print("N, fact(N)")
print("---------")
for n in range(10):
print(n, fact(n))
Assignment:
x = 34 - 23 # Integer
y = "Aslam" # String
z = 3.45 # Float
Operators:
a = 5 + 3 # Addition
b = 7 - 2 # Subtraction
c = 3 * 4 # Multiplication
d = 8 / 2 # Division
e = 10 % 3 # Modulus
Logical Operators:
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
Python uses indentation instead of braces {}:
if x > 10:
print("X is greater than 10")
Comments:
# This is a comment
"""This is a
multi-line comment"""
Creating and manipulating lists:
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Add element
my_list.remove(2) # Remove element
print(my_list[1:3]) # Slicing
Immutable sequences:
my_tuple = (1, 2, 3)
print(my_tuple[0])
Key-value pairs:
my_dict = {"name": "Ali", "age": 25}
print(my_dict["name"])
my_dict["city"] = "Karachi"
Unique unordered collections:
my_set = {1, 2, 3, 4}
my_set.add(5)
print(my_set)
Reading a file:
with open("data.txt", "r") as file:
content = file.read()
Writing to a file:
with open("output.txt", "w") as file:
file.write("Hello, world!")
Importing NumPy and creating arrays:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.shape)
Creating a DataFrame:
import pandas as pd
data = {"Name": ["Ali", "Sara"], "Age": [25, 22]}
df = pd.DataFrame(data)
print(df)
Plotting a simple graph:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y)
plt.show()
This lab manual covers fundamental Python concepts for data science. As you progress, explore more advanced topics such as machine learning, deep learning, and big data processing using Python.