Python_Programs_Short
Python_Programs_Short
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)
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)
t = (1, 2, 3, 2, 4, 1)
repeats = set([x for x in t if t.count(x) > 1])
print("Repeated items:", repeats)
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)
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
print("Factorial:", factorial(5))
# 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)
import math
r = float(input("Enter radius: "))
area = math.pi * r * r
print("Area:", area)
# 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))
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)
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")
c = C()
c.showA()
c.showB()
import pandas as pd
data = [1, 2, 3]
s = pd.Series(data)
print(s)
import pandas as pd
data = {'Name': ['A', 'B'], 'Age': [20, 21]}
df = pd.DataFrame(data)
print(df)
import pandas as pd
df = pd.read_csv('data.csv')
df.to_csv('output.csv', index=False)
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()
import sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
print(row)