0% found this document useful (0 votes)
0 views10 pages

Python Programs -Unit i & II

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)
0 views10 pages

Python Programs -Unit i & II

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
You are on page 1/ 10

1. Write a python program to find the largest element among three Numbers.

# Taking input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Checking which number is the largest


if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

# Displaying the result


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

2. Write a Program to display all prime numbers within an interval

# Function to check if a number is prime

def is_prime(num):

if num <= 1:

return False

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

if num % i == 0:

return False

return True

# Taking interval input from the user

start = int(input("Enter the start of interval: "))


end = int(input("Enter the end of interval: "))

print(f"Prime numbers between {start} and {end} are:")

# Loop through the interval and print prime numbers

for number in range(start, end + 1):

if is_prime(number):

print(number, end=" ")

OUTPUT:

3. Write a program to swap two numbers without using a temporary variable.

# Taking input from the user

a = int(input("Enter the first number (a): "))

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

print(f"Before swapping: a = {a}, b = {b}")

# Swapping without using a temporary variable

a=a+b

b=a-b

a=a-b

print(f"After swapping: a = {a}, b = {b}")

OUTPUT:

4. Demonstrate the following Operators in Python with suitable examples.

i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators iv) Logical

Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators
viii) Identity Operators

# i) Arithmetic Operators

a = 10

b=3

print("Arithmetic Operators:")

print("a + b =", a + b) # Addition

print("a - b =", a - b) # Subtraction

print("a * b =", a * b) # Multiplication

print("a / b =", a / b) # Division

print("a % b =", a % b) # Modulus

print("a ** b =", a ** b) # Exponent

print("a // b =", a // b) # Floor Division

print()

# ii) Relational (Comparison) Operators

print("Relational Operators:")

print("a == b:", a == b) # Equal to

print("a != b:", a != b) # Not equal to

print("a > b:", a > b) # Greater than

print("a < b:", a < b) # Less than

print("a >= b:", a >= b) # Greater than or equal to

print("a <= b:", a <= b) # Less than or equal to

print()

# iii) Assignment Operators

print("Assignment Operators:")

x=5

print("x =", x)

x += 3

print("x += 3:", x)

x -= 2
print("x -= 2:", x)

x *= 2

print("x *= 2:", x)

x /= 3

print("x /= 3:", x)

x %= 2

print("x %= 2:", x)

print()

# iv) Logical Operators

print("Logical Operators:")

p = True

q = False

print("p and q:", p and q) # Logical AND

print("p or q:", p or q) # Logical OR

print("not p:", not p) # Logical NOT

print()

# v) Bitwise Operators

print("Bitwise Operators:")

m=5 # 0101

n=3 # 0011

print("m & n =", m & n) # AND

print("m | n =", m | n) # OR

print("m ^ n =", m ^ n) # XOR

print("~m =", ~m) # NOT

print("m << 1 =", m << 1) # Left Shift

print("m >> 1 =", m >> 1) # Right Shift

print()

# vi) Ternary Operator


print("Ternary Operator:")

age = 18

result = "Eligible" if age >= 18 else "Not Eligible"

print("Age:", age, "| Result:", result)

print()

# vii) Membership Operators

print("Membership Operators:")

my_list = [1, 2, 3, 4, 5]

print("3 in my_list:", 3 in my_list)

print("6 not in my_list:", 6 not in my_list)

print()

# viii) Identity Operators

print("Identity Operators:")

x = [1, 2, 3]

y=x

z = [1, 2, 3]

print("x is y:", x is y) # True (same object)

print("x is z:", x is z) # False (different objects)

print("x == z:", x == z) # True (same content)

OUTPUT:

5. Write a program to add and multiply complex numbers

# Taking input for two complex numbers

real1 = float(input("Enter real part of first complex number: "))

imag1 = float(input("Enter imaginary part of first complex number: "))

real2 = float(input("Enter real part of second complex number: "))

imag2 = float(input("Enter imaginary part of second complex number: "))


# Creating complex numbers

c1 = complex(real1, imag1)

c2 = complex(real2, imag2)

# Performing addition and multiplication

sum_result = c1 + c2

product_result = c1 * c2

# Displaying results

print(f"\nFirst complex number: {c1}")

print(f"Second complex number: {c2}")

print(f"Sum: {sum_result}")

print(f"Product: {product_result}")

output:

6. Write a program to print multiplication table of a given number.

# Taking input from the user

num = int(input("Enter a number to print its multiplication table: "))

# Printing the multiplication table

print(f"\nMultiplication Table of {num}:\n")

for i in range(1, 11):

print(f"{num} x {i} = {num * i}")

7. Write a python program to define a function with multiple return values

def calculate_operations(a, b):

addition = a + b

subtraction = a - b

multiplication = a * b

division = a / b
#if b != 0 else "Cannot divide by zero"

# Returning multiple values

return addition, subtraction, multiplication, division

# Calling the function

x = 20

y = 10

add, sub, mul, div = calculate_operations(x, y)

# Displaying the results

print("Addition:", add)

print("Subtraction:", sub)

print("Multiplication:", mul)

print("Division:", div)

output:

8. Write a python program to define a function using default arguments

def greet(name="Guest"):

print("Hello,", name)

# Calling with no argument

greet()

# Calling with one argument

greet("Alice")

OR

def student_info(name, course="B.Tech", branch="CSE"):

print("Name:", name)
print("Course:", course)

print("Branch:", branch)

print()

student_info("Ravi")

student_info("Sita", "M.Tech")

student_info("Arjun", "B.Tech", "ECE")

output:

9. Write a python program to find the length of the string without using any library function

def find_length(s):

count = 0

for char in s:

count += 1

return count

#input from user

input_string = input("Enter a string:")

length = find_length(input_string)

print("Length of the string is:", length)

output:

10. Write a python program to check if the substring is present in a given string or not

# Input main string and substring from the user

main_string = input("Enter the main string: ")

substring = input("Enter the substring to search: ")

# Check if substring is present in the main string

if substring in main_string:
print("Yes, the substring is present in the main string.")

else:

print("No, the substring is not present in the main string.")

output:

11. Write a python program to perform the given operationson a list

i. Addition ii. Insertion iii. Slicing

# Initialize a sample list


my_list = [10, 20, 30, 40, 50]
print(f"Original list: {my_list}")

# i) Addition (appending an element)


# The append() method adds an element to the end of the list.
my_list.append(60)
print(f"After addition (append 60): {my_list}")

# You can also "add" elements from another iterable using extend()
another_list = [70, 80]
my_list.extend(another_list)
print(f"After addition (extend with [70, 80]): {my_list}")

# ii) Insertion
# The insert() method inserts an element at a specified index.
# Syntax: list.insert(index, element)
my_list.insert(2, 25) # Insert 25 at index 2
print(f"After insertion (insert 25 at index 2): {my_list}")

# iii) Slicing
# Slicing creates a new list containing a subset of elements from the original list.
# Syntax: list[start:end:step]
# Get elements from index 1 up to (but not including) index 5
slice1 = my_list[1:6]
print(f"Slice from index 1 to 5 (exclusive): {slice1}")

# Get elements from the beginning up to index 4 (exclusive)


slice2 = my_list[:5]
print(f"Slice from beginning to index 4 (exclusive): {slice2}")

# Get elements from index 3 to the end


slice3 = my_list[3:]
print(f"Slice from index 3 to end: {slice3}")
# Get every other element
slice4 = my_list[::2]
print(f"Slice with a step of 2 (every other element): {slice4}")

# Reverse the list using slicing


reversed_list = my_list[::-1]
print(f"Reversed list using slicing: {reversed_list}")

Output:

12. Write a python program to perform any five built in functions by taking any list

# Define a sample list


my_list = [10, 5, 20, 15, 8, 25]

print(f"Original list: {my_list}")

# 1. len(): Returns the number of items in the list.


list_length = len(my_list)
print(f"Length of the list (len()): {list_length}")

# 2. max(): Returns the largest item in the list.


maximum_value = max(my_list)
print(f"Maximum value in the list (max()): {maximum_value}")

# 3. min(): Returns the smallest item in the list.


minimum_value = min(my_list)
print(f"Minimum value in the list (min()): {minimum_value}")

# 4. sum(): Returns the sum of all items in the list.


total_sum = sum(my_list)
print(f"Sum of all items in the list (sum()): {total_sum}")

# 5. sorted(): Returns a new sorted list from the items in the iterable.
sorted_list = sorted(my_list)
print(f"Sorted list (sorted()): {sorted_list}")

# Demonstrate that sorted() returns a new list and doesn't modify the original
print(f"Original list after sorting (remains unchanged): {my_list}")

Output:

You might also like