0% found this document useful (0 votes)
2 views35 pages

Python RecordH2

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)
2 views35 pages

Python RecordH2

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

Program:

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

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

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

if (num1 >= num2) and (num1 >= num3):

largest = num1

elif (num2 >= num1) and (num2 >= num3):

largest = num2

else:

largest = num3 print(f"The largest number is {largest}")

Output:
Enter first number: 5
Enter second number: 3 Enter third number: 8

The largest number is 8

24F41A05H2
Program:
lower = int(input("Enter lower range: "))

upper = int(input("Enter upper range: "))

print(f"Prime numbers between {lower} and {upper}are:") for num in

range(lower, upper + 1):

if num > 1:

for i in range(2, num):

if (num % i) == 0:

break else:

print(num)
Output:
Enter lower range: 10
Enter upper range: 20
Prime numbers between 10 and 20 are:
11
13
17
19

24F41A05H2
Program:
a = int(input("Enter first number: "))

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

b=a–b

a=a-b

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

Output:
Enter first number: 5
Enter second number: 8
After swapping: a = 8, b = 5

24F41A05H2
Program:
# Arithmetic Operators

a = 10

b = 3 print("ArithmeticOperators:")

print(f"Addition: {a + b}, Subtraction: {a - b}, Multiplication: {a * b},


Division: {a / b}, Modulus: {a % b}, Exponent: {a ** b}, Floor division: {a //
b}")
# Relational Operators print("Relational Operators:")

print(f"a == b: {a == b}, a != b: {a != b}, a > b: {a > b}, a < b: {a < b}, a >= b:

{a >= b}, a <= b: {a <= b}")

# Assignment Operators

print("Assignment Operators:")

a += b # a = a + b

print(f"a += b: {a}")

# Logical Operators

print("Logical Operators:")

print(f"(a > 0 and b > 0): {(a > 0 and b > 0)}, (a > 0 or b > 0): {(a > 0 or b >

0)}, not(a > 0): {not(a > 0)}")

# Bitwise Operators print("Bitwise Operators:")

24F41A05H2
print(f"a & b: {a & b}, a | b: {a | b}, a ^ b: {a ^ b}, ~a: {~a}, a << 2: {a << 2},

a >> 2: {a >> 2}")

# Ternary Operator

print("Ternary Operator:")

min_val = a if a < b else b

print(f"Minimum value between a and b is{min_val}")

# Membership Operators print("Membership Operators:")

my_list = [1, 2, 3, 4, 5] print(f"Is 3 in list: {3 in my_list}, Is not in list: {6 not

in my_list}")

# Identity Operators print("Identity Operators:")

print(f"a is b: {a is b}, a is not b: {a is not b}")

24F41A05H2
Output:
Arithmetic Operators:
Addition: 13, Subtraction: 7, Multiplication: 30, Division:
3.3333333333333335, Modulus: 1, Exponent: 1000, Floor division: 3
Relational Operators:
a == b: False, a != b: True, a > b: True, a < b: False, a >= b: True, a <= b:
False
Assignment Operators:
a += b: 13
Logical Operators:
(a > 0 and b > 0): True, (a > 0 or b > 0): True, not(a > 0): False
Bitwise Operators:
a & b: 1, a | b: 15, a ^ b: 14, ~a: -14, a << 2: 52, a >> 2: 3
Ternary Operator:
Minimum value between a and b is: 3

Membership Operators:

Is 3 in list: True, Is 6 not in list: True


Identity Operators: a is b: False, a is not b: True

24F41A05H2
Program:
c1 = complex(input("Enter first complex number (a+bj format): "))

c2 = complex(input("Enter second complex number (a+bj format):"))

sum_c = c1 + c2 prod_c = c1 * c2

print(f"Sum of {c1} and {c2} is {sum_c}")

print(f"Product of {c1} and {c2} is {prod_c}")

Output:

Enter first complex number (a+bj format): 1+2j


Enter second complex number (a+bj format): 3+4j
Sum of (1+2j) and (3+4j) is (4+6j)
Product of (1+2j) and (3+4j) is (-5+10j)

24F41A05H2
Program:
num = int(input("Enter the number: ")) print(f"Multiplication table of

{num}:"

) for i in range(1, 11):

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


Output:
Enter the number: 5
Multiplication table of 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

24F41A05H2
Program:
def calculate(a, b):

sum_val = a + b

product = a * b

return sum_val,

product a, b = 5, 10

result_sum, result_prod = calculate(a, b) print(f"Sum: {result_sum},

Product: {result_prod}")

Output:
Sum: 15, Product: 50

24F41A05H2
Program:
def greet(name="User"):

print(f"Hello, {name}!")

greet("Nanda")
greet()

Output:

Hello, Nanda!
Hello, User!

24F41A05H2
Program:
my_str = input("Enter a string: ") length = 0

for char in my_str:

length += 1

print(f"The length of the string is: {length}")

Output:
Enter a string: Python
The length of the string is: 6

24F41A05H2
Program:
# Input main string and substring

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

sub_str = input("Enter the substring: ")

if sub_str in main_str:

print(f"The substring '{sub_str}' is present in the main string.")

else:

print(f"The substring '{sub_str}' is not present in the main string.")


Output:
Enter the main string: Hello Python
Enter the substring: Python
The substring 'Python' is present in the main string.

24F41A05H2
Program:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)

print(f"List after addition: {my_list}")

# Insertion

my_list.insert(2, 10)

print(f"List after insertion: {my_list}")

# Slicing

sliced_list = my_list[1:4] print(f"Sliced list: {sliced_list}")

Output:

List after addition: [1, 2, 3, 4, 5, 6]


List after insertion: [1, 2, 10, 3, 4, 5, 6]
Sliced list: [2, 10, 3]

24F41A05H2
Program:
my_list = [3, 1, 4, 1, 5, 9, 2]

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

print(f"Maximum value: {max(my_list)}")

print(f"Minimum value: {min(my_list)}")

print(f"Sum of the elements: {sum(my_list)}")

print(f"Sorted list: {sorted(my_list)}")

Output:
Length of the list: 7
Maximum value: 9
Minimum value: 1
Sum of the elements: 25
Sorted list: [1, 1, 2, 3, 4, 5, 9]

24F41A05H2
Program:
member1 = ("Nanda", 21, "Address1", "KEC")

member2 = ("Ravi", 22, "Address2", "KEC")

concatenated_tuple = member1 + member2

print(f"Concatenated Tuple: {concatenated_tuple}")


Output:
Concatenated Tuple: ('Nanda', 21, 'Address1', 'KEC', 'Ravi', 22, 'Address2',
'KEC')

24F41A05H2
Program:
my_str = input("Enter a string: ")

vowel_count = sum([1 for char in my_str.lower() if char in 'aeiou'])

print(f"Number of vowels: {vowel_count}")

Output:
Enter a string: Hello World
Number of vowels: 3

24F41A05H2
Program:
my_dict = {'name': 'Nanda', 'age': 21, 'college': 'KEC'}

key = input("Enter the key to check: ")

if key in my_dict:

print(f"Key '{key}' exists in the dictionary.")

else:

print(f"Key '{key}' does not exist in the dictionary.")


Output:
Enter the key to check: age
Key 'age' exists in the dictionary.

24F41A05H2
Program:
my_dict = {'name': 'Nanda', 'age': 21, 'college': 'KEC'}

new_key = input("Enter new key: ")

new_value = input("Enter new value: ")

my_dict[new_key] = new_value

print(f"Updated dictionary: {my_dict}")

Output:
Enter new key: address
Enter new value: India
Updated dictionary: {'name': 'Nanda', 'age': 21, 'college': 'KEC', 'address':
'India'}

24F41A05H2
Program:
my_dict = {'a': 10, 'b': 20, 'c': 30}

total_sum = sum(my_dict.values())

print(f"Sum of all items: {total_sum}")

Output:
Sum of all items: 60

24F41A05H2
Program:
with open("[Link]", "r") as source_file:
words = source_file.read().split()

sorted_words = sorted([[Link]() for word in words])

with open("[Link]", "w") as output_file:

output_file.write(' '.join(sorted_words))

Output (in [Link]):

apple banana cat dog.

24F41A05H2
Program:
with open("[Link]", "r") as file:
lines = [Link]()

for line in lines:

print([Link]()[::-1])
Output (if source file has "Hello World" on a line):
dlroW olleH

24F41A05H2
Program:

char_count = word_count = line_count = 0

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


for line in file:

line_count += 1

word_count += len([Link]())

char_count += len(line)

print(f"Lines: {line_count}, Words: {word_count}, Characters:

{char_count}")

Output:
Lines: 3, Words: 6, Characters: 24

24F41A05H2
Program:

import array

arr = [Link]('i', [1, 2, 3, 4, 5])

print("Original array:", arr)

[Link](6)

print("Array after append:", arr)

[Link](2, 10)

print("Array after insertion:", arr)

[Link]()

print("Array after reverse:", arr)

Output:
Original array: array('i', [1, 2, 3, 4, 5])
Array after append: array('i', [1, 2, 3, 4, 5, 6])
Array after insertion: array('i', [1, 2, 10, 3, 4, 5, 6])
Array after reverse: array('i', [6, 5, 4, 3, 10, 2, 1])

24F41A05H2
Program:
import numpy as np
matrix1 = [Link]([[1, 2], [3, 4]])

matrix2 = [Link]([[5, 6], [7, 8]])

matrix_sum = [Link](matrix1, matrix2)

print("Matrix addition:\n", matrix_sum)

matrix_transpose = [Link](matrix1)

print("Transpose of matrix1:\n", matrix_transpose)

matrix_product = [Link](matrix1, matrix2)

print("Matrix multiplication:\n", matrix_product)

Output:
Matrix addition:
[[ 6 8]
[10 12]]
Transpose of matrix1:
[[1 3]
[2 4]]
Matrix multiplication:
[[19 22]
[43 50]]

24F41A05H2
Program:

import math

class Shape:

def area(self):

pass
def perimeter(self):
pass
class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return [Link] * [Link] ** 2

def perimeter(self):

return 2 * [Link] * [Link]


class Square(Shape):
def __init__(self, side):
[Link] = side

def area(self):

return [Link] ** 2

def perimeter(self):

return 4 * [Link]

24F41A05H2
class Triangle(Shape):

def __init__(self, a, b, c):

self.a = a

self.b = b

self.c = c

def area(self):
s = (self.a + self.b + self.c) / 2

return [Link](s * (s - self.a) * (s - self.b) * (s - self.c))

def perimeter(self):

return self.a + self.b + self.c

circle = Circle(5)

print(f"Circle Area: {[Link]()}, Perimeter: {[Link]()}")

square = Square(4)

print(f"Square Area: {[Link]()}, Perimeter: {[Link]()}")

triangle = Triangle(3, 4, 5)

print(f"Triangle Area: {[Link]()}, Perimeter: {[Link]()}")

Output:
Circle Area: 78.53981633974483, Perimeter: 31.41592653589793
Square Area: 16, Perimeter: 16
Triangle Area: 6.0, Perimeter: 12

24F41A05H2
Program:

import json

json_data = '{"name": "John", "age": 30, "address": {"city": "New York"},

"hobbies": ["reading", "traveling"]}'

data = [Link](json_data)

if isinstance(data, dict) and any(isinstance(value, (list, dict)) for value in

[Link]()):

print("The JSON string contains complex objects.")

else:

print("No complex objects found in the JSON string.")


Output:
The JSON string contains complex objects.

24F41A05H2
Program:
import numpy as np
arr1 = [Link]([1, 2, 3])

arr2 = [Link]([[1, 2, 3], [4, 5, 6]])

print("1D Array:", arr1)

print("2D Array:\n", arr2)

Output:

1D Array: [1 2 3]

2D Array:
[[1 2 3]
[4 5 6]]

24F41A05H2
Program:
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])

print(f"Dimensions: {[Link]}")

print(f"Shape: {[Link]}")

print(f"Size: {[Link]}")

print(f"Data type: {[Link]}")

Output:
Dimensions: 2
Shape: (2, 3)
Size: 6
Data type: int64

24F41A05H2
Program:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])

print("Slicing [1:3]:", arr[1:3])

print("Integer indexing [0]:", arr[0])

print("Boolean indexing [arr > 2]:", arr[arr > 2])

Output:
Slicing [1:3]: [2 3]
Integer indexing [0]: 1
Boolean indexing [arr > 2]: [3 4 5]

24F41A05H2
Program:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])

print(f"Min: {[Link](arr)}")

print(f"Max: {[Link](arr)}")

print(f"Sum: {[Link](arr)}")

print(f"Cumulative sum: {[Link](arr)}")

Output:
Min: 1
Max: 5
Sum: 15
Cumulative sum: [ 1 3 6 10 15]

24F41A05H2
Program:
import pandas as pd data = {

'A': [i for i in range(10)],


'B': [i*2 for i in range(10)],
'C': [i**2 for i in range(10)],
'D': [i+5 for i in range(10)],
'E': [i*3 for i in range(10)]
}
df = [Link](data)

print("Head of the DataFrame:\n", [Link]())

print("Select columns A and C:\n", df[['A', 'C']])

Output:
Head of the DataFrame:
A B C D E
0 0 0 0 5 0
1 1 2 1 6 3
2 2 4 4 7 6
3 3 6 9 8 9
4 4 8 16 9 12

24F41A05H2
Select columns A and C:
A C
0 0 0
1 1 1
2 2 4
3 3 9

24F41A05H2
Program:
import pandas as pd import [Link] as plt data = {

'A': [i for i in range(10)],


'B': [i*2 for i in range(10)],
'C': [i**2 for i in range(10)],
'D': [i+5 for i in range(10)],
'E': [i*3 for i in range(10)]
}
df = [Link](data)
x = df['A']

y = df['C']

[Link](x, y)

[Link]('Scatter plot of A vs C')

[Link]('A')

[Link]('C')

[Link]()

[Link](x, y)

[Link]('Line plot of A vs C')

[Link]('A')

[Link]('C')

[Link]()

24F41A05H2
Output:

24F41A05H2

You might also like