Class 12 Python Programs
Class 12 Python Programs
def is_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
print(is_prime(29))
Fibonacci Series
def fibonacci(n):
fib_series = [0, 1]
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
print(fibonacci(10))
Sum of Digits
def sum_of_digits(n):
if n == 0:
return 0
print(sum_of_digits(1234))
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
Simple Calculator
if operation == '+':
return a + b
return a - b
return a * b
return a / b
print(calculator(10, 5, '+'))
def count_vowels_consonants(string):
vowels = "aeiouAEIOU"
c_count = len([char for char in string if char.isalpha() and char not in vowels])
print(count_vowels_consonants("Hello World"))
Reverse a String
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
Palindrome Checker
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("radar"))
Sorting a List
def sort_list(lst):
return sorted(lst)
print(sort_list([4, 3, 1, 2]))
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
def frequency_counter(lst):
return Counter(lst)
print(frequency_counter([1, 2, 2, 3, 4, 4, 5]))
def read_write_file():
data = infile.read()
outfile.write(data)
lines = file.readlines()
Student Class
class Student:
self.name = name
self.age = age
self.grade = grade
class BankAccount:
self.owner = owner
self.balance = balance
self.balance += amount
self.balance -= amount
account1 = BankAccount("Alice", 1000)
account1.deposit(500)
print(account1.balance)
Stack Implementation
class Stack:
def __init__(self):
self.items = []
self.items.append(item)
def pop(self):
return self.items.pop()
stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())
Binary Search
if arr[mid] == target:
return mid
left = mid + 1
else:
right = mid - 1
return -1
import numpy as np
print(array * 2)
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()