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

Python manual

Uploaded by

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

Python manual

Uploaded by

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

1.

Program to check whether the given number is Fibonacci or not

n=int(input("Enter the number: "))


c=0
a=1
b=1
if n==0 or n==1:
print("Yes")
else:
while c<n:
c=a+b
b=a
a=c
if c==n:
print("Fibonacci number")
else:
print("Not a Fibonacci number ")

2. Solve Quadratic Equations


# Solve the quadratic equation ax**2 + bx + c = 0
import cmath
a=1
b=5
c=6
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

3. Sum of n natural numbers


num = 5
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
4. Display Multiplication Tables

num = 5
for i in range(1, 11):
print(num, 'x', i, '=', num*i)

5. Program to check whether the given number is prime or not


num = 20
flag = False
if num == 1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

6. Program to demonstrate Linear search


def linearSearch(array, n, x):
for i in range(0, n):
if (array[i] == x):
return i
return -1
array = [2, 4, 0, 1, 9]
x=1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)
7. Create a calculator program
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

next_calculation = input("Let's do next calculation? (yes/no): ")


if next_calculation == "no":
break
else:
print("Invalid Input")
8. Explore string functions
text = 'hELlO worLd'
print("\nConverted String:")
print(text.upper())
print("\nConverted String:")
print(text.lower())
print("\nConverted String:")
print(text.title())
print("\nConverted String:")
print(text.swapcase())
print("\nConverted String:")
print(text.capitalize())
print("\nOriginal String")
print(text)

9. Program to implement selection sort


def selectionSort(array, size):
for ind in range(size):
min_index = ind
for j in range(ind + 1, size):
# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747]


size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
10. Implement Stack
def create_stack():
stack = []
return stack
def check_empty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
print("pushed item: " + item)
def pop(stack):
if (check_empty(stack)):
return "stack is empty"
return stack.pop()

stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
11. Write a program to read and write into a file.
file_name = input("Enter the name of the file to create and write to: ")
try:
with open(file_name, 'w') as file:
content = input("Enter the content to write to the file: ")
file.write(content)
print(f"Content has been written to '{file_name}'.")
except FileNotFoundError:
print(f"File '{file_name}' not found.")
try:
with open(file_name, 'r') as file:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
print(f"File '{file_name}' not found.")
12. Write a Program to basic regular expression

import re

str="hello world "

a=re.findall("l",str)

print(a)

b=re.search("o",str)

print(b.start())

d=re.sub("llo","abc",str)

print(d)

c=re.split("w",str)

print(c)
PART B
13) Demonstrate use of List.
list=[]
print("How many element do you want to insert into a list")
n=int(input())
print("Enter {0} element".format(n))
for i in range(n):
ele=int(input())
list.append(ele)
print(list)
print("The maximum element in the list:",max(list))
print("The minimum element in the list:",min(list))
print("The number of element in the list:",len(list))
list.sort()
print("The list after sorting")
print(list)
list.reverse()
print("The list after reverse")
print(list)

14) Demonstrate use of Dictionaries.


dist={}
n=int(input("How many element do you want to insert into dictionaries"))
for i in range(n):
key=input("Enter key name")
value=input("Enter key value")
dist[key]=value
print(dist)
print("Keys in dictionaries")
print(dist.keys())
print("Values in dictionaries")
print(dist.values())
print("After updates",dist)
i=input("Enter the key to access the values to the given key")
print(dist.get(i))
nm=input("Enter the key to remove the key value pair from the dictionaries")
del dist[nm]
print(dist)
print("After deleting the key")
print(dist)
dist.clear()
print("After clearing the dictionaries")
print(dist)

15) Create a GUI using Tkinter module.


import tkinter as tk
from tkinter import messagebox
def mess():
messagebox.showinfo("message","Hello,Welcome")
r=tk.Tk()
r.title("GUI PROGRAM")
r.geometry("500x500")
label=tk.Label(text="GUI")
label.pack()
button=tk.Button(text="Click me",command=mess)
button.pack()
r.mainloop()

16) Demonstrate Exceptions in python.


try:
a=10
b=0
result=a/b
print(result)
except:
print("Error: divide zero exception")
else:
print("no exception has occurred")
finally:
print("Exception has occurred and handled")

17) Drawing Line chart and Bar chart using Matplotlib.


import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[2,4,5,6,7]
plt.subplot(1,2,1)
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.title("line plot")
plt.plot(x,y)

x=["role","age","marks","number"]
y=[3,1,5,6]
plt.subplot(1,2,2)
plt.bar(x,y)
plt.title("bar plot")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()

18) Drawing Histogram and Pie chart using Matplotlib.


import matplotlib.pyplot as plt
import numpy as np
x=np.random.randint(0,5,50)
print(x)
plt.subplot(1,2,1)
plt.hist(x)

sub=['p','c','m','b']
mark=[90,34,56,23]
plt.subplot(1,2,2)
plt.pie(mark,labels=sub)
plt.show()
9) Create Array using NumPy and Perform Operations on array.
import numpy as np
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2,3],[4,5,6],[7,8,9]]
n1=np.array(a)
n2=np.arry(b)
print(“ADD”,n1+n2)
print(“SUB”,n1-n2)
print(“MUL”,n1*n2)
print(“DIV”,n1/n2)

10) Create DataFrameform Excel sheet using Pandas and Perform Operations on DataFrames.
import pandas as pd
df=pd.read_excel(“data.xlsx”)
print(df)
df[‘age’]=df[‘age’]+10

age=df[‘age’]
print(age)

print(“Sorting the Marks:”,df.sort_values(by=”mark”))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy