0% found this document useful (0 votes)
25 views34 pages

Python Programming Basics and Examples

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)
25 views34 pages

Python Programming Basics and Examples

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.

PASCAL TRIANGLE

def print_pascal(n):

row = [1]

for i in range(n):

print(' ' * (n - i), end='')

print(' '.join(str(j) for j in row))

row = [sum(pair) for pair in zip([0]+row, row+[0])]


print_pascal(5)
OUTPUT
2. PATTERN USING NESTED LOOP

n=5

for i in range(n):

print((' '.join('*' * (i+1))).center(n*14))


for i in range(n-1, 0, -1):
print((' '.join('*' * i)).center(n*14))
OUTPUT
[Link] TO CONVERT THE GIVEN TEMPERATURE FROM
FAHRENHEIT TO CELSIUS AND VICE VERSA DEPENDING UPON
USER’S CHOICE

def convert_temp():
while True:
choice = input("Enter 'F' for F to C, 'C' for C to F, or 'Q' to quit: ").upper()
if choice == 'Q':
print("Goodbye!"); break
temp = float(input("Enter temperature: "))
if choice == 'F':
print(f"{temp}°F = {(temp - 32) * 5/9:.2f}°C\n")
elif choice == 'C':
print(f"{temp}°C = {temp * 9/5 + 32:.2f}°F\n")
else:
print("Invalid choice.\n")
convert_temp()
OUTPUT
[Link] NUMBERS LESS THAN 20

def print_primes(n):

for num in range(2, n):

if all(num % i != 0 for i in range(2, num)):


print(num)
print_primes(20)
OUTPUT
[Link]’S GRADE

subjects = ['TAMIL', 'ENGLISH', 'FOC', 'STATISTICS', 'COMPUTER SCIENCE']


marks = []

for subject in subjects:


[Link](int(input(f"Enter marks for {subject}: ")))

total_marks = sum(marks)
percentage = (total_marks / (5*100)) * 100

print(f"Total Marks: {total_marks}")


print(f"Percentage: {percentage}%")

if percentage >= 80:


grade = 'A'
elif percentage >= 70:
grade = 'B'
elif percentage >= 60:
grade = 'C'
elif percentage >= 40:
grade = 'D'
else:
grade = 'E'
print(f"Grade: {grade}")
OUTPUT
6. PROGRAM, TO FIND THE AREA OF RECTANGLE, SQUARE,
CIRCLE AND TRIANGLE BY ACCEPTING SUITABLE INPUT
PARAMETERS FROM USER.

import math

l = float(input("Enter rectangle length: "))

w = float(input("Enter rectangle width: "))

print("Area of Rectangle:", l * w)

r = float(input("Enter circle radius: "))

print("Area of Circle:", [Link] * r ** 2)

s = float(input("Enter square side: "))

print("Area of Square:", s * s)

b = float(input("Enter triangle base: "))

h = float(input("Enter triangle height: "))

print("Area of Triangle:", 0.5 * b * h)


OUTPUT
[Link] TO FIND FACTORIAL OF THE GIVEN NUMBER USING
RECURSIVE FUNCTION

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number to find its factorial: "))

if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print("Factorial of", num, "is", factorial(num))
OUTPUT
8. PYTHON PROGRAMTO PRINT REVERSE OF THE STRING
MALAYALAM

def reverse_string(word):

reverse_word = word[::-1]

return reverse_word

word = "MALAYALAM"

reversed_word = reverse_string(word)

print("The original word is:", word)

print("The reversed word is:", reversed_word)


OUTPUT
[Link] OF THREE NUMBERS

def find_largest(num1, num2, num3):

return max(num1, num2, num3)

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

num3 = float(input("Enter third number: "))

largest = find_largest(num1, num2, num3)

print("The largest number is", largest)


OUTPUT
10. PROGRAM TO PERFORM READ AND COPY
OPERATIONS ON A FILE

with open('[Link]', 'r') as source_file:

content = source_file.read()

print("Content of source file:\n", content)

with open('[Link]', 'w') as destination_file:

destination_file.write(content)

with open('[Link]', 'r') as destination_file:

print("Content of destination file:\n", destination_file.read())


OUTPUT
[Link] PROGRAM FOR ARITHMETIC OPERATORS

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
if num2 != 0:
print("Quotient:", num1 / num2)
else:
print("Cannot divide by zero")
OUTPUT
[Link] SERIES PROGRAM

def fibonacci(n):

a, b = 0, 1

for i in range(n):

print(a)

a, b = b, a + b

fibonacci(10)
OUTPUT
[Link] OF HANOI

def hanoi(n, source, auxiliary, target):

if n == 1:

print(f"Move disk 1 from {source} to {target}")

else:

hanoi(n - 1, source, target, auxiliary)

print(f"Move disk {n} from {source} to {target}")

hanoi(n - 1, auxiliary, source, target)

num_disks = 3

hanoi(num_disks, 'A', 'B', 'C')


OUTPUT
[Link] THE ODD AND EVEN NUMBERS IN THE LIST

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

count_odd = 0

count_even = 0
for x in numbers:
if x % 2 == 0:

count_even+=1
else:
count_odd+=1

print("Number of even numbers :",count_even)


print("Number of odd numbers :",count_odd)
OUTPUT
[Link] A TURTLE GRAPHICS WINDOW WITH SPECIFIC SIZE

import turtle

# Create a screen object


screen = [Link]()

# Set the window size (width x height)


[Link](width=600, height=400)

# Set window title


[Link]("Turtle Graphics Window")

# Keep the window open until clicked


[Link]()
OUTPUT
[Link] A PROGRAM TO FIND SUM OF ALL ITEMS IN A DICTIONARY

# Sample dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30}

# Calculate sum of all values


total = sum(my_dict.values( ))

# Display the result


print("Sum of all items in the dictionary:", total)
OUTPUT
17. WRITE A PYTHON PROGRAM USING A TUPLE

# Creating a tuple

fruits = ("apple", "banana", "cherry", "mango")

# Accessing elements

print("First fruit:", fruits[0])

print("Last fruit:", fruits[-1])

# Iterating through the tuple

print("All fruits:")

for fruit in fruits:

print(fruit)

# Checking if an item exists

if "banana" in fruits:

print("Yes, banana is in the tuple")


OUTPUT

You might also like