0% found this document useful (0 votes)
22 views14 pages

Python Programming Basics and Examples

The document contains a series of Python programming exercises covering various topics such as data types, conditional statements, loops, functions, exception handling, file operations, and data manipulation using libraries like NumPy and Pandas. Each exercise includes code snippets demonstrating the implementation of specific concepts. The document serves as a comprehensive guide for learning Python programming through practical examples.

Uploaded by

vhgshreyas
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)
22 views14 pages

Python Programming Basics and Examples

The document contains a series of Python programming exercises covering various topics such as data types, conditional statements, loops, functions, exception handling, file operations, and data manipulation using libraries like NumPy and Pandas. Each exercise includes code snippets demonstrating the implementation of specific concepts. The document serves as a comprehensive guide for learning Python programming through practical examples.

Uploaded by

vhgshreyas
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

1. Write a Python program to demonstrate the different data types and conditional statements.

a = 10
b = 2.5
c = "Python"
d = True

if a > 5:
print("a is greater than 5")
else:
print("a is less than or equal to 5")

print(type(a), type(b), type(c), type(d))

Slide 1/30

Q2: Write a Python program to implement the different types of built-in methods of list, tuple and dictionary.

# list
lst = [3, 1, 4]
[Link](2)
[Link]()
print(lst)

# tuple
t = (1, 2, 2, 3)
print([Link](2), [Link](3))

# dict
d = {"a": 1, "b": 2}
print([Link](), [Link]())
[Link]({"c": 3})
print(d)

Slide 2/30
3. Write a Python program to implement mathematical functions using Math module.

import math

print([Link](16))
print([Link](5))
print([Link](2, 3))

Slide 3/30

4. Write a Python program to check if a Number is Positive, Negative, or Zero using if-elif-else.

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

if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")

Slide 4/30

5. Write a Python program to calculate the grade based on marks using if-else-if condition.
m = int(input("Enter marks: "))

if m >= 90:
print("Grade A")
elif m >= 75:
print("Grade B")
elif m >= 50:
print("Grade C")
else:
print("Fail")

Slide 5/30

6. Write a Python program to check for a leap year using if-else condition.

y = int(input("Enter year: "))

if y % 4 == 0 and y % 100 != 0 or y % 400 == 0:


print("Leap Year")
else:
print("Not a Leap Year")

Slide 6/30

7. Write a Python program to find the factorial of a number using for loop.

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


fact = 1

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


fact *= i
print("Factorial =", fact)

Slide 7/30

8. Write a Python program to find the sum of digits in a number using while loop.

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


s = 0

while n > 0:
s += n % 10
n //= 10

print("Sum =", s)

Slide 8/30

9. Write a Python program to find Largest of Three Numbers using conditional statement and logical operator.

a, b, c = 10, 20, 15

if a >= b and a >= c:


print(a)
elif b >= a and b >= c:
print(b)
else:
print(c)
Slide 9/30

10. Write a Python program to find Even Numbers in a List using looping statements.

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

for i in lst:
if i % 2 == 0:
print(i)

Slide 10/30

11. Write a Python program to check whether a given number is prime or not.

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


i = 2

while i <= n // 2:
if n % i == 0:
print("Not Prime")
break
i += 1
else:
print("Prime")
Slide 11/30

12. Write a Python program to define a function with argument and return the result for area of a rectangle.

def area(l, b):


return l * b

print(area(5, 4))

Slide 12/30

13. Write a Python program to use default keyword arguments in a function to add two numbers.

def add(a=10, b=5):


return a + b

print(add())

Slide 13/30
14. Write a Python Program to demonstrate the behaviour of local and global variable.

x = 10

def func():
x = 5
print("Local x:", x)

func()
print("Global x:", x)

Slide 14/30

15. Write a Python program to calculate factorial using recursion.

def fact(n):
if n == 1:
return 1
return n * fact(n - 1)

print(fact(5))

Slide 15/30
16. Write a Python Program to print a Fibonacci series using recursion.

def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)

for i in range(5):
print(fib(i), end=" ")

Slide 16/30

17. Write a Python program to handle exception while dividing two numbers using try-except.

try:
a = int(input())
b = int(input())
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")

Slide 17/30

18. Write a Python program to find the reciprocal of a number using try-else-except-finally.
try:
n = int(input())
r = 1 / n
except ZeroDivisionError:
print("Invalid number")
else:
print("Reciprocal:", r)
finally:
print("Done")

Slide 18/30

19. Write a Python program that throws an exception if a string does not contain vowels.

s = input("Enter string: ")

if not any(v in [Link]() for v in "aeiou"):


raise Exception("No vowels found")
else:
print("Valid string")

Slide 19/30

20. Write a Python program to read an existing file and write its contents to a new file.

with open("[Link]", "r") as f1:


with open("[Link]", "w") as f2:
[Link]([Link]())
Slide 20/30

21. Store student names and marks in a file and display them.

try:
with open("[Link]", "w") as f:
[Link]("Amit 85\nRiya 90\n")

with open("[Link]", "r") as f:


print([Link]())
except:
print("File error")

Slide 21/30

22. Merge two files into a new file with exception handling.

try:
with open("[Link]") as f1, open("[Link]") as f2:
with open("[Link]", "w") as f:
[Link]([Link]() + [Link]())
except:
print("File missing")
Slide 22/30

23. List all .py files using glob module.

import glob

files = [Link]("*.py")
print(files)
print("Total:", len(files))

Slide 23/30

24. Display current directory and list files > 1 KB using os module.

import os

print([Link]())

for f in [Link]():
if [Link](f) and [Link](f) > 1024:
print(f)
Slide 24/30

25. Write a Python program to implement file operations using switch case.

import os, shutil

ch = int(input("Enter choice: "))

match ch:
case 1:
open("[Link]", "w")
case 2:
print(open("[Link]").read())
case 3:
[Link]("[Link]")
case 4:
[Link]("[Link]", "[Link]")
case 5:
[Link]("[Link]", "[Link]")
case 6:
print([Link]())
case 7:
print([Link]())
case 8:
open("b txt" "a") write("Hello\n")
Slide 25/30

26. NumPy program to find average, highest and lowest temperature.

import numpy as np

t = [Link]([30, 32, 31, 29, 28, 33, 34])


print([Link](t), [Link](t), [Link](t))

Slide 26/30
27. NumPy slicing and square root using ufunc.

import numpy as np

m = [Link]([81, 64, 49, 36])


print(m[:3])
print([Link](m))

Slide 27/30

28. Pandas program to fill missing marks with mean.

import pandas as pd

df = [Link]({"Marks": [80, None, 90]})


df["Marks"].fillna(df["Marks"].mean(), inplace=True)
print(df)

Slide 28/30
29. Pandas program to fill missing data and add Total column.

import pandas as pd

df = [Link]({
"Item": ["Pen", None],
"Price": [10, None],
"Quantity": [2, None]
})

[Link]({"Item": "Pencil", "Price": 5, "Quantity": 1}, inplace=True)


df["Total"] = df["Price"] * df["Quantity"]
print(df)

Slide 29/30

30. Pandas program to display bar chart of students' marks.

import pandas as pd

df = [Link]({"Marks": [80, 90, 70]})


[Link](kind="bar")

Slide 30/30

You might also like