0% found this document useful (0 votes)
34 views9 pages

Python Programming Basics: 50 Examples

The document contains a comprehensive set of Python programming exercises organized into five units, covering basic concepts, data types, flow control, functions, and file handling. Each unit includes ten programs that demonstrate various programming techniques and functionalities in Python. The exercises range from simple tasks like printing names and calculating sums to more complex operations like file manipulation and exception handling.

Uploaded by

b3262508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views9 pages

Python Programming Basics: 50 Examples

The document contains a comprehensive set of Python programming exercises organized into five units, covering basic concepts, data types, flow control, functions, and file handling. Each unit includes ten programs that demonstrate various programming techniques and functionalities in Python. The exercises range from simple tasks like printing names and calculating sums to more complex operations like file manipulation and exception handling.

Uploaded by

b3262508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

✅ UNIT I – Overview of Python (10

Programs)

1. Print your name 5 times.


for i in range(5):
print("My Name")

2. Print the ASCII value of a character.


ch = input("Enter a character: ")
print("ASCII value:", ord(ch))

3. Take two numbers and display their sum.


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)

4. Read radius and compute area of circle.


r = float(input("Enter radius: "))
area = 3.14 * r * r
print("Area of circle:", area)

5. Program to check variable type after input.


value = input("Enter something: ")
print("Data type:", type(value))

6. Convert string input into integer and float.


s = input("Enter a number: ")
print("As integer:", int(s))
print("As float:", float(s))

7. Accept three values and print them formatted.


a, b, c = input("Enter three values: ").split()
print("Value 1 =", a)
print("Value 2 =", b)
print("Value 3 =", c)

8. Display Python version.


import sys
print("Python version:", [Link])
9. Demonstrate escape characters.
print("Hello\nWorld")
print("Name:\tPython")

10. Count words in a sentence.


s = input("Enter a sentence: ")
words = [Link]()
print("Number of words:", len(words))

✅ UNIT II – Data Types and Operations (10


Programs)

11. Find the largest of three numbers.


a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))

if a >= b and a >= c:


print("Largest:", a)
elif b >= c:
print("Largest:", b)
else:
print("Largest:", c)

12. Check even or odd.


n = int(input("Enter number: "))
print("Even" if n % 2 == 0 else "Odd")

13. Convert string to uppercase (no upper()).


s = input("Enter string: ")
result = ""

for ch in s:
if 'a' <= ch <= 'z':
result += chr(ord(ch) - 32)
else:
result += ch

print(result)

14. Print characters one by one.


s = input("Enter string: ")
for ch in s:
print(ch)

15. Reverse list (no reverse/slicing).


lst = [1, 2, 3, 4, 5]
rev = []

for i in range(len(lst)-1, -1, -1):


[Link](lst[i])

print("Reversed list:", rev)

16. Find common elements of two lists.


l1 = [1, 2, 3, 4]
l2 = [3, 4, 5, 6]

common = []
for x in l1:
if x in l2:
[Link](x)

print("Common:", common)

17. Count frequency of elements.


lst = [1, 2, 2, 3, 3, 3]
freq = {}

for x in lst:
if x in freq:
freq[x] += 1
else:
freq[x] = 1

print(freq)

18. Remove duplicates from list.


lst = [1, 2, 2, 3, 4, 4]
unique = []

for x in lst:
if x not in unique:
[Link](x)

print(unique)

19. Dictionary of squares from 1 to n.


n = int(input("Enter n: "))
d = {}

for i in range(1, n+1):


d[i] = i*i

print(d)
20. Convert list of tuples into dictionary.
lst = [(1, "A"), (2, "B"), (3, "C")]
d = dict(lst)
print(d)

✅ UNIT III – Flow Control (10 Programs)

21. Check divisibility by 7.


n = int(input("Enter number: "))
print("Divisible" if n % 7 == 0 else "Not divisible")

22. Print numbers 10 to 1.


for i in range(10, 0, -1):
print(i)

23. Sum of first n natural numbers.


n = int(input("Enter n: "))
s = 0
for i in range(1, n+1):
s += i
print("Sum =", s)

24. Count digits of a number.


n = int(input("Enter number: "))
count = 0

while n > 0:
count += 1
n //= 10

print("Digits:", count)

25. Print odd numbers in range.


a = int(input("Start: "))
b = int(input("End: "))

for i in range(a, b+1):


if i % 2 != 0:
print(i)

26. Find factorial (loop).


n = int(input("Enter number: "))
f = 1
for i in range(1, n+1):
f *= i

print("Factorial =", f)

27. Multiplication table.


n = int(input("Enter number: "))
for i in range(1, 11):
print(n, "x", i, "=", n*i)

28. Star pattern.


n = int(input("Enter rows: "))
for i in range(1, n+1):
print("*" * i)

29. Fibonacci series.


n = int(input("Enter terms: "))
a, b = 0, 1

for i in range(n):
print(a, end=" ")
a, b = b, a + b

30. Armstrong numbers 1–1000.


for num in range(1, 1001):
s = 0
temp = num
digits = len(str(num))
while temp > 0:
s += (temp % 10) ** digits
temp //= 10
if s == num:
print(num)

✅ UNIT IV – Functions, Modules, Packages


(10 Programs)

31. Check prime using function.


def prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

n = int(input("Enter number: "))


print("Prime" if prime(n) else "Not prime"))

32. Square and cube of a number.


def calc(n):
return n*n, n*n*n

n = int(input("Enter number: "))


print("Square and Cube:", calc(n))

33. Function to return largest element in list.


def largest(lst):
m = lst[0]
for x in lst:
if x > m:
m = x
return m

print(largest([10, 20, 5, 8]))

34. Function with default argument.


def greet(name="Guest"):
print("Hello,", name)

greet()
greet("Alice")

35. Function for simple interest.


def si(p, r, t):
return (p * r * t) / 100

print("Simple Interest:", si(1000, 5, 2))

36. Function to count vowels.


def count_vowels(s):
c = 0
for ch in s:
if [Link]() in "aeiou":
c += 1
return c

s = input("Enter string: ")


print("Vowels:", count_vowels(s))

37. Create module [Link]

[Link]

def add(a, b): return a + b


def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b

[Link]

import mathops

print([Link](10, 5))
print([Link](10, 5))

38. Use math module (sin, cos, tan).


import math
x = float(input("Enter value: "))
print([Link](x))
print([Link](x))
print([Link](x))

39. Dice roll using random.


import random
print("Dice:", [Link](1, 6))

40. Generate random 6-digit password.


import random
pwd = ""

for i in range(6):
pwd += str([Link](0, 9))

print("Password:", pwd)

✅ UNIT V – File & Exception Handling (10


Programs)

41. Create file and write 5 lines.


f = open("[Link]", "w")
for i in range(5):
[Link]("This is line " + str(i+1) + "\n")
[Link]()

42. Read file line by line.


f = open("[Link]", "r")
for line in f:
print(line, end="")
[Link]()

43. Count uppercase and lowercase letters.


f = open("[Link]", "r")
data = [Link]()
u = l = 0

for ch in data:
if [Link]():
u += 1
elif [Link]():
l += 1

print("Uppercase:", u)
print("Lowercase:", l)

44. Read numbers from file and compute sum.


f = open("[Link]", "r")
total = 0

for line in f:
total += int(line)

print("Total:", total)
[Link]()

45. Copy one file to another.


s = open("[Link]", "r")
d = open("[Link]", "w")

for line in s:
[Link](line)

[Link]()
[Link]()

46. Append 3 lines to existing file.


f = open("[Link]", "a")
for i in range(3):
[Link]("New line " + str(i+1) + "\n")
[Link]()

47. Sort lines in a text file.


f = open("[Link]", "r")
lines = [Link]()
[Link]()

[Link]()

f = open("[Link]", "w")
[Link](lines)
[Link]()
48. Handle invalid integer input.
try:
n = int(input("Enter integer: "))
print(n)
except ValueError:
print("Invalid integer!")

49. Raise custom exception for age < 18.


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

if age < 18:


raise Exception("Not eligible!")
else:
print("Eligible")

50. Check file exists before opening.


import os

filename = "[Link]"

if [Link](filename):
f = open(filename, "r")
print([Link]())
[Link]()
else:
print("File not found!")

You might also like