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

Python_Programs_Short

The document contains various Python code snippets demonstrating different programming concepts such as data type conversions, control structures, list and set operations, and object-oriented programming. It also includes examples of using libraries like NumPy, Pandas, and Tkinter for mathematical operations, data manipulation, and GUI creation. Overall, it serves as a practical guide for implementing fundamental programming tasks in Python.

Uploaded by

Tanisha Waichal
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)
10 views

Python_Programs_Short

The document contains various Python code snippets demonstrating different programming concepts such as data type conversions, control structures, list and set operations, and object-oriented programming. It also includes examples of using libraries like NumPy, Pandas, and Tkinter for mathematical operations, data manipulation, and GUI creation. Overall, it serves as a practical guide for implementing fundamental programming tasks in Python.

Uploaded by

Tanisha Waichal
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/ 5

Convert bits to Megabytes, Gigabytes and Terabytes

bits = int(input("Enter bits: "))


mb = bits / (8 * 1024 * 1024)
gb = bits / (8 * 1024 * 1024 * 1024)
tb = bits / (8 * 1024 * 1024 * 1024 * 1024)
print("MB:", mb, "GB:", gb, "TB:", tb)

Check if the input year is a leap year

year = int(input("Enter a year: "))


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Not a leap year")

Print even numbers between 1 to 100 using while loop

i = 1
while i <= 100:
if i % 2 == 0:
print(i, end=" ")
i += 1

Reverse a list

lst = [1, 2, 3, 4, 5]
lst.reverse()
print("Reversed list:", lst)

Built-in list functions

lst = [1, 2, 3, 2]
print("Length:", len(lst))
print("Max:", max(lst))
lst.append(4)
print("After append:", lst)
print("Count of 2:", lst.count(2))
lst.pop()
print("After pop:", lst)

Find repeated items in a tuple

t = (1, 2, 3, 2, 4, 1)
repeats = set([x for x in t if t.count(x) > 1])
print("Repeated items:", repeats)

Find max, min and length of a set

s = {10, 20, 30, 40}


print("Max:", max(s))
print("Min:", min(s))
print("Length:", len(s))
Set operations

a = {1, 2, 3}
b = {3, 4, 5}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
print("Symmetric Difference:", a ^ b)

Sort dictionary by value

d = {'a': 3, 'b': 1, 'c': 2}


print("Ascending:", dict(sorted(d.items(), key=lambda x: x[1])))
print("Descending:", dict(sorted(d.items(), key=lambda x: x[1], reverse=True)))

Factorial using function

def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)

print("Factorial:", factorial(5))

Lambda, map, reduce

from functools import reduce


nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
product = reduce(lambda x, y: x * y, nums)
print("Squared:", squared)
print("Product:", product)

Fibonacci module and import

# fib_module.py
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

# main.py
import fib_module
fib_module.fibonacci(5)

Area of circle using math module

import math
r = float(input("Enter radius: "))
area = math.pi * r * r
print("Area:", area)

User-defined package for arithmetic

# arithmetic.py
def add(x, y): return x + y
def sub(x, y): return x - y

# main.py
import arithmetic
print(arithmetic.add(3, 2))

Matrix operations using NumPy

import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print("Addition:
", a + b)
print("Subtraction:
", a - b)
print("Multiplication:
", a * b)
print("Division:
", a / b)

Rectangle class to compute area

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

r = Rectangle(5, 4)
print("Area:", r.area())

Parameterized constructor

class Student:
def __init__(self, name):
self.name = name

s = Student("Aryan")
print("Name:", s.name)

Method overloading

class Demo:
def show(self, a=None, b=None):
if a and b:
print(a + b)
elif a:
print(a)
else:
print("No args")

d = Demo()
d.show()
d.show(2)
d.show(2, 3)

Data hiding

class MyClass:
def __init__(self):
self.__hidden = 10

def get_hidden(self):
return self.__hidden

obj = MyClass()
print(obj.get_hidden())

Multiple inheritance

class A:
def showA(self):
print("A")

class B:
def showB(self):
print("B")

class C(A, B):


pass

c = C()
c.showA()
c.showB()

Create Series using Pandas

import pandas as pd
data = [1, 2, 3]
s = pd.Series(data)
print(s)

Create DataFrame using list or dictionary

import pandas as pd
data = {'Name': ['A', 'B'], 'Age': [20, 21]}
df = pd.DataFrame(data)
print(df)

Read/write CSV using pandas

import pandas as pd
df = pd.read_csv('data.csv')
df.to_csv('output.csv', index=False)

Registration form using Tkinter

import tkinter as tk
root = tk.Tk()
tk.Label(root, text="Name").pack()
tk.Entry(root).pack()
tk.Checkbutton(root, text="I agree").pack()
tk.Radiobutton(root, text="Male", value=1).pack()
tk.Listbox(root).pack()
tk.Button(root, text="Submit").pack()
root.mainloop()

Select records from DB table

import sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
print(row)

Use of matplotlib to represent data

import matplotlib.pyplot as plt


x = [1, 2, 3]
y = [2, 4, 1]
plt.plot(x, y)
plt.title("Line Graph")
plt.show()

You might also like