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

Python Lab ALL 10 Prgms

The document contains 10 programming tasks related to Python. The tasks cover topics like file permissions checking using os module, linear regression, lambda functions, NumPy arrays, dictionaries, Pandas for CSV files, turtle graphics, packages and modules, matplotlib for plotting, and Flask for a basic login web page.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Python Lab ALL 10 Prgms

The document contains 10 programming tasks related to Python. The tasks cover topics like file permissions checking using os module, linear regression, lambda functions, NumPy arrays, dictionaries, Pandas for CSV files, turtle graphics, packages and modules, matplotlib for plotting, and Flask for a basic login web page.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Python Lab

1. Write a python program to open a file and check what are the access permissions acquired
by that file using os module.

import os

def check_file_permissions(file_path):

if not os.path.exists(file_path):

print(f"The file '{file_path}' does not exist.")

return

try:

mode = os.stat(file_path).st_mode

permissions = {

'readable': bool(mode & 0o400),

'writable': bool(mode & 0o200),

'executable': bool(mode & 0o100)

print(f"File permissions for '{file_path}':")

print(f"Readable: {permissions['readable']}")
print(f"Writable: {permissions['writable']}")

print(f"Executable: {permissions['executable']}")

except OSError as e:

print(f"Error: {e}")

if __name__ == "__main__":

file_path = input("Enter the file path: ")

check_file_permissions(file_path)

2. Write a python program to find the linear regression.


import numpy as np

import matplotlib.pyplot as plt

def estimate_coef(x, y):

n = np.size(x)

m_x = np.mean(x)

m_y = np.mean(y)

SS_xy = np.sum(y*x) - n*m_y*m_x


SS_xx = np.sum(x*x) - n*m_x*m_x

b_1 = SS_xy / SS_xx

b_0 = m_y - b_1*m_x

return (b_0, b_1)

def plot_regression_line(x, y, b):

plt.scatter(x, y, color="m", marker="o", s=30)

y_pred = b[0] + b[1]*x

plt.plot(x, y_pred, color="g")

plt.xlabel('x')

plt.ylabel('y')

plt.show()

def main():

x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])

b = estimate_coef(x, y)

print("Estimated coefficients:\nb_0 = {}\nb_1 = {}".format(b[0], b[1]))

plot_regression_line(x, y, b)

if __name__ == "__main__":

main()

3. Write a program to double a given number and add two numbers using lambda().
# Define the lambda functions

double = lambda x: x * 2

add = lambda x, y: x + y

# Take input from the user

num = int(input("Enter a number: "))

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))


# Apply the lambda functions

result1 = double(num)

result2 = add(num1, num2)

# Display the results

print("Double of", num, "is", result1)

print("Sum of", num1, "and", num2, "is", result2)

4. Write a Python Program to Using a numpy module create an array and check the
following: 1. Type of array 2. Shape of array 3. Type of elements in array.

import numpy as np

# Create an array

array = np.array([[1, 2, 3], [4, 5, 6]])

# 1. Type of array

array_type = type(array)

print("Type of array:", array_type)

# 2. Shape of array
array_shape = array.shape

print("Shape of array:", array_shape)

# 3. Type of elements in array

element_type = array.dtype

print("Type of elements in array:", element_type)

5. Create a dictionary and apply the following methods 1) Print


the dictionary items 2) access items 3) use get() 4)change values 5) use len()
# Create a dictionary

my_dict = {

"name": "John",

"age": 30,

"city": "New York"

# 1. Print the dictionary items

print("Dictionary items:", my_dict)

# 2. Access items
name = my_dict["name"]

age = my_dict["age"]

print("Accessed items - Name:", name, "Age:", age)

# 3. Use get() - The get() method returns the value of the item with the specified key.

city = my_dict.get("city:", "Unknown")

country = my_dict.get("country:", "Not specified")

print("City:", city, "Country:", country)

# 4. Change values

my_dict["age"] = 31

my_dict["city"] = "San Francisco"

print("Updated dictionary:", my_dict)

# 5. Use len()

dict_length = len(my_dict)

print("Length of the dictionary:", dict_length)


6. Write a python code to read a csv file using pandas module and print the first and
last five lines of a file.
import pandas as pd

# Replace 'your_file.csv' with the actual path to your CSV file

file_path = 'your_file.csv'

# Read the CSV file into a pandas DataFrame

df = pd.read_csv(file_path)

# Print the first line (header) of the CSV file

print("First Line (Header):")

print(df.head(1))

# Print the last line of the CSV file

print("\nLast Line:")

print(df.tail(1))
7. Write a python code to set background color and pic and draw a circle using turtle
module.
import turtle

# Set up the screen

screen = turtle.Screen()

screen.title("Turtle Drawing")

screen.bgcolor("lightblue")

# Set the background image

screen.bgpic("path_to_image.png") # Replace with the actual path to your image

# Create a Turtle instance

t = turtle.Turtle()

# Draw a circle

t.penup()
t.goto(0, -100) # Move the turtle to the center of the circle

t.pendown()

t.color("red")

t.begin_fill()

t.circle(100)

t.end_fill()

# Hide the turtle

t.hideturtle()

# Keep the window open until it's closed by the user

turtle.done()

8. Write a python program to create a package, sub -package, modules and create
staff and student function to module.

Creating a Python package with sub-packages, modules, and functions is a multi-step


process. Here's a step-by-step guide to creating such a package structure:

• Create a directory for your package. This will be the root directory of your package.
• Inside the root directory, create a Python package directory. A package directory is a
directory with an _init_.py file. This file can be empty or contain initialization code for your
package.

• Inside the package directory, you can create sub-package directories in the same
way as you created the root package directory, each with their own _init_.py file.

• Inside the sub-packages, you can create Python modules. These are .py files that
contain code and functions.

• Define functions within the modules as needed. In your case, you want to create
staff and student functions.

how to structure your package:

my_package/

_init_.py # Initialization file for the root package

staff_module.py # Module containing the staff function

student_module.py # Module containing the student function

sub_package/

_init_.py # Initialization file for the sub-package

create the Python code for the staff_module.py and student_module.py modules:

staff_module.py:

def staff_function(name):

return f"Hello, {name}! You are a staff member."


student_module.py:

def student_function(name):

return f"Hello, {name}! You are a student."

use these functions by importing them from your package

from my_package.staff_module import staff_function

from my_package.student_module import student_function

staff_result = staff_function("John")

student_result = student_function("Alice")

print(staff_result)

print(student_result)

Make sure that you have a proper directory structure with _init_.py files where needed to
ensure that Python recognizes your directories as packages and sub-packages.

9. Write a python program to plot a bar graph for the car data set.
import matplotlib.pyplot as plt

import pandas as pd

# Load the dataset (replace 'car_data.csv' with your dataset file)

data = pd.read_csv('car_data.csv')
# Extract data for the plot

car_brands = data['Car Brand']

num_cars_sold = data['Number of Cars Sold']

# Create a bar graph

plt.figure(figsize=(10, 6)) # Adjust the figure size if needed

plt.bar(car_brands, num_cars_sold, color='skyblue')

plt.xlabel('Car Brand')

plt.ylabel('Number of Cars Sold')

plt.title('Car Sales by Brand')

plt.xticks(rotation=90) # Rotate x-axis labels for readability if needed

# Display the plot

plt.tight_layout()
plt.show()

10. Write a python program to create a login web page using pycharm.

Creating a login web page involves using a web framework like Flask and HTML for the front-
end. PyCharm is just an integrated development environment (IDE) that you can use for
coding. Here's a simple example of how to create a basic login web page using Python and
Flask in PyCharm:

First, make sure you have Flask installed. You can install it using pip:

pip install Flask

Create a new Python file (e.g., app.py) in your PyCharm project directory and add the
following code:

from flask import Flask, render_template, request, redirect, url_for

app = Flask(_name_)

# A simple user database (for demonstration purposes)

users = {

'username': 'password'

@app.route('/')

def home():

return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():

username = request.form['username']

password = request.form['password']

if username in users and users[username] == password:

return 'Login successful'

else:

return 'Login failed. Please check your username and password.'

if _name_ == '_main_':

app.run(debug=True)

Create a "templates" folder in your project directory and within it, create an HTML file
named login.html with the following content:

<!DOCTYPE html>

<html>

<head>

<title>Login</title>

</head>

<body>

<h1>Login</h1>

<form method="POST" action="/login">

<label for="username">Username:</label>

<input type="text" name="username" id="username" required><br><br>

<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br><br>

<input type="submit" value="Login">

</form>

</body>

</html>

Run your Flask application by executing app.py. You should see a basic login web page at
http://127.0.0.1:5000/.

This is a minimal example. In a real-world application, you would use a proper database for
storing user information, handle sessions, and add security measures to protect against
common web vulnerabilities. This code is just a starting point for creating a simple login page
using Flask and PyCharm.

You might also like