0% found this document useful (0 votes)
6 views26 pages

Untitled Document Removed

The document contains multiple Python programming tasks including printing student details, using if-else statements, checking for prime and Armstrong numbers, and performing various list operations. It also covers loops, functions, and data structures like tuples, demonstrating their syntax and usage through examples. Each task is accompanied by code snippets and expected output.

Uploaded by

arunhargun77
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)
6 views26 pages

Untitled Document Removed

The document contains multiple Python programming tasks including printing student details, using if-else statements, checking for prime and Armstrong numbers, and performing various list operations. It also covers loops, functions, and data structures like tuples, demonstrating their syntax and usage through examples. Each task is accompanied by code snippets and expected output.

Uploaded by

arunhargun77
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

[Link] a program print class,name ,roll no, section .

# Program to print student details

# Assigning values to variables


name = "Manpreet Kaur"
student_class = "BCA"
roll_no = 7703
section = "A"

# Printing the details


print("Student Details")
print("----------------")
print("Name :", name)
print("Class :", student_class)
print("Roll No. :", roll_no)
print("Section :", section)

Output

Student Details
----------------
Name : Manpreet Kaur
Class : BCA
Roll No. : 7703
Section : A
2. Write a program to if - else loops syntax examples.

if condition:
# code to execute if the condition is True
num = 10

if num > 0:
print("The number is positive.")

Output

The number is positive.

if condition:
# code to execute if the condition is True
else:
# code to execute if the condition is False
num = 7

if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd 7.")

Output
The number is odd 7.
[Link] a program to primary number.

# Program to check if a number is prime

num = int(input("Enter a number: "))

if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(num, "is not a Prime Number")
break
else:
print(num, "is a Prime Number")
else:
print(num, "is not a Prime Number")

Output

Enter a number: 7
7 is a Prime Number.
4. Write a program to Armstrong Number.

# Program to check Armstrong number

num = int(input("Enter a number: "))

# Store the original number


original_num = num

# Count the number of digits


num_digits = len(str(num))

# Initialize sum
sum_of_powers = 0

# Calculate the sum of digits raised to the power of num_digits


while num > 0:
digit = num % 10
sum_of_powers += digit ** num_digits
num //= 10

# Check if it is an Armstrong number


if original_num == sum_of_powers:
print(original_num, "is an Armstrong Number")
else:
print(original_num, "is not an Armstrong Number")

Output

Enter a number: 153


153 is an Armstrong Number
[Link] a program to find greater number, find prime has from 1-50, print all vowels and
constant, convert given # is palindrome , convert temperature from celsius to fahrenheit.

# Combined Python Program for Multiple Tasks

# 1. Find the Greater Number


print("----- Find the Greater Number -----")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

if num1 > num2:


print(f"{num1} is greater than {num2}")
elif num2 > num1:
print(f"{num2} is greater than {num1}")
else:
print("Both numbers are equal")

# 2. Print Prime Numbers from 1 to 50


print("\n----- Prime Numbers from 1 to 50 -----")
for num in range(2, 51):
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, end=" ")
print()

# 3. Print All Vowels and Consonants from a String


print("\n----- Vowels and Consonants -----")
text = input("Enter a string: ")

vowels = "aeiouAEIOU"
vowel_list = []
consonant_list = []

for char in text:


if [Link](): # Consider only alphabetic characters
if char in vowels:
vowel_list.append(char)
else:
consonant_list.append(char)
print("Vowels:", ", ".join(vowel_list))
print("Consonants:", ", ".join(consonant_list))

# 4. Check Whether a Number is a Palindrome


print("\n----- Palindrome Number Check -----")
number = input("Enter a number: ")

if number == number[::-1]:
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")

# 5. Convert Celsius to Fahrenheit


print("\n----- Celsius to Fahrenheit Conversion -----")
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit:.2f}°F")

Output

----- Find the Greater Number -----


Enter the first number: 10
Enter the second number: 20
20 is greater than 10

----- Prime Numbers from 1 to 50 -----


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

----- Vowels and Consonants -----


Enter a string: Hello World
Vowels: e, o, o
Consonants: H, l, l, W, r, l, d

----- Palindrome Number Check -----


Enter a number: 121
121 is a palindrome.

----- Celsius to Fahrenheit Conversion -----


Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.00°F
6. Write a program to print Days of week ( continue series).

# Program to print days of the week using continue

days = ["Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday", "Sunday"]

for day in days:


if day == "Sunday":
continue # Skip Sunday
print(day)

Output

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
7. Write a program to break and continue statement.

# Program demonstrating break and continue with a while loop

i=0
while i < 10:
i += 1
if i == 4:
continue # Skip 4
if i == 9:
break # Stop the loop at 9
print(i)

Output

1
2
3
5
6
7
8
8. Write a program of for loop , while loop ( syntax examples).

# For loop example


print("For Loop Example:")
for i in range(1, 4):
print(i)

# While loop example


print("\nWhile Loop Example:")
j=1
while j <= 3:
print(j)
j += 1

Output

For Loop Example:


1
2
3

While Loop Example:


1
2
3
9. Write a program to Fruits prints.

# Taking fruit names from the user and printing them


fruits = []

n = int(input("How many fruits do you want to enter? "))

for i in range(n):
fruit = input(f"Enter fruit {i + 1}: ")
[Link](fruit)

print("\nList of Fruits:")
for fruit in fruits:
print(fruit)

Output

Enter fruit 1: Apple


Enter fruit 2: Mango
Enter fruit 3: Banana

List of Fruits:
Apple
Mango
Banana
10. Write a program to odd , even number print.

# Program to print odd and even numbers from 1 to 20

print("Even numbers from 1 to 20:")


for i in range(1, 21):
if i % 2 == 0:
print(i, end=" ")

print("\nOdd numbers from 1 to 20:")


for i in range(1, 21):
if i % 2 != 0:
print(i, end=" ")

Output

Even numbers from 1 to 20:


2 4 6 8 10 12 14 16 18 20
Odd numbers from 1 to 20:
1 3 5 7 9 11 13 15 17 19
11. Write a program to Range function ( syntax, color,pass stmt,
function,limitation,definition,parameters, value return.

# 1. Range Function Syntax


print("1. Range Function Examples:")

# range(stop)
print("range(stop):")
for i in range(5):
print(i, end=" ")
print("\n")

# range(start, stop)
print("range(start, stop):")
for i in range(2, 7):
print(i, end=" ")
print("\n")

# range(start, stop, step)


print("range(start, stop, step):")
for i in range(1, 10, 2):
print(i, end=" ")
print("\n")

# 2. Color Printing

print("2. Color Printing Examples:")

# Using ANSI escape codes for colored text


print("\033[91mThis is Red Text\033[0m")
print("\033[92mThis is Green Text\033[0m")
print("\033[94mThis is Blue Text\033[0m")
print("\033[93mThis is Yellow Text\033[0m]

# 3. Pass Statement

print("\n3. Pass Statement Example:")

for i in range(3):
if i == 1:
pass # Placeholder for future code
print("Value:", i)
# 4. Function Definition, Parameters, and Return Value
print("\n4. Function Definition and Return Value:")

# Function definition with parameters


def add_numbers(a, b):
"""This function returns the sum of two numbers."""
result = a + b
return result # Returning a value

# Calling the function


sum_result = add_numbers(5, 7)
print("Sum of 5 and 7 is:", sum_result

# 5. Function with Default Parameters


# -----------------------------------------
print("\n5. Function with Default Parameter:")

def greet(name="Guest"):
return f"Hello, {name}!"

print(greet()) # Uses default value


print(greet("Manpreet")) # Uses provided value

# -----------------------------------------
# 6. Function Limitation Example
# -----------------------------------------
print("\n6. Function Limitation Example:")

def multiply_numbers(a, b):


result = a * b
# No return statement here

output = multiply_numbers(3, 4)
print("Output of multiply_numbers:", output) # Will print None

Output

1. Range Function Examples:


01234
23456
13579

2. Color Printing Examples:


This is Red Text
This is Green Text
This is Blue Text
This is Yellow Text

3. Pass Statement Example:


Value: 0
Value: 1
Value: 2

4. Function Definition and Return Value:


Sum of 5 and 7 is: 12

5. Function with Default Parameter:


Hello, Guest!
Hello, Manpreet!

6. Function Limitation Example:


Output of multiply_numbers: None
12. Write a program to for loop in print name,(fruits,color name,syntax,value, range)

# 1. Print Name
print("----- Student Details -----")
name = "Manpreet Kaur"
print("Name:", name )

# 2. Print Fruits

print("\n----- List of Fruits -----")


fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"]
for fruit in fruits:
print(fruit)

# 3. Print Color Names


print("\n----- List of Colors -----")
colors = ["Red", "Green", "Blue", "Yellow", "Purple"]
for color in colors:
print(color)

# 4. Demonstrate range() Function Syntax and Values


print("\n----- range() Function Examples -----")

# Syntax 1: range(stop)
print("\nSyntax: range(stop)")
print("Values:", end=" ")
for i in range(5):
print(i, end=" ")

# Syntax 2: range(start, stop)


print("\n\nSyntax: range(start, stop)")
print("Values:", end=" ")
for i in range(2, 7):
print(i, end=" ")

# Syntax 3: range(start, stop, step)


print("\n\nSyntax: range(start, stop, step)")
print("Values:", end=" ")
for i in range(1, 10, 2):
print(i, end=" ")

print("\n")
# 5. Using range() to Print Items with Index

print("----- Fruits with Index Using range() -----")


for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")

Output

----- Student Details -----


Name: Manpreet Kaur

----- List of Fruits -----


Apple
Banana
Mango
Orange
Grapes

----- List of Colors -----


Red
Green
Blue
Yellow
Purple

----- range() Function Examples -----

Syntax: range(stop)
Values: 0 1 2 3 4

Syntax: range(start, stop)


Values: 2 3 4 5 6

Syntax: range(start, stop, step)


Values: 1 3 5 7 9

----- Fruits with Index Using range() -----


Index 0: Apple
Index 1: Banana
Index 2: Mango
Index 3: Orange
Index 4: Grapes
13. Write a program to list programs in syntax ,examples , print colors, print A,B,C,D,E,F,
append function,insert extend list clear, list sort functions ,list sort reverse , [Link].

# 1. List Creation (Syntax)


print("----- List Creation Syntax -----")
colors = ["Red", "Green", "Blue"]
print("Initial List:", colors)

# 2. Printing Colors
print("\n----- Printing Colors -----")
for color in colors:
print(color)

# 3. Printing Letters A, B, C, D, E, F

print("\n----- Printing Letters A to F -----")


letters = ['A', 'B', 'C', 'D', 'E', 'F']
for letter in letters:
print(letter, end=" ")
print()

# 4. append() Function

print("\n----- append() Function -----")


[Link]("Yellow")
print("After append:", colors)

# 5. insert() Function

print("\n----- insert() Function -----")


[Link](1, "Purple") # Insert at index 1
print("After insert:", colors)

# 6. extend() Function

print("\n----- extend() Function -----")


more_colors = ["Orange", "Pink"]
[Link](more_colors)
print("After extend:", colors)
# 7. sort() Function

print("\n----- sort() Function -----")


[Link]() # Sorts the list in ascending (alphabetical) order
print("After sort:", colors)

# 8. reverse() Function
print("\n----- reverse() Function -----")
[Link]()
print("After reverse:", colors)

# 9. copy() Function

print("\n----- copy() Function -----")


colors_copy = [Link]()
print("Copied List:", colors_copy)

# 10. clear() Function

print("\n----- clear() Function -----")


[Link]()
print("After clear:", colors)

Output

----- List Creation Syntax -----


Initial List: ['Red', 'Green', 'Blue']

----- Printing Colors -----


Red
Green
Blue

----- Printing Letters A to F -----


ABCDEF

----- append() Function -----


After append: ['Red', 'Green', 'Blue', 'Yellow']

----- insert() Function -----


After insert: ['Red', 'Purple', 'Green', 'Blue', 'Yellow']
----- extend() Function -----
After extend: ['Red', 'Purple', 'Green', 'Blue', 'Yellow', 'Orange', 'Pink']

----- sort() Function -----


After sort: ['Blue', 'Green', 'Orange', 'Pink', 'Purple', 'Red', 'Yellow']

----- reverse() Function -----


After reverse: ['Yellow', 'Red', 'Purple', 'Pink', 'Orange', 'Green', 'Blue']

----- copy() Function -----


Copied List: ['Yellow', 'Red', 'Purple', 'Pink', 'Orange', 'Green', 'Blue']

----- clear() Function -----


After clear: []
14. Write a program to tuple program syntax function ( type () ) union statement print ( class,
tuple) print ( class,name ) parse tree print ( “ dod” .c ) long() deletion tuple constructor Range in
function update ( modify) for loop multiple values remove.

# 1. Tuple Syntax and Constructor


t1 = (10, 20, 30, 40)
t2 = tuple(["apple", "banana", "cherry"]) # Tuple constructor

print("Tuple t1:", t1)


print("Tuple t2:", t2)

# 2. type() Function
print("Type of t1:", type(t1))

# 3. Printing Class and Tuple


class Student:
def __init__(self, name, course):
[Link] = name
[Link] = course

s1 = Student("Manpreet Kaur", "BCA")


print("Class object:", s1)
print("Class Name:", s1.__class__.__name__)
print("Student Name:", [Link])

# 4. Printing Multiple Values (class, name)


print("Class and Name:", s1.__class__.__name__, [Link])

# 5. Union of Tuples (using + operator)


t3 = (50, 60)
union_tuple = t1 + t3
print("Union of tuples:", union_tuple)

# 6. Parsing a String into a Tuple


parsed_tuple = tuple("dog")
print("Parsed tuple from string:", parsed_tuple)

# 7. Accessing a Character (similar to 'parse tree print("dod".c)')


# Python does not use '.c'; instead, we use indexing
print("First character of 'dog':", "dog"[0])

# 8. Length of Tuple using len()


print("Length of t1:", len(t1))
# 9. Range Function with Tuple
range_tuple = tuple(range(1, 6))
print("Tuple created using range():", range_tuple)

# 10. Updating/Modifying a Tuple


# Tuples are immutable, so convert to list, modify, then convert back
temp_list = list(t1)
temp_list[1] = 200 # Modify value
updated_tuple = tuple(temp_list)
print("Updated tuple:", updated_tuple)

# 11. Adding Multiple Values to a Tuple


extended_tuple = t1 + (70, 80, 90)
print("Tuple after adding multiple values:", extended_tuple)

# 12. Removing an Element from a Tuple


# Convert to list, remove the element, then convert back
temp_list = list(t1)
temp_list.remove(30)
removed_tuple = tuple(temp_list)
print("Tuple after removing 30:", removed_tuple)

# 13. Deleting a Tuple


t_delete = (1, 2, 3)
print("Tuple before deletion:", t_delete)
del t_delete
# print(t_delete) # This would raise a NameError if uncommented

# 14. For Loop to Iterate Through a Tuple


print("Iterating through tuple t1:")
for value in t1:
print(value)

# 15. Function Returning a Tuple (Multiple Values)


def student_details():
return ("Manpreet Kaur", "BCA", 7703)

name, course, roll_no = student_details()


print("Returned values from function:")
print("Name:", name)
print("Course:", course)
print("Roll No:", roll_no)

Output
Tuple t1: (10, 20, 30, 40)
Tuple t2: ('apple', 'banana', 'cherry')
Type of t1: <class 'tuple'>
Class and Name: Student Manpreet Kaur
Union of tuples: (10, 20, 30, 40, 50, 60)
Parsed tuple from string: ('d', 'o', 'g')
Length of t1: 4
Tuple created using range(): (1, 2, 3, 4, 5)
Updated tuple: (10, 200, 30, 40)
Tuple after removing 30: (10, 20, 40)
15. Write a program to set function in syntax len () type () type ( class, type) Access items ( for
loop) colors print member function Boolean expression Add function color add set combine
update remove function Pop function clear function deletion function.

# 1. Set Syntax
colors = {"red", "green", "blue", "yellow"}
print("Original Set:", colors)

# 2. len() Function
print("Number of elements in the set:", len(colors))

# 3. type() Function
print("Type of colors:", type(colors))

# 4. Using type() with a Class


class Student:
def __init__(self, name):
[Link] = name

student1 = Student("Manpreet Kaur")


print("Class of student1:", type(student1))
print("Class Name:", student1.__class__.__name__)
print("Student Name:", [Link])

# 5. Accessing Set Items Using a For Loop


print("\nAccessing items in the set:")
for color in colors:
print(color)

# 6. Membership Function with Boolean Expression


print("\nMembership Test:")
print("Is 'red' in colors?", "red" in colors) # Returns True or False
print("Is 'black' in colors?", "black" in colors) # Returns True or False

# 7. Add Function - Adding a Single Element


[Link]("black")
print("\nAfter adding 'black':", colors)

# 8. Adding Multiple Elements (update function)


[Link](["white", "pink"])
print("After updating with multiple colors:", colors)

# 9. Combining Sets (Union)


more_colors = {"orange", "purple"}
combined_set = [Link](more_colors)
print("\nCombined Set using union():", combined_set)

# Another way to combine using update()


[Link](more_colors)
print("After combining using update():", colors)

# 10. Remove Function


[Link]("green") # Raises an error if the element is not present
print("\nAfter removing 'green':", colors)

# 11. Discard Function (Safe Removal)


[Link]("silver") # No error if the element is not present
print("After discarding 'silver':", colors)

# 12. Pop Function - Removes a Random Element


removed_item = [Link]()
print("\nItem removed using pop():", removed_item)
print("Set after pop():", colors)

# 13. Clear Function - Removes All Elements


temp_set = {"a", "b", "c"}
print("\nTemporary set before clear():", temp_set)
temp_set.clear()
print("Temporary set after clear():", temp_set)

# 14. Deletion Function - Deleting the Entire Set


delete_set = {"x", "y", "z"}
print("\nSet before deletion:", delete_set)
del delete_set
# Uncommenting the next line will raise a NameError because the set is deleted
# print(delete_set)

Output

Original Set: {'red', 'green', 'blue', 'yellow'}


Number of elements in the set: 4
Type of colors: <class 'set'>
Class of student1: <class '__main__.Student'>
Class Name: Student
Student Name: Manpreet Kaur

Accessing items in the set:


red
green
blue
yellow

Membership Test:
Is 'red' in colors? True
Is 'black' in colors? False

After adding 'black': {'red', 'green', 'blue', 'yellow', 'black'}


After updating with multiple colors: {'red', 'green', 'blue', 'yellow', 'black', 'white', 'pink'}

Combined Set using union(): {'red', 'green', 'blue', 'yellow', 'black', 'white', 'pink', 'orange', 'purple'}
16 . Write a program to frozen set syntax examples.

Syntax

frozenset(iterable)

Examples
# Creating a frozenset from a list
fruits = frozenset(["apple", "banana", "cherry"])

print("Frozenset:", fruits)
print("Type:", type(fruits))
print("Length:", len(fruits))

Output

Frozenset: frozenset({'apple', 'banana', 'cherry'})


Type: <class 'frozenset'>
Length: 3.

You might also like