Pythonlabques
Pythonlabques
def greet(name):
print("Hello, " + name)
greet("Alice")
output:
a = 10
b=5
add_result = a + b
sub_result = a - b
mul_result = a * b
div_result = a / b
mod_result = a % b
exp_result = a ** b
output:
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50
Division: 10 / 5 = 2.0
Modulus: 10 % 5 = 0
Exponentiation: 10 ** 5 = 100000
Ques 3: WAP that takes command line argument as input and print the addition of two
numbers as output.
import sys
def main():
if len(sys.argv) != 3:
return
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
python add_numbers.py 5 10
import math
return distance
def main():
try:
print("The distance between the points ({}, {}) and ({}, {}) is: {:.2f}".format(x1, y1, x2, y2,
distance))
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 5: create a string “hello world ” and perform the following operation :
# Note: Indexing in Python starts from 0, so characters from index 2 to 4 are the 3rd to 5th
characters.
OUTPUT :
Ques 6: Create a List containing the following items and perform the following operations-
Student =[ 556,”Mothi”,84,96,84,75,84]
OUTPUT :
import pandas as pd
data = {
df = pd.DataFrame(data)
print("DataFrame:")
print(df)
OUTPUT :
DataFrame:
Student_ID Name Math_Score Science_Score English_Score
0 556 Mothi 84 96 84
1 557 Alice 90 85 79
2 558 Bob 78 88 92
Ques 8: write a program to check whether the given no is even or odd
def check_even_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
def main():
try:
result = check_even_odd(number)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 12
The number 12 is even.
Ques 9 :Write a program to get the marks of 5 subjects and calculate the average marks
scored and calculate the grade based on the average marks
If
71 to 80 (C grade )
61 to 60 (D grade)
51 to 60 (E grade)
>50 (fail)
def calculate_grade(average):
return 'A'
return 'B'
return 'C'
return 'D'
return 'E'
else:
return 'Fail'
def main():
try:
marks = []
marks.append(mark)
grade = calculate_grade(average)
print(f"Grade: {grade}")
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 10: Write a program to implement the simple calculator that performs basic
mathematical operation it takes 3 inputs from the user at first the user is asked to enter 2
numbers after that the user is asked to enter the operator based on which arithmetic
operation is performed
return x + y
return x - y
return x * y
if y == 0:
else:
return x / y
def main():
try:
if operator == '+':
else:
print("Result:", result)
except ValueError:
except Exception as e:
if __name__ == "__main__":
main()
OUTPUT :
def check_case(char):
if char.islower():
return "Lowercase"
elif char.isupper():
return "Uppercase"
else:
def main():
try:
case = check_case(char)
except Exception as e:
if __name__ == "__main__":
main()
OUTPUT :
Enter a character: a
The character 'a' is in Lowercase.
Ques 12: Write a program that ask user to enter the number and if the entered number is
greater that or equal to 100 check the number is even or odd if number is less that 100 it will
not check the number is even or not it will only print the message that the number is less
100
def check_even_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
def main():
try:
result = check_even_odd(number)
else:
except ValueError:
main()
OUTPUT :
Ques 13: Write a program to check whether the given year is leap or not
def is_leap_year(year):
return True
else:
return False
def main():
try:
if is_leap_year(year):
else:
except ValueError:
main()
OUTPUT :
Ques 14: write a program to print even numbers upto n using while loop
def print_even_numbers(n):
i=2
while i <= n:
i += 2
def main():
try:
print_even_numbers(n)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 15: wap to find the sum of the two matrixes using for loop
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
def main():
try:
if isinstance(result, str):
print(result)
else:
print(row)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 16: wap to find the sum of n natural numbers using while loop and for loop and should
be entered by the user
def sum_of_natural_numbers_while(n):
sum = 0
i=1
while i <= n:
sum += i
i += 1
return sum
def main_while():
try:
if n < 1:
return
result = sum_of_natural_numbers_while(n)
print("Sum of the first {} natural numbers using while loop: {}".format(n, result))
except ValueError:
main_while()
OUTPUT :
def sum_of_natural_numbers_for(n):
sum = 0
sum += i
return sum
def main_for():
try:
if n < 1:
return
result = sum_of_natural_numbers_for(n)
print("Sum of the first {} natural numbers using for loop: {}".format(n, result))
except ValueError:
if __name__ == "__main__":
main_for()
OUTPUT :
22
333
4444
55555
def print_pattern(rows):
print(str(i) * i)
def main():
try:
print("Pattern:")
print_pattern(rows)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 18: wap to calculate the power of the number using the anonymous function
def main():
try:
# Take input from the user for the base and exponent
print("Result:", result)
except ValueError:
print("Please enter valid numeric values for the base and exponent.")
if __name__ == "__main__":
main()
OUTPUT :
return x + y
return x - y
return x * y
if y == 0:
else:
return x / y
def main():
try:
print("\nOperations:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice == '1':
else:
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 20: create a txt file intern.txt and ask the user to write a single line of text by user input
def main():
try:
file.write(line)
except Exception as e:
if __name__ == "__main__":
main()
OUTPUT :
def main():
try:
for i in range(3):
file.write(line + "\n")
except Exception as e:
if __name__ == "__main__":
main()
OUTPUT :
Ques 22: wap to read the content of both the file created in above program and merge the
content intol merge.txt
def merge_files():
try:
# Open the first file (intern.txt) in read mode ('r')
content1 = file1.read()
content2 = file2.read()
merge_file.write(merged_content)
except Exception as e:
if __name__ == "__main__":
merge_files()
OUTPUT :
Ques 23: count the total number of uppercase and lowercase and digit used in merge.txt
def count_characters(filename):
try:
content = file.read()
# Initialize counters
uppercase_count = 0
lowercase_count = 0
digit_count = 0
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
elif char.isdigit():
digit_count += 1
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
count_characters("merge.txt")
OUTPUT :
def is_prime(number):
if number <= 1:
return False
return True
return False
i=5
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def main():
try:
# Take input from the user
if is_prime(num):
else:
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 23
23 is a prime number.
Ques 25: develop a python program to print all the prime numbers within a range of
numbers
def is_prime(number):
if number <= 1:
return False
return True
return False
i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
if is_prime(num):
def main():
try:
print_primes(start, end)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Enter the start of the range: 1
Enter the end of the range: 50
Prime numbers between 1 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Ques 26:develop a python program to find the largest and smallest number in the list
def find_largest_and_smallest(numbers):
if not numbers:
# Initialize the largest and smallest with the first element of the list
largest = numbers[0]
smallest = numbers[0]
# Iterate through the list to find the largest and smallest numbers
largest = number
smallest = number
def main():
try:
else:
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 27: develop a python program to develop a calculator and perform the basic
calculation based on the user input and menu should be continuity available
return x + y
return x - y
def multiply(x, y):
return x * y
if y == 0:
else:
return x / y
def menu():
print("\nSelect operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
def main():
while True:
menu()
try:
if choice == '5':
break
if choice in ('1', '2', '3', '4'):
if choice == '1':
else:
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 1
Enter first number: 2
Enter second number: 3
The result of addition is: 5.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 2
Enter first number: 5
Enter second number: 3
The result of subtraction is: 2.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 3
Enter first number: 2
Enter second number: 3
The result of multiplication is: 6.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 4
Enter first number: 10
Enter second number: 2
The result of division is: 5.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 5
Exiting the calculator. Goodbye!
print("Positional arguments:")
print("\nKeyword arguments:")
print(f"{key}: {value}")
def main():
if __name__ == "__main__":
main()
OUTPUT :
Positional arguments:
arg1: 1
arg2: hello
arg3: True
Keyword arguments:
name: Alice
age: 30
city: Wonderland
[ ]:
if operator == '+':
if num2 == 0:
else:
else:
def main():
while True:
try:
if again != 'yes':
print("Exiting the calculator. Goodbye!")
break
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 30: wap to find the middle element of the string passed and id middle element is not
therir than return nothing
def find_middle_element(s):
length = len(s)
if length % 2 != 0:
middle_index = length // 2
return s[middle_index]
else:
return "Nothing"
def main():
result = find_middle_element(user_input)
if __name__ == "__main__":
main()
OUTPUT :
Ques 31: wap by define a function to calculate mean median of array of the number
def calculate_mean(numbers):
if not numbers:
def calculate_median(numbers):
if not numbers:
sorted_numbers = sorted(numbers)
length = len(sorted_numbers)
middle_index = length // 2
if length % 2 == 0:
else:
median = sorted_numbers[middle_index]
return median
def main():
try:
mean = calculate_mean(numbers)
median = calculate_median(numbers)
else:
print("The list is empty.")
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 32: wap to change the string to the new string where the first and the last character
has been existed
def swap_first_last_characters(s):
if len(s) <= 1:
return s
return new_string
def main():
# Get the new string with the first and last characters swapped
result = swap_first_last_characters(user_input)
if __name__ == "__main__":
main()
OUTPUT :
def print_string_length(s):
length = len(s)
def main():
print_string_length(user_input)
if __name__ == "__main__":
main()
OUTPUT :
Ques 34: create a function to print the square of the number using the function
def print_square_of_number(n):
square = n * n
def main():
try:
print_square_of_number(user_input)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 5
The square of 5.0 is: 25.0
def print_name():
print(f"Hello, {name}!")
def main():
print_name()
if __name__ == "__main__":
main()
OUTPUT :
def factorial(n):
if n < 0:
elif n == 0 or n == 1:
return 1
else:
result = 1
result *= i
return result
def main():
try:
result = factorial(user_input)
except ValueError:
if __name__ == "__main__":
main()
OUTPUT :
Ques 37:write a pandas program to create and display array using pandas model
import pandas as pd
import numpy as np
def create_and_display_array():
print(df)
def main():
create_and_display_array()
if __name__ == "__main__":
main()
OUTPUT :
import pandas as pd
def convert_series_to_list():
data_list = data.tolist()
print(data)
print(data_list)
def main():
convert_series_to_list()
if __name__ == "__main__":
main()
OUTPUT :
import pandas as pd
def perform_operations(series1, series2):
# Addition
# Subtraction
# Multiplication
# Division
print("Series 1:")
print(series1)
print("\nSeries 2:")
print(series2)
print("\nAddition of Series:")
print(addition)
print("\nSubtraction of Series:")
print(subtraction)
print("\nMultiplication of Series:")
print(multiplication)
print("\nDivision of Series:")
print(division)
def main():
perform_operations(series1, series2)
if __name__ == "__main__":
main()
OUTPUT :
Series 1:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Series 2:
0 5
1 4
2 3
3 2
4 1
dtype: int64
Addition of Series:
0 15
1 24
2 33
3 42
4 51
dtype: int64
Subtraction of Series:
0 5
1 16
2 27
3 38
4 49
dtype: int64
Multiplication of Series:
0 50
1 80
2 90
3 80
4 50
dtype: int64
Division of Series:
0 2.0
1 5.0
2 10.0
3 20.0
4 50.0
dtype: float64
import numpy as np
import pandas as pd
def convert_array_to_series(array):
series = pd.Series(array)
print(array)
print(series)
def main():
# Create a NumPy array
# Call the function to convert the array to a series and display the result
convert_array_to_series(array)
if __name__ == "__main__":
main()
OUTPUT :
Ques 41: wap to create a display a dataframe from dic which has index label
import pandas as pd
# Example dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
Output:
Name Age City
Person1 Alice 25 New York
Person2 Bob 30 Los Angeles
Person3 Charlie 35 Chicago
Ques 42: Using the dirtydata csv fix the bad data set( bad data could be : empty cell ,data in
wrong format ,duplicate data and wrong data)
import pandas as pd
df = pd.read_csv('dirtydata.csv')
print("Initial DataFrame:")
print(df)
df.dropna(inplace=True)
# df.fillna({
# 'column_name': 'fill_value',
# 'another_column_name': 'another_fill_value'
# }, inplace=True)
df.drop_duplicates(inplace=True)
df.loc[df['score'] > 100, 'score'] = 100 # assuming scores should be between 0 and 100
print("Cleaned DataFrame:")
print(df)
df.to_csv('cleaneddata.csv', index=False)
Ques 43: wap to fix the wrong data using pandas (file used for the operation is dirtydata.csv)
import pandas as pd
print("Initial DataFrame:")
print(df)
df.dropna(inplace=True)
# Option 2: Fill empty cells with a specific value (e.g., fill numeric columns with 0 and string
columns with 'Unknown')
# df.fillna({
# 'column_name': 'fill_value',
# 'another_column_name': 'another_fill_value'
# }, inplace=True)
if 'date_column' in df.columns:
if 'numeric_column' in df.columns:
df.drop_duplicates(inplace=True)
# Replace negative ages with the column's mean age (assuming age should be positive)
if 'age' in df.columns:
if 'score' in df.columns:
df.loc[df['score'] > 100, 'score'] = 100 # assuming scores should be between 0 and 100
if 'gender' in df.columns:
print("Cleaned DataFrame:")
print(df)
df.to_csv('cleaneddata.csv', index=False)
Ques 44:using pandas remove the duplicate data (file used for the operation is dirtydata.csv)
import pandas as pd
df = pd.read_csv('dirtydata.csv')
print("Initial DataFrame:")
print(df)
df.drop_duplicates(inplace=True)
print(df)
df.to_csv('cleaneddata.csv', index=False)
ques 45: wap to find the sum of all elements in a list
numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers)
numbers = [1, 2, 3, 4, 5, 2, 3, 1]
unique_numbers = list(set(numbers))
Ques 47: create a program to reverse a li8st without using build in function
numbers = [1, 2, 3, 4, 5]
reversed_numbers = []
# Iterate over the original list in reverse order and append elements to the new list
reversed_numbers.append(numbers[i])
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
if len(numbers) == 0:
raise ValueError("The list is empty, cannot find maximum and minimum values.")
max_element = numbers[0]
min_element = numbers[0]
# Iterate through the list to find the maximum and minimum values
max_element = num
min_element = num
Ques 49: implement a program to sort the list of integer in asc order without using build in
function
def bubble_sort(arr):
n = len(arr)
bubble_sort(numbers)
print("
length = len(my_tuple)
return concatenated_tuple
# Example tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Iterate through the tuple elements and find the index of the element
for i in range(len(tuple)):
if tuple[i] == element:
return i
return -1
# Example tuple
# Element to find
element_to_find = 30
if index != -1:
Ques 53: create a program to count the occurrence of an element in the tuple
count = 0
# Iterate through the tuple elements and count the occurrences of the element
if item == element:
count += 1
return count
# Example tuple
my_tuple = (1, 2, 3, 1, 4, 1, 5)
# Element to count
element_to_count = 1
print("The occurrence count of", element_to_count, "in the tuple is:", occurrence_count)
Ques 54: write a function to check if two tuples have any element in common
if element in tuple2:
return True
# If no common element found, return False
return False
# Example tuples
tuple1 = (1, 2, 3, 4, 5)
# Check if the tuples have any common element using the have_common_element function
if have_common_element(tuple1, tuple2):
else:
Ques 55: wap to illiterate over a dic and print key values pair
# Define a dictionary
return merged_dict
# Example dictionaries
Ques 57: wap to find the keys corresponding to the max and min value in the dic
def find_max_min_keys(dictionary):
if not dictionary:
# Initialize variables to store max and min values and their corresponding keys
max_value = value
max_key = key
min_value = value
min_key = key
# Example dictionary
# Find keys corresponding to max and min values using the function
max_key, min_key = find_max_min_keys(my_dict)
# Example dictionary
# Key to check
key_to_check = 'b'
if key_exists(my_dict, key_to_check):
else:
def sort_dict_by_value_asc(dictionary):
# Use sorted() function with a lambda function as key to sort dictionary by value in
ascending order
return sorted_dict
# Example dictionary
# Sort the dictionary by value in ascending order using the sort_dict_by_value_asc function
sorted_dict = sort_dict_by_value_asc(my_dict)
Ques 60: wap to create a set and perform basic set operation (union, intersection and
difference)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set1 = set1.difference(set2)
difference_set2 = set2.difference(set1)
Ques 62: wap to check if two sets have any elements in common
# Example sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Check if the sets have any common elements using the have_common_elements function
if have_common_elements(set1, set2):
for i in range(1,n+1):
print(" "*(n-i),end="")
for j in range(1,i+1):
print(chr(64+j),end=" ")
print()
for i in range(1,num+1):
print(" "*(i-1),end="")
for j in range(1,num+2-i):
print(chr(65+num-i),end=" ")
for k in range(2,num+2-i):
print(chr(65+num-i),end=" ")
print()
num=int(input("Enter a number:"))
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(1,i+1):
print(num-j,end=" ")
print()
for k in range(1,num):
print(" "*k,end="")
for l in range(1,num+1-k):
print(num-1,end=" ")
print()
num=int(input("Enter a number:"))
for i in range(1,num+1):
for j in range(1,i+1):
print(num-i+j-1,end="")
print()
for a in range(1,num+1):
for k in range(0,num-a):
print(k+a,end="")
print()
num=int(input("Enter a number:"))
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(0,i):
print(chr(65+num+j-i),end=" ")
print()
for k in range(1,num):
print(" "*k,end="")
for l in range(0,num-k):
print(chr(65+k+1),end=" ")
print()
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(1,i+1):
print("*",end=" ")
print(" "*(num-i),end="")
for k in range(1,i+1):
print("*",end=" ")
print()