0% found this document useful (0 votes)
19 views28 pages

Python Programming Basics and Tasks

The document contains a series of Python programming tasks demonstrating various concepts such as data types, arithmetic operations, string manipulation, date formatting, list operations, tuple and dictionary handling, and more. Each task includes code snippets and expected outputs, covering topics like temperature conversion, finding prime numbers, and creating modules. The document serves as a comprehensive guide for learning Python programming through practical examples.

Uploaded by

Shruti Gupta
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)
19 views28 pages

Python Programming Basics and Tasks

The document contains a series of Python programming tasks demonstrating various concepts such as data types, arithmetic operations, string manipulation, date formatting, list operations, tuple and dictionary handling, and more. Each task includes code snippets and expected outputs, covering topics like temperature conversion, finding prime numbers, and creating modules. The document serves as a comprehensive guide for learning Python programming through practical examples.

Uploaded by

Shruti Gupta
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

PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL

BTCS 513-18 2224473


TASK 1: Write a program to demonstrate different datatypes in python.
# String
name = input("Enter your name: ")

print(f"Name (String): {name}, Type: {type(name)}")

# Integer
age = int(input("Enter your age: "))
print(f"Age (Integer): {age}, Type: {type(age)}")

# Float
height = float(input("Enter your height in meters: "))

print(f"Height (Float): {height}, Type: {type(height)}")

# Boolean
is_student_input = input("Are you a student? (yes/no): ").strip().lower()

is_student = True if is_student_input == "yes" else False


print(f"Is Student (Boolean): {is_student}, Type: {type(is_student)}")

# List
hobbies_input = input("Enter your hobbies (comma-separated): ")

hobbies = hobbies_input.split(",")

print(f"Hobbies (List): {hobbies}, Type: {type(hobbies)}")

# Tuple
fav_colors_input = input("Enter your favorite colors (comma-separated): ")
fav_colors = tuple(fav_colors_input.split(","))

print(f"Favorite Colors (Tuple): {fav_colors}, Type: {type(fav_colors)}")

# Set
unique_numbers_input = input("Enter some numbers (comma-separated): ")

unique_numbers = set(unique_numbers_input.split(","))

print(f"Unique Numbers (Set): {unique_numbers}, Type: {type(unique_numbers)}")

1
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
# Dictionary
print("Enter your details for a dictionary:")

key1 = input("Enter key 1: ")

value1 = input("Enter value for key 1: ")


key2 = input("Enter key 2: ")

value2 = input("Enter value for key 2: ")

user_dict = {key1: value1, key2: value2}

print(f"Dictionary:{user_dict},Type:{type(user_dict)}")

OUTPUT:

2
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 2: Write a program to perform different arithmetic operation.
# Taking two numbers as input from the user
num1 = float(input("Enter first number: "))

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

# Performing arithmetic operations


addition = num1 + num2
subtraction = num1 - num2

multiplication = num1 * num2

division = num1 / num2 if num2 != 0 else "Undefined (division by zero)"

floor_division = num1 // num2 if num2 != 0 else "Undefined (division by zero)"

modulus = num1 % num2 if num2 != 0 else "Undefined (modulus by zero)"

exponent = num1 ** num2

# Displaying results
print(f"Addition: {addition}")

print(f"Subtraction: {subtraction}")

print(f"Multiplication: {multiplication}")

print(f"Division: {division}")

print(f"Floor Division: {floor_division}")


print(f"Modulus: {modulus}")

print(f"Exponent: {exponent}")

OUTPUT:

3
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 3:Write a program to create, concatenate and print a string and
accessing substring from given string.
#create a string
str1="Hello"

#Concatenate string
str2=str1+"World"

#print the concatenated string


print("Contatenatind String:",str2)

#access substring
substring=str2[4:11]

#print the substring


print("Substring:",substring)

OUTPUT:

4
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 4: Write a python script to print the current date in the following format
“Sun May 29 02:26:23 IST 2017”.
from datetime import datetime

import time

now = [Link]()

formatted_time = [Link]("%a %b %d %H:%M:%S %Z %Y")

if not [Link]("%Z"):

formatted_time = [Link]("%a %b %d %H:%M:%S") + f" {[Link][0]} " +


[Link]("%Y")
print(formatted_time)

OUTPUT:

5
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 5: Write a program to create, append, and remove lists in python.
# Create a list
my_list = [10, 20, 30, 40]

print("Initial List:", my_list)

# Append elements to the list


my_list.append(50)
my_list.append(60)

print("After Appending:", my_list)

# Remove elements from the list


my_list.remove(30) # removes the first occurrence of 30

print("After Removing 30:", my_list)

# Remove element by index using pop()


removed_item = my_list.pop(2) # removes element at index 2
print(f"After Popping index 2 ({removed_item} removed):", my_list)

# Clear the list completely


my_list.clear()

print("After Clearing:", my_list)

OUTPUT:

6
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 6: Write a program to demonstrate working with tuples in python.
# Creating tuples
empty_tuple = ()

single_tuple = (10,)

numbers = (10, 20, 30, 40, 50)

mixed = (1, "hello", 3.14, True)


print("Empty Tuple:", empty_tuple)

print("Single Element Tuple:", single_tuple)

print("Numbers Tuple:", numbers)

print("Mixed Tuple:", mixed)

# Accessing elements
print("\nFirst element of numbers:", numbers[0])

print("Last element of numbers:", numbers[-1])

# Slicing
print("Slice from index 1 to 3:", numbers[1:4])

# Iterating over a tuple


print("\nIterating over numbers tuple:")

for num in numbers:


print(num, end=" ")

# Tuple unpacking
a, b, c, d, e = numbers

print("\n\nTuple Unpacking -> a:", a, "b:", b, "c:", c, "d:", d, "e:", e)

# Nesting tuples
nested = (numbers, mixed)

print("Nested Tuple:", nested)

7
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
# Using tuple methods
print("\nCount of 20 in numbers:", [Link](20))

print("Index of 40 in numbers:", [Link](40))

# Concatenation and repetition


new_tuple = numbers + (60, 70)

print("After Concatenation:", new_tuple)

print("Repetition (numbers * 2):", numbers * 2)

OUTPUT:

8
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 7: Write a program to demonstrate working with dictionaries in python.
# Creating dictionaries
empty_dict = {}

student = {

"name": "Rahul",

"age": 21,
"course": "Computer Science",

"marks": [85, 90, 78]

print("Empty Dictionary:", empty_dict)

print("Student Dictionary:", student)

# Accessing values
print("\nName:", student["name"])
print("Age:", [Link]("age")) # safer than student["age"]

#Adding new key-value pairs


student["email"] = "rahul@[Link]"

print("\nAfter Adding Email:", student)

# Updating values
student["age"] = 22

print("After Updating Age:", student)

# Removing elements
removed_value = [Link]("course") # remove by key

print("\nAfter Removing 'course':", student)

print("Removed Value:", removed_value)

9
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
# Iterating over dictionary
print("\nIterating through keys:")

for key in student:

print(key, "->", student[key])


print("\nIterating through items (key-value pairs):")

for key, value in [Link]():

print(f"{key}: {value}")

# Dictionary methods
print("\nKeys:", [Link]())

print("Values:", [Link]())

print("Items:", [Link]())

# Nesting dictionaries
students = {

"s1": {"name": "Rahul", "age": 22},

"s2": {"name": "Priya", "age": 20}

print("\nNested Dictionary:", students)

# Clearing a dictionary
[Link]()

print("\nAfter Clearing:", student)

10
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
OUTPUT:

11
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 8: Write a python program to find largest of three numbers.
# Taking three numbers as input
a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

c = int(input("Enter third number: "))

# Method 1: Using if-else


if (a >= b) and (a >= c):

largest = a

elif (b >= a) and (b >= c):

largest = b

else:

largest = c

print("The largest number is:", largest)

# Method 2: Using built-in function


print("Largest using max():", max(a, b, c))

OUTPUT:

12
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 9: Write a Python program to convert temperatures to and from Celsius,
Fahrenheit. [ Formula: c/5 = f-32/9].

# Formula: (c/5) = (f - 32) / 9


def celsius_to_fahrenheit(c):

return (c * 9/5) + 32

def fahrenheit_to_celsius(f):

return (f - 32) * 5/9

# Menu for user


print("Temperature Conversion Program")

print("1. Celsius to Fahrenheit")

print("2. Fahrenheit to Celsius")

choice = int(input("Enter choice (1 or 2): "))

if choice == 1:

c = float(input("Enter temperature in Celsius: "))

print(f"{c}°C = {celsius_to_fahrenheit(c):.2f}°F")
elif choice == 2:

f = float(input("Enter temperature in Fahrenheit: "))

print(f"{f}°F = {fahrenheit_to_celsius(f):.2f}°C")

else:

print("Invalid choice! Please enter 1 or 2.")

13
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
OUTPUT:

14
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 10: Write a python program to construct the following pattern, using a
nested for loop *
**
***
****

for i in range(1,5):
for j in range(i):

print("*",end="")

print()

for i in range(3,0-1):

for j in range(i):

print("*",end="")
print()

OUTPUT:

15
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 11: Print prime numbers less than 20.
for num in range(2, 20):

is_prime = True

for i in range(2, int(num ** 0.5) + 1):

if num % i == 0:

is_prime = False
break

if is_prime:

print(num)

OUTPUT:

16
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 12: Find factorial of a number using recursion.

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)
# Example: Find factorial of 5

num = 5

print("Factorial of", num, "is:", factorial(num))

OUTPUT:

17
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 13: Check if a triangle is a right triangle.

# Input the three sides of the triangle

a = float(input("Enter first side: "))

b = float(input("Enter second side: "))

c = float(input("Enter third side: "))

# Sort sides so the largest side is last (potential hypotenuse)

sides = sorted([a, b, c])

# Apply Pythagoras theorem: a² + b² = c²

if abs(sides[0]**2 + sides[1]**2 - sides[2]**2) < 1e-9:

print("✅ The triangle is a right-angled triangle.")

else:

print("❌ The triangle is NOT a right-angled triangle.")

OUTPUT:

18
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 14: Write a python program to define a module to find Fibonacci
Numbers and import the module to another program.
# fibonacci_module.py

def fibonacci(n):

"""Return a list containing the Fibonacci sequence up to n terms."""

sequence = []

a, b = 0, 1
for _ in range(n):

[Link](a)

a, b = b, a + b

return sequence

# main_program.py

import fibonacci_module # Import the custom module


n = int(input("Enter the number of terms: "))

fib_sequence = fibonacci_module.fibonacci(n)

print(f"Fibonacci sequence up to {n} terms:")

print(fib_sequence)

OUTPUT:

19
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 15: Write a python program to define a module and import a specific
function in that module to another program.
# math_module.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

def multiply(a, b):

return a * b

def divide(a, b):


if b != 0:

return a / b

else:

return "Division by zero not allowed!"

# main_program.py

from math_module import multiply # Import only the 'multiply' function


x = int(input("Enter first number: "))

y = int(input("Enter second number: "))

result = multiply(x, y)

print(f"The product of {x} and {y} is: {result}")

OUTPUT:

20
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 16: Write a script named [Link]. This script should prompt the user
for the names of two text files. The contents of the first file should be input and
written to the second file.
# [Link]

# Prompt the user for source and destination file names

source_file = input("Enter the name of the source file: ")


destination_file = input("Enter the name of the destination file: ")

try:

# Open the source file in read mode


with open(source_file, 'r') as src:

content = [Link]() # Read the entire content of the source file

# Open the destination file in write mode and copy the content

with open(destination_file, 'w') as dest:


[Link](content)

print(f"✅ Contents of '{source_file}' have been successfully copied to '{destination_file}'.")

except FileNotFoundError:

print(f"❌ Error: The file '{source_file}' was not found.")

except Exception as e:

print(f"⚠️ An error occurred: {e}")

OUTPUT:

21
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 17: Write a program that inputs a text file. The program should print all
of the unique words in the file in alphabetical order.
# unique_words.py

# Prompt the user for the file name

file_name = input("Enter the name of the text file: ")

try:

# Open the file in read mode

with open(file_name, 'r') as file:

text = [Link]() # Read all content

# Convert text to lowercase and split into words


words = [Link]().split()

# Remove punctuation from words

clean_words = []

for word in words:

word = ''.join(ch for ch in word if [Link]()) # Keep only letters and numbers

if word: # Avoid empty strings

clean_words.append(word)
# Create a set to store unique words

unique_words = sorted(set(clean_words))

# Print the unique words in alphabetical order

print("\nUnique words in alphabetical order:")

for word in unique_words:

print(word)

except FileNotFoundError:

print(f"❌ Error: The file '{file_name}' was not found.")

except Exception as e:

print(f"⚠️ An error occurred: {e}")

22
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
OUTPUT:

23
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 18: Write a Python class to convert an integer to a roman numeral.
# integer_to_roman.py

class IntegerToRoman:

def __init__(self):

# Mapping of integers to Roman numerals

[Link] = [
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),

(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),

(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")

def convert(self, num):

"""Convert an integer to a Roman numeral."""

roman = ""
for value, symbol in [Link]:

while num >= value:

roman += symbol

num -= value

return roman
# --- Main Program ---

if __name__ == "__main__":
number = int(input("Enter an integer (1-3999): "))

if 1 <= number <= 3999:

converter = IntegerToRoman()

print(f"Roman numeral: {[Link](number)}")

else:

print("❌ Please enter a number between 1 and 3999.")

24
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
OUTPUT:

25
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 19: Write a Python class to implement pow(x, n).
# power_function.py

class Power:

def pow(self, x, n):

"""Compute x raised to the power n (x^n) without using built-in pow()."""

# Handle negative exponents


if n < 0:

x=1/x

n = -n

result = 1

# Exponentiation by squaring (efficient method)

while n > 0:

if n % 2 == 1: # If n is odd
result *= x

x *= x

n //= 2

return result

# --- Main Program ---


if __name__ == "__main__":

base = float(input("Enter the base (x): "))


exponent = int(input("Enter the exponent (n): "))

power_obj = Power()

print(f"{base} raised to the power {exponent} is: {power_obj.pow(base, exponent)}")

26
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
OUTPUT:

27
PROGRAMMING IN PYTHON [ELECTIVE-I] PRANAV AGGARWAL
BTCS 513-18 2224473
TASK 20: Write a Python class to reverse a string word by word.
# reverse_words.py

class StringReverser:

def __init__(self, text):

[Link] = text

def reverse_words(self):
"""Reverse the string word by word."""

words = [Link]()

reversed_words = words[::-1]

return ' '.join(reversed_words)

# --- Main Program ---

if __name__ == "__main__":

input_text = input("Enter a string: ")


reverser = StringReverser(input_text)

print("Reversed string word by word:")

print(reverser.reverse_words())

OUTPUT:

28

You might also like