1) Reverse a string using a class
class ReverseString:
def __init__(self, text):
[Link] = text
def reverse(self):
return [Link][::-1]
obj = ReverseString("hello")
print([Link]())
2) Factors of a number
num = int(input("Enter number: "))
for i in range(1, num + 1):
if num % i == 0:
print(i)
3) Swap two numbers
a = int(input("Enter first: "))
b = int(input("Enter second: "))
a, b = b, a
print(a, b)
4) Fibonacci series using generator
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
n = int(input("How many terms? "))
for i in fib(n):
print(i)
5) Calculator class
class Calc:
def add(self, a, b): return a + b
def sub(self, a, b): return a - b
def mul(self, a, b): return a * b
def div(self, a, b): return a / b
c = Calc()
print([Link](5, 3))
6) Recursive factorial
def fact(n):
if n == 0 or n == 1:
return 1
return n * fact(n - 1)
print(fact(5))
7) Check if key exists
data = {"name": "Arjun", "age": 20}
key = input("Enter key: ")
if key in data:
print(data[key])
else:
print("Not found")
8) Tkinter Entry insert/delete
from tkinter import *
root = Tk()
e = Entry(root); [Link]()
def insert_text(): [Link](0, "Hello")
def delete_text(): [Link](0, END)
Button(root, text="Insert", command=insert_text).pack()
Button(root, text="Delete", command=delete_text).pack()
[Link]()
9) Tkinter alert
from tkinter import *
from tkinter import messagebox
root = Tk()
def show(): [Link]("Alert","Clicked")
Button(root,text="Click",command=show).pack()
[Link]()
10) Cylinder GUI
from tkinter import *
import math
root = Tk()
def calc():
r=float([Link]()); h=float([Link]())
sa=2*[Link]*r*(r+h); v=[Link]*r*r*h
[Link](text=str(sa)); [Link](text=str(v))
e1=Entry(root); [Link]()
e2=Entry(root); [Link]()
Button(root,text="Compute",command=calc).pack()
l1=Label(root); [Link]()
l2=Label(root); [Link]()
[Link]()
11) Reverse number
num=int(input("Enter: "))
rev=0
while num>0:
digit=num%10
rev=rev*10+digit
num//=10
print(rev)
12) Count vowels
text=input("Enter: ")
vowels="aeiouAEIOU"
count=0
for ch in text:
if ch in vowels:
count+=1
print(count)
13) Prime check
num=int(input("Enter: "))
if num<2: print("Not prime")
else:
for i in range(2,num):
if num%i==0:
print("Not prime"); break
else:
print("Prime")
14) Largest of three
a=int(input()); b=int(input()); c=int(input())
if a>=b and a>=c: print(a)
elif b>=a and b>=c: print(b)
else: print(c)
15) Palindrome
text=input("Enter: ")
if text==text[::-1]: print("Palindrome")
else: print("Not Palindrome")
16) Sum of list
lst=[1,2,3,4,5]
total=0
for n in lst: total+=n
print(total)
17) Remove duplicates
lst=[1,2,2,3,4,4]
u=[]
for x in lst:
if x not in u:
[Link](x)
print(u)
18) Celsius to Fahrenheit
c=float(input("Enter C: "))
f=(c*9/5)+32
print(f)
19) Multiplication table
num=int(input("Enter: "))
for i in range(1,11):
print(num,"x",i,"=",num*i)
20) Count words
text=input("Enter: ")
words=[Link]()
print(len(words))