Python Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

SCRIPTING LANGUAGE USING (PYTHON)

1. Running instructions in Interactive interpreter and a Python Script:

Interactive Interpreter:

 Open your terminal or command prompt.


 Type python and press Enter to enter the interactive mode.
 Now, you can type Python code directly and see the results.

Python Script:

 Create a new file with a .py extension, e.g., myscript.py.


 Write your Python code in the file.
 Open a terminal or command prompt, navigate to the file's directory, and run python
myscript.py.

2. Write a script to purposefully raise Indentation Error and Correct it:


# Indentation Error Script

def indentation_error_example():

print("This line will cause an IndentationError.")

# Corrected Script

def corrected_script():

print("This line is correctly indented.")

3. Write a script to find the Sum and average of first n natural numbers:

def sum_and_average(n):

numbers = list(range(1, n + 1))

total = sum(numbers)

average = total / n

return total, average

n = int(input("Enter the value of n: "))

result = sum_and_average(n)

print(f"Sum: {result[0]}, Average: {result[1]}")

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

4. Given 2 strings, s1 and s2, create a new string by appending s2 in the middle of s1:
def append_middle(s1, s2):
middle_index = len(s1) // 2
result = s1[:middle_index] + s2 + s1[middle_index:]
return result

s1 = input("Enter the first string: ")


s2 = input("Enter the second string: ")
new_string = append_middle(s1, s2)
print("Result:", new_string)

OUTPUT

5. Write a script to check whether a given string is a palindrome or not


def is_palindrome(s):

return s == s[::-1]

word = input("Enter a string: ")

if is_palindrome(word):

print("It's a palindrome.")

else:

print("It's not a palindrome.")

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

6. Write a script using a for loop that loops over a sequence:Write a program add.py
that takes 2 numbers as command line arguments and prints their sum:
# add.py

import sys

if len(sys.argv) != 3:

print("Usage: python add.py <num1> <num2>")

else:

num1 = float(sys.argv[1])

num2 = float(sys.argv[2])

result = num1 + num2

print(f"Sum: {result}")

OUTPUT

7. Write a script using a for loop that loops over a sequence:


# Loop over a sequence

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

for num in numbers:

print(num)

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

8. Write a script to count the numbers of characters in the string and store them in a
dictionary data structure:
def count_characters(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
return char_count

input_string = input("Enter a string: ")


result_dict = count_characters(input_string)
print("Character Count:", result_dict)
OUTPUT

9. Write a program to use split and join methods in the string and trace a birthday with
a dictionary data structure:
def add_birthday(dictionary, name, birthday):
dictionary[name] = birthday

def find_birthday(dictionary, name):


return dictionary.get(name, "Birthday not found for {}".format(name))

def main():
# Initialize an empty dictionary to store birthdays
birthday_dict = {}

# Adding birthdays to the dictionary


add_birthday(birthday_dict, "Alice", "1990-05-15")
add_birthday(birthday_dict, "Bob", "1985-08-22")
add_birthday(birthday_dict, "Charlie", "1995-02-10")
add_birthday(birthday_dict, "David", "1992-11-30")

# Print the dictionary


print("Birthday Dictionary:")
for name, birthday in birthday_dict.items():
print(f"{name}: {birthday}")

# Joining dictionary values into a string


birthday_string = ','.join(f"{name}:{birthday}" for name, birthday in birthday_dict.items())
print("\nJoined String:", birthday_string)

# Splitting the joined string back into a dictionary


split_birthday_list = birthday_string.split(',')
split_birthday_dict = {}
for item in split_birthday_list:
SCRIPTING LANGUAGE USING (PYTHON)
name, birthday = item.split(':')
split_birthday_dict[name] = birthday

# Print the split dictionary


print("\nSplit Dictionary:")
for name, birthday in split_birthday_dict.items():
print(f"{name}: {birthday}")

# Search for a birthday in the split dictionary


search_name = "Bob"
result = find_birthday(split_birthday_dict, search_name)
print(f"\nBirthday for {search_name}: {result}")

if __name__ == "__main__":
main()

10. Write a script that combines more than one list into a dictionary:
# Combine lists into a dictionary

keys = ['name', 'age', 'city']

values = ['Basak', 20, 'Raiganj']

combined_dict = dict(zip(keys, values))

print("Combined Dictionary:", combined_dict)

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

11. Compute the GCD (Greatest Common Divisor) & LCM (Least Common Multiple) of
two numbers:
import math

def compute_gcd(x, y):

return math.gcd(x, y)

def compute_lcm(x, y):

return abs(x * y) // math.gcd(x, y)

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

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

gcd_result = compute_gcd(num1, num2)

lcm_result = compute_lcm(num1, num2)

print(f"GCD: {gcd_result}")

print(f"LCM: {lcm_result}")

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

12. Check if a number is prime or not


def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

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


if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
OUTPUT

13.Find the square root of a number:


import math

number = float(input("Enter a number: "))


sqrt_result = math.sqrt(number)
print(f"The square root of {number} is {sqrt_result}")
OUTPUT

14. Exponentiation (power of a number):


base = float(input("Enter the base: "))
exponent = float(input("Enter the exponent: "))
result = base ** exponent
print(f"{base} raised to the power of {exponent} is {result}")
OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

15. Find all primes within a given range:


def sieve_of_eratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize all entries as True
prime = [True for _ in range(n + 1)]
p=2
while p**2 <= n:
# If prime[p] is not changed, then it is a prime
if prime[p]:
# Update all multiples of p
for i in range(p**2, n + 1, p):
prime[i] = False
p += 1

# Collect the prime numbers


primes = [i for i in range(2, n + 1) if prime[i]]
return primes

def find_primes_in_range(start, end):


if start < 2:
start = 2 # Prime numbers start from 2
primes = sieve_of_eratosthenes(end)
primes_in_range = [p for p in primes if start <= p <= end]
return primes_in_range

def main():
# Set the range for finding prime numbers
start_range = 10
end_range = 50

# Find and print prime numbers within the given range


primes_in_range = find_primes_in_range(start_range, end_range)
print(f"Prime numbers between {start_range} and {end_range}:")
print(primes_in_range)

if __name__ == "__main__":
main()
OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

16. Find the First n Fibonacci numbers:


def generate_fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence

n_fibonacci = int(input("Enter the value of n for Fibonacci sequence: "))


fibonacci_result = generate_fibonacci(n_fibonacci)
print(f"The first {n_fibonacci} Fibonacci numbers are: {fibonacci_result}")
OUTPUT

17. Find the maximum of a list of numbers:


numbers = [int(x) for x in input("Enter a list of numbers separated by space: ").split()]

max_number = max(numbers)

print(f"The maximum number is: {max_number}")

OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

18. Linear search and Binary search:


def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index if the target is found
return -1 # Return -1 if the target is not found

# Example usage:
arr = [1, 3, 5, 7, 9, 11, 13]
target = 7
result = linear_search(arr, target)

if result != -1:
print(f"Linear Search: Element {target} found at index {result}.")
else:
print(f"Linear Search: Element {target} not found.")

def binary_search(arr, target):


low, high = 0, len(arr) - 1

while low <= high:


mid = (low + high) // 2
mid_value = arr[mid]

if mid_value == target:
return mid # Return the index if the target is found
elif mid_value < target:
low = mid + 1
else:
high = mid - 1

return -1 # Return -1 if the target is not found

# Example usage:
sorted_arr = [1, 3, 5, 7, 9, 11, 13]
target = 7
result = binary_search(sorted_arr, target)

if result != -1:
print(f"Binary Search: Element {target} found at index {result}.")
else:
print(f"Binary Search: Element {target} not found.")
OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)
19. Write a function nearly equal to test whether two strings are nearly equal:
def nearly_equal(str1, str2):
return sum(c1 != c2 for c1, c2 in zip(str1, str2)) <= 1

string1 = input("Enter the first string: ")


string2 = input("Enter the second string: ")

if nearly_equal(string1, string2):
print("Strings are nearly equal.")
else:
print("Strings are not nearly equal.")
OUTPUT

20. Program that takes command line arguments (word count):


import sys

def word_count(text):
words = text.split()
return len(words)

if len(sys.argv) != 2:
print("Usage: python word_count.py <text>")
else:
input_text = sys.argv[1]
count = word_count(input_text)
print(f"Word count: {count}")
OUTPUT

21. Write a function to find all duplicates in the list:


def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)

input_list = [1, 2, 3, 2, 4, 5, 6, 4]
result_duplicates = find_duplicates(input_list)
print(f"Duplicates in the list: {result_duplicates}")
OUTPUT
SCRIPTING LANGUAGE USING (PYTHON)

22. Remove empty strings from the list of strings:


def remove_empty_strings(lst):
return list(filter(lambda x: x != "", lst))

input_strings = ["hello", "", "world", "", "python"]


result_filtered = remove_empty_strings(input_strings)
print(f"List after removing empty strings: {result_filtered}")
OUTPUT

23. Write a script to calculate the age in years, months, and days of a person:

from datetime import datetime

def calculate_age(birthdate):

# Get the current date

current_date = datetime.now()

# Calculate the difference between the birthdate and the current date

age = current_date - birthdate

# Calculate the number of years, months, and days

years = age.days // 365

remaining_days = age.days % 365

months = remaining_days // 30

days = remaining_days % 30

return years, months, days

def main():

# Input the birthdate in the format YYYY-MM-DD

birthdate_str = input("Enter your birthdate (YYYY-MM-DD): ")

# Convert the input string to a datetime object


SCRIPTING LANGUAGE USING (PYTHON)
birthdate = datetime.strptime(birthdate_str, "%Y-%m-%d")

# Calculate the age

years, months, days = calculate_age(birthdate)

# Display the result

print(f"Your age is {years} years, {months} months, and {days} days.")

if __name__ == "__main__":

main()

OUTPUT

24. Write a regular expression to search for digits inside a string:


import re

def search_digits(input_string):
digits = re.findall(r'\d', input_string)
return digits

input_text = input("Enter a string: ")


result_digits = search_digits(input_text)
print(f"Digits found: {result_digits}")
OUTPUT

You might also like