0% found this document useful (0 votes)
12 views16 pages

Python Basic Programs and Examples

The document contains a collection of Python basic programs covering various topics such as checking for palindromes, leap years, prime numbers, Armstrong numbers, and more. Each program includes input prompts, logic, and outputs, demonstrating fundamental programming concepts. The document serves as a practical guide for beginners to learn and practice Python programming.
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)
12 views16 pages

Python Basic Programs and Examples

The document contains a collection of Python basic programs covering various topics such as checking for palindromes, leap years, prime numbers, Armstrong numbers, and more. Each program includes input prompts, logic, and outputs, demonstrating fundamental programming concepts. The document serves as a practical guide for beginners to learn and practice Python programming.
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

Python Basic Programs

Output:
1. Python program to
check whether a string is Performed By Abdullah Boat
Enter Year: 2020
palindrome or not Its Leap year
print("Performed By Abdullah Boat")
str = input("Enter String: ")
str = [Link]().strip()
rev = ""
3. Python Program to Print
length = len(str) all Prime Numbers in an
for i in range(length-1,-1,-1):
rev += str[i] Interval
if(rev == str): print("Performed By Abdullah Boat")
print("This Palindrome") start = int(input("Enter the start of the
else: interval: "))
print("Not a Palindrome") end = int(input("Enter the end of the interval:
"))

Output: for num in range(start, end + 1):


if num > 1:
Performed By Abdullah Boat
for i in range(2, int(num ** 0.5) + 1):
Enter String: Abdullah
if num % i == 0:
Not a Palindrome
break
else:
print(num, end=" ")
2. Python Program to
Check Leap Year Output:
print("Performed By Abdullah Boat")
Performed By Abdullah Boat
#Python Program to Check Leap Year
Enter the start of the interval: 1
year = int(input("Enter Year: "))
Enter the end of the interval: 50
if((year%400 == 0) and (year % 100 == 0) ):
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
print("Its Leap year")
elif(year % 4 == 0 and year % 100 != 0):
print("Its Leap year")
else: 4. Python Program to
print("Its not Leap year")
Check Armstrong Number
print("Performed By Abdullah Boat")
number = int(input('Enter Number: '))
6. Find the Common
num = str(number) Elements Between Two
len = len(num)
arm = 0
Lists
for i in range(len): print("Performed By Abdullah Boat")
arm += int(num[i]) ** len l1 = [1,2,3,1,2,15,4,78,6]
if(number == arm): l2 = [1,2,3,25,75,6]
print("Its an armstrong number") s1 = set(l1)
else: s2 = set(l2)
print("Its not an armstrong number") common = [Link](s2)
print(common)

Output:
Output:
Performed By Abdullah Boat
Enter Number: 153 Performed By Abdullah Boat
Its an armstrong number {1, 2, 3, 6}

5. Count the Occurrence


of Each Character in a
String
print("Performed By Abdullah Boat")
s = input("Enter a String: ").lower().strip()

for ch in set(s):
print(f"{ch} Occurrence is: {[Link](ch)}")

Output:

Performed By Abdullah Boat


Enter a String: Abdullah
n Occurrence is: 1
b Occurrence is: 1
d Occurrence is: 1
l Occurrence is: 2
h Occurrence is: 1
a Occurrence is: 2
u Occurrence is: 1
Tuple
print(f"Merged Tuple with removed dublicate
1. Count the occurrences elements are: {t3}")

of an element in a tuple
print("Performed By Abdullah Boat") Output:
t1 = (1, 1, 15, 15, 25, 25, 6, 1, 2)
Performed By Abdullah Boat
temp = set()
Merged Tuple with removed dublicate
elements are: (1, 15, 25, 6, 2, 18, 20)
for i in t1:
if i not in temp:
print(f"{i} occurred in tuple {[Link](i)}
times") 3. Find the first and last
[Link](i)
elements of a tuple
print("Performed By Abdullah Boat")
Output: t1 = (1,2,3,4,5,6,7,8,9,0)
length = len(t1)
Performed By Abdullah Boat
1 occurred in tuple 3 times
print(f"First element from tuple is : {t1[0]}")
15 occurred in tuple 2 times
print(f"Last element from tuple is :
25 occurred in tuple 2 times
{t1[length-1]}")
6 occurred in tuple 1 times
2 occurred in tuple 1 times
Output:

Performed By Abdullah Boat


2. Merge two tuples and First element from tuple is : 1
remove duplicates Last element from tuple is : 0

print("Performed By Abdullah Boat")


t1 = (1, 1, 15, 15, 25, 25, 6, 1, 2)
t2 = (1, 1, 15, 18, 25, 20) 4. Find the difference
temp = t1 + t2
t3 = () between two tuples
for i in temp: print("Performed By Abdullah Boat")
if i not in t3: t1 = (1, 2, 3, 4, 5)
t3 += (i,) t2 = (4, 5, 6, 7, 8)
difference = set(t1) - set(t2)

diff = tuple(difference) 6. Find the frequency of


each element in a tuple
print(diff)
print("Performed By Abdullah Boat")
t1 = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
Output: frequency = {}

Performed By Abdullah Boat for i in t1:


(1, 2, 3) if i in frequency:
frequency[i] += 1
else:
frequency[i] = 1
5. Check if a tuple is a
subset of another tuple print(frequency)

print("Performed By Abdullah Boat")


t1 = (1, 2, 3, 4, 5) Output:
t2 = (4, 5, 6, 7, 8)
s1 = set(t1) Performed By Abdullah Boat
s2 = set(t2) {1: 1, 2: 2, 3: 3, 4: 4}
subset = [Link](s2)
print(f"Subset of t1 : {subset}")

Output:

Performed By Abdullah Boat


Subset of t1 : False

Dictionary
print(dict)
1. Create a dictionary with
default values using the Output:
[Link]() method Performed By Abdullah Boat
print("Performed By Abdullah Boat") {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}
keys = ("a", "b", "c", "d", "e")

dict = [Link](keys, 0)
Performed By Abdullah Boat
2. Count the number of
Are dict1 and dict2 equal? False
occurrences of each Merged dict is: {'a': 0, 'b': 0, 'h': 1, 'i': 1, 'n': 1,
'v': 1, 'c': 0, 'd': 0, 'e': 0}
character in a string using
a dictionary
print("Performed By Abdullah Boat") 4. Create a dictionary
temp_dic = {}
str = "Abdullah" where the values are
str = [Link]().strip() squares of the keys
for char in str: print("Performed By Abdullah Boat")
if char in temp_dic: dic = {}
temp_dic[char] += 1 length = 5
else: for i in range(1, length):
temp_dic[char] = 1 dic[i] = i ** 2
print(dic)
print(temp_dic)

Output:
Output:
Performed By Abdullah Boat
Performed By Abdullah Boat {1: 1, 2: 4, 3: 9, 4: 16}
{'a': 2, 'b': 1, 'd': 1, 'u': 1, 'l': 2, 'h': 1}

5. Find the key with the


3. Check if two maximum value in a
dictionaries are equal and dictionary
Merge two dictionaries print("Performed By Abdullah Boat")
print("Performed By Abdullah Boat") data = {'a': 10, 'b': 25, 'c': 5, 'd': 30, 'e': 20}
dict1 = {'a': 2, 'b': 1, 'h': 1, 'i': 1, 'n': 1, 'v': 1}
dict2 = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0} max_key = max(data, key=[Link])

print(f"Are dict1 and dict2 equal? {dict1 == print(f"Key with the maximum value:
dict2}") {max_key}")

[Link](dict2)
Output:
print(f"Merged dict is: {dict1}")
Performed By Abdullah Boat
Key with the maximum value: d
Output:
print(sorted_dict)
6. Sort a dictionary by its
keys
Output:
print("Performed By Abdullah Boat")
my_dict = {'banana': 3, 'apple': 5, 'cherry': 2, Performed By Abdullah Boat
'date': 4} {'apple': 5, 'banana': 3, 'cherry': 2, 'date': 4}

# Sorting by keys
sorted_dict = dict(sorted(my_dict.items()))

String
1. Python Program to Sort print(clean_text)

Words in Alphabetic Order


print("Performed By Abdullah Boat") Output:
text = input("Enter a sentence: ")
Performed By Abdullah Boat
words = [Link]()
Hello World Hows it going
[Link]()
print("Sorted words:", " ".join(words))

3. Generate Random
Output:
String
Performed By Abdullah Boat
print("Performed By Abdullah Boat")
Enter a sentence: Abdullah Boat is here
import random
Sorted words: Abdullah Boat here is
import string

def generate_random_string(length):
2. Python Program to characters = string.ascii_letters +
[Link]
Remove Punctuation return ''.join([Link](characters,
From a String k=length))

print("Performed By Abdullah Boat") random_string =


import string generate_random_string(10)
print("Random String:", random_string)
text = "Hello, World! How's it going?"
clean_text = [Link]([Link]('',
'', [Link])) Output:
Performed By Abdullah Boat result = find_substring_occurrences(text,
Random String: 9C080SvWQe substring)
print("Occurrences at indices:", result)

4. Reverse Words in a Output:


String Performed By Abdullah Boat
print("Performed By Abdullah Boat") Enter the main string: Abdullah
def reverse_words(sentence): Enter the substring to find: ll
words = [Link]() Occurrences at indices: [5]
reversed_sentence = " ".join(word[::-1] for
word in words)
return reversed_sentence
text = input("Enter a sentence: ")
result = reverse_words(text)
print("Reversed words sentence:", result)

Output:

Performed By Abdullah Boat


Enter a sentence: Abdullah
Reversed words sentence: halludbA

5. Find Substring
Occurrences
print("Performed By Abdullah Boat")
def find_substring_occurrences(text,
substring):
indices = []
start = 0
while True:
start = [Link](substring, start)
if start == -1:
break
[Link](start)
start += 1
return indices
text = input("Enter the main string: ")
substring = input("Enter the substring to
find: ")
List
1. Python Program to 3. Python Program to add
compare two lists two lists
print("Performed By Abdullah Boat")
print("Performed By Abdullah Boat")
def have_same_elements(list1, list2):
list1 = [1, 2, 3]
return sorted(list1) == sorted(list2)
list2 = [4, 5, 6]
list1 = [1, 2, 3, 4]
result = list1 + list2
list2 = [4, 3, 2, 1]
print("Concatenated List:", result)
print("List1 and List2 have the same
elements:", have_same_elements(list1,
list2)) Output:

Performed By Abdullah Boat


Output: Concatenated List: [1, 2, 3, 4, 5, 6]

Performed By Abdullah Boat


List1 and List2 have the same elements:
True 4. Python Program to
convert List to Set
print("Performed By Abdullah Boat")
2. Python Program to my_list = [1, 2, 3, 4, 4, 5, 5, 6]
convert list to dictionary my_set = set(my_list)
print("Set:", my_set)
print("Performed By Abdullah Boat")
keys = ["name", "age", "city"]
dict_from_list = [Link](keys, Output:
"Unknown")
print("Dictionary:", dict_from_list) Performed By Abdullah Boat
Set: {1, 2, 3, 4, 5, 6}

Output:

Performed By Abdullah Boat 5. Python Program to


Dictionary: {'name': 'Unknown', 'age':
'Unknown', 'city': 'Unknown'}
convert list to string
print("Performed By Abdullah Boat")
my_list = ["Hello", "World", "Python"]
result = " ".join(my_list)
print("String:", result)

Output:

Performed By Abdullah Boat


String: Hello World Python

6. Find second largest


element in a list
print("Performed By Abdullah Boat")
def second_largest(numbers):
if len(numbers) < 2:
return "List must have at least two
unique numbers"
unique_numbers = list(set(numbers))
unique_numbers.sort(reverse=True)
return unique_numbers[1] if
len(unique_numbers) > 1 else "No second
largest element"
num_list = [10, 20, 4, 45, 99, 99, 20]
print("Second largest number:",
second_largest(num_list))

Output:

Performed By Abdullah Boat


Second largest number: 45
Python Function Programs
Output:
1. Python Program to Find
HCF Performed By Abdullah Boat
Result: 15
print("Performed By Abdullah Boat")
def find_hcf(a, b):
while b:
a, b = b, a % b 3. Python program to print
return a
print("HCF:", find_hcf(12, 18)) all disarium numbers
between 1 to 100
Output: print("Performed By Abdullah Boat")
def is_disarium(num):
Performed By Abdullah Boat digits = str(num)
HCF: 6 total = 0

for i in range(len(digits)):
total += int(digits[i]) ** (i + 1)
2. Python Program to
Make a Simple Calculator return total == num

print("Performed By Abdullah Boat") disarium_numbers = []


def calculator(a, b, operation): for n in range(1, 101):
if operation == '+': if is_disarium(n):
return a + b disarium_numbers.append(n)
elif operation == '-':
return a - b print("Disarium numbers:",
elif operation == '*': disarium_numbers)
return a * b
elif operation == '/':
return a / b if b != 0 else "Cannot divide Output:
by zero"
else: Performed By Abdullah Boat
return "Invalid operation" Disarium numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9,
89]
print("Result:", calculator(10, 5, '+'))
4. Python Program to 6. Merge two sorted lists
Display Fibonacci into one sorted list
Sequence Using print("Performed By Abdullah Boat")
def merge_sorted_lists(list1, list2):
Recursion return sorted(list1 + list2)
print("Performed By Abdullah Boat")
def fibonacci(n): print("Merged List:", merge_sorted_lists([1,
a, b = 0, 1 3, 5], [2, 4, 6]))
sequence = []

for _ in range(n): Output:


[Link](a)
Performed By Abdullah Boat
a, b = b, a + b
Merged List: [1, 2, 3, 4, 5, 6]
return sequence

print("Fibonacci sequence:", fibonacci(10))

Output:

Performed By Abdullah Boat


Fibonacci sequence: [0, 1, 1, 2, 3, 5, 8, 13,
21, 34]

5. Python Program to Find


Factorial of Number Using
Recursion
print("Performed By Abdullah Boat")
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)

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

Output:

Performed By Abdullah Boat


Factorial: 120
Important Programs
1. Display Pattern 3. List Operations Output
print("Performed By Abdullah Boat")
Outputs of given code:
num = 2 # Starting number
i) >>> a=[2,5,1,3,6,9,7] >>> a[2:6]=[2,4,9,0]
for i in range(1, 4):
>>> print(a)
for j in range(i * 2 - 1): # Print i * 2 - 1
Output: [2, 5, 2, 4, 9, 0, 7] (Elements from
numbers
index 2 to 5 are replaced with new list)
print(num, end=" ")
num += 2
ii) >>> b = ["Hello", "Good"]
print()
>>> [Link]("python")
>>> print(b)
Output: ['Hello', 'Good', 'python']
Output:
(New element "python" is added at the end)
Performed By Abdullah Boat
2 iii) >>> t1=[3,5,6,7]
468 print(t1[2]) → 6 (element at index 2)
10 12 14 16 18 print(t1[-1]) → 7 (last element)
print(t1[2:]) → [6, 7] (from index 2 to end)
print(t1[:]) → [3, 5, 6, 7] (entire list)

2. Print Number Pattern


print("Performed By Abdullah Boat") 4. List Slicing Output
for i in range(1, 5):
for j in range(1, i + 1): indices = ['zero', 'one', 'two', 'three', 'four',
print(j, end=" ") 'five']
print() i) indices[:4] → ['zero', 'one', 'two', 'three']
(from start to index 3)
ii) indices[-2:] → ['four', 'five'] (last 2
Output: elements)

Performed By Abdullah Boat


1
12 5. Class Inheritance
123 Example
1234
print("Performed By Abdullah Boat")
class Animal:
def feed(self): print(f"Mobile Number:
print("Animal is feeding") {self.mobile_number}")

class Herbivorous(Animal): student = Student()


def feed(self): # Overriding the parent student.read_info()
method student.print_info()
print("Herbivorous animal is eating
plants")
Output:
herb = Herbivorous()
[Link]() Performed By Abdullah Boat
Enter name: Abdullah Boat
Enter roll number: 21
Output: Enter department: CO
Enter mobile number: 9321009205
Performed By Abdullah Boat Student Information:
Herbivorous animal is eating plants Name: Abdullah Boat
Roll Number: 21
Department: CO
Mobile Number: 9321009205
6. Student Class Example
print("Performed By Abdullah Boat")
class Student:
def __init__(self):
[Link] = ""
self.roll_number = ""
[Link] = ""
self.mobile_number = ""

def read_info(self):
[Link] = input("Enter name: ")
self.roll_number = input("Enter roll
number: ")
[Link] = input("Enter
department: ")
self.mobile_number = input("Enter
mobile number: ")

def print_info(self):
print("Student Information:")
print(f"Name: {[Link]}")
print(f"Roll Number:
{self.roll_number}")
print(f"Department: {[Link]}")
File Handling and Exception Handling
number = float(input("Enter a number:
1. Count Words in Each "))
if number < 0:
Line of a File raise NegativeValueError("Negative
print("Performed By Abdullah Boat") numbers are not allowed!")
def count_words_in_file(filename): print(f"You entered: {number}")
try: except NegativeValueError as e:
with open(filename, 'r') as file: print(e)
for line_number, line in except ValueError:
enumerate(file, 1): print("Please enter a valid number!")
words = [Link]()
print(f"Line {line_number}: check_positive_number()
{len(words)} words")
except FileNotFoundError:
print("File not found!") Output:

Performed By Abdullah Boat


count_words_in_file("[Link]")
Enter a number: -2
Negative numbers are not allowed!
Output:

Performed By Abdullah Boat


Line 1: 5 words
3.
Line 2: 0 words InsufficientBalanceExcept
Line 3: 37 words
ion Example
print("Performed By Abdullah Boat")
class
2. User-defined Exception InsufficientBalanceException(Exception):
for Negative Values pass

print("Performed By Abdullah Boat") class BankAccount:


class NegativeValueError(Exception): def __init__(self, balance):
pass [Link] = balance

def check_positive_number(): def withdraw(self, amount):


try: try:
if amount > [Link]:
raise consonant_count += 1
InsufficientBalanceException("Insufficient
balance for withdrawal!") print(f"Total characters: {total_chars}")
[Link] -= amount print(f"Vowels: {vowel_count}")
print(f"Withdrawal successful! New print(f"Consonants:
balance: {[Link]}") {consonant_count}")
except InsufficientBalanceException as print(f"Spaces: {space_count}")
e:
print(e) except FileNotFoundError:
print("File not found!")
account = BankAccount(1000)
[Link](500) # Works analyze_file_content("[Link]")
[Link](700) # Raises exception

Output:
Output:
Performed By Abdullah Boat
Performed By Abdullah Boat Total characters: 328
Withdrawal successful! New balance: 500 Vowels: 108
Insufficient balance for withdrawal! Consonants: 162
Spaces: 43

4. Analyze Text File


Content 5. Append Content to a
print("Performed By Abdullah Boat")
File
def analyze_file_content(filename): print("Performed By Abdullah Boat")
vowels = 'aeiouAEIOU' def append_to_file(filename, content):
total_chars = 0 try:
vowel_count = 0 with open(filename, 'a') as file: # 'a'
consonant_count = 0 mode for append
space_count = 0 [Link](content + '\n')
print("Content appended
try: successfully!")
with open(filename, 'r') as file: except IOError:
content = [Link]() print("An error occurred while writing to
total_chars = len(content) the file!")
for char in content:
if [Link](): # Example usage
space_count += 1 append_to_file("[Link]", "This is new
elif [Link](): content being appended.")
if char in vowels:
vowel_count += 1
else: Output:
Performed By Abdullah Boat
Content appended successfully!

6. Count Characters After


First 20 in a File
print("Performed By Abdullah Boat")
def count_chars_after_20(filename):
try:
with open(filename, 'r') as file:
content = [Link]()
if len(content) <= 20:
print("File has 20 or fewer
characters!")
print(f"Total characters:
{len(content)}")
else:
chars_after_20 = len(content[20:])
print(f"Total characters after first
20: {chars_after_20}")
print(f"Total file characters:
{len(content)}")
except FileNotFoundError:
print("File not found!")

# Example usage
count_chars_after_20("[Link]")

Output:

Performed By Abdullah Boat


Total characters after first 20: 344
Total file characters: 364

You might also like