Rajendranath College of Polytechnic
Diploma In Computer Science & Technology
3rd Semester
Lab Manual
SCRIPTING LANGUAGE LAB
CST213
1
Scripting language Lab Manual
INDEX
Exp. No. List of Experiment Page No.
1. Running instructions in Interactive interpreter and a 4-5
Python Script
.
2. Write a script to purposefully raise Indentation Error 5-6
and Correct it
3. Write and execute scripts based on data types 6-7
.
4. Write a script to find Sum and average of first n natural 7
numbers
5. Given 2 strings, s1 and s2, create a new string by 7
appending s2 in the middle of s1.
6. Write a script to check whether a given string is 7-8
palindrome or not.
.
7. Write a program [Link] that takes 2 numbers as 8
command line arguments and prints its sum.
8. Write a script using a for loop that loops over a 8
sequence
9. Write a script to count the numbers of characters in the 8
string and store them in a dictionary.
10. Write a program to use split and join methods in the 9
string and trace a birthday
with a dictionary data structure.
11. Write a script that combines more than one lists into a 9
dictionary
12. Compute the GCD & LCM of two numbers 10
13. Check a number is prime or not 10-11
14. Find the square root of a number 11
.
2
Scripting language Lab Manual
15. Exponentiation (power of a number) 11
16 Find all primes within a given range 11-12
17 Find First n Fibonacci numbers 12
18 Find the maximum of a list of numbers 12-13
19 Linear search and Binary search 13-14
20 Write a program to compute the number of characters, 14
words and lines in a file.
21 Write a script to Calculate age in year month days of a 14-15
person taking his/her date of birth as input and
accessing current system date.
22 Write a regular expression to search digit inside a 15
string.
3
Scripting language Lab Manual
Running instructions in Interactive interpreter and a Python Script
Running Python instructions in an interactive interpreter and executing a Python script are two common
ways to run Python code. Here's an explanation of both:
### Interactive Interpreter:
1. **Open the Interpreter:**
- Open your terminal or command prompt.
- Type `python` or `python3` (depending on your Python version) and press Enter.
2. **Interactive Mode:**
- You will enter the Python interactive mode, indicated by the `>>>` prompt.
- You can type and execute Python instructions directly.
```python
>>> print("Hello, World!")
Hello, World!
```
- You can also define variables and perform calculations interactively.
```python
>>> x = 5
>>> y = 10
>>> z = x + y
>>> z
15
```
3. **Exit Interactive Mode:**
- To exit the interactive mode, type `exit()` or press `Ctrl + D`.
### Python Script:
1. **Create a Python Script:**
- Open a text editor (e.g., VSCode, Atom, Sublime Text).
- Write your Python code and save it with a `.py` extension. For example, `[Link]`.
```python
# [Link]
print("Hello, World!")
x=5
y = 10
z=x+y
print(z)
```
2. **Run the Script:**
- Open your terminal or command prompt.
- Navigate to the directory containing your script using the `cd` command.
```bash
cd path/to/your/script
```
- Run the script using the `python` or `python3` command.
```bash
python [Link]
```
- The output will be displayed in the terminal.
```
Hello, World!
15
```
These are the basic steps for running Python code interactively in an interpreter or as a script.
Interactive mode is useful for testing small pieces of code, while scripts are better for larger programs or
when you want to save and share your code.
Write a script to purposefully raise Indentation Error and Correct it
Certainly! I'll provide you with a Python script that intentionally raises an `IndentationError` and then a
corrected version of the script.
**Intentionally Indentation Error Script:**
```python
# IndentationError script
def example_function():
print("This line has incorrect indentation.")
print("This line also has incorrect indentation.")
# Call the function
example_function()
```
This script will raise an `IndentationError` because the lines inside the `example_function` lack the
proper indentation.
**Corrected Version:**
```python
# Corrected script
def example_function():
print("This line is correctly indented.")
print("This line is also correctly indented.")
# Call the function
example_function()
```
In the corrected version, the lines inside `example_function` are indented with four spaces (or a tab,
depending on your coding style). This adheres to Python's syntax rules.
To run these scripts, save each version in a separate file (e.g., `indentation_error_script.py` and
`corrected_script.py`). Open your terminal or command prompt, navigate to the directory containing the
scripts, and run them using the `python` command:
```bash
python indentation_error_script.py
python corrected_script.py
The first script will raise an `IndentationError`, and the corrected script will run without errors,
demonstrating the importance of proper indentation in Python.
Write and execute scripts based on data types
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
[Link] a script to find Sum and average of first n natural numbers.
Ans.
n = int(input("Enter number"))
sum = 0
for num in range(1, n + 1, 1):
sum = sum + num
print("Sum of first ", n, "numbers is: ", sum)
average = sum / n
print("Average of ", n, "numbers is: ", average)
2. Given 2 strings, s1 and s2, create a new string by appending s2 in the middle of s1.
Ans.
def append_middle(s1, s2):
print("Original Strings are", s1, s2)
# middle index number of s1
mi = int(len(s1) / 2)
# get character from 0 to the middle index number from s1
x = s1[:mi:]
# concatenate s2 to it
x = x + s2
# append remaining character from s1
x = x + s1[mi:]
print("After appending new string in middle:", x)
append_middle("Ault", "Kelly")
3. Write a script to check whether a given string is palindrome or not.
# function which return reverse of a string
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
4. Write a program [Link] that takes 2 numbers as command line arguments and prints its sum.
Ans.
import sys
x=int([Link][1])
y=int([Link][2])
sum=x+y
print("The addition is :",sum)
5. Write a script using a for loop that loops over a sequence
Ans.
li = ["Geeks", "for", "Geeks"]
for i in li:
print(i)
print('-----')
for i in range(len(li)):
print(li[i])
6. Write a script to count the numbers of characters in the string and store them in a dictionary.
Ans.
str=input("Enter a String:")
dict = {}
for n in str:
keys = [Link]()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)
7. Write a program to use split and join methods in the string and trace a birthday
with a dictionary data structure.
Ans.
# Create a dictionary of birthdays
birthdays = {
"Alice": "April 1st",
"Bob": "December 25th",
"Carol": "March 8th",
}
# Get the name of the person whose birthday we want to trace
name = input("Whose birthday do you want to trace? ")
# Split the name into first and last name
first_name, last_name = [Link](" ")
# Get the birthday from the dictionary
birthday = birthdays[first_name]
# Split the birthday into month and day
month, day = [Link](" ")
# Trace the birthday
print(f"{first_name}'s birthday is on {month} {day}")
8. Write a script that combines more than one lists into a dictionary
Ans.
def combine_lists_into_dictionary(lists):
dictionary = {}
for list in lists:
for element in list:
dictionary[element] = list
return dictionary
lists = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
dictionary = combine_lists_into_dictionary(lists)
print(dictionary)
9. Compute the GCD & LCM of two numbers.
import sys
# Function to return
# LCM of two numbers
def findLCM(a, b):
lar = max(a, b)
small = min(a, b)
i = lar
while(1) :
if (i % small == 0):
return i
i += lar
# Driver Code
a=5
b=7
print("LCM of " , a , " and ", b , " is " , findLCM(a, b), sep = "")
Recursive function to return gcd of a and b
def gcd(a,b):
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
# base case
if (a == b): return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)
# Driver program to test above function
a = 98
b = 56
if(gcd(a, b)):
print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
print('not found')
[Link] a number is prime or not
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, int(num/2)+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")
11. Find the square root of a number
num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
12. Exponentiation (power of a number)
base = 3
exponent = 4
result = 1
for exponent in range(exponent, 0, -1):
result *= base
print("Answer = " + str(result))
13. Find all primes within a given range
a = int(input(“Enter start value : “))
b = int(input(“Enter end value : “))
print(“Prime numbers between”,a,”and”,b,”are :”)
while (a < b):
flag = 0;
for i in range(2, int(a/2),1):
if(a % i == 0):
flag = 1;
break
if (flag == 0):
print(a, end = ” “)
a=a+1
14. Find First n Fibonacci numbers.
def fibonacci_numbers(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
# printing fibonacci numbers
return fibonacci_numbers(num-2)+fibonacci_numbers(num-1)
n=7
for i in range(0, n):
print(fibonacci_numbers(i), end=" ")
15. Find the maximum of a list of numbers
list1 = []
num = int(input("Enter number of elements in list: "))
# Iterating till num to append elements in list
for i in range(1, num + 1):
ele = int(input("Enter elements: ")
[Link](ele)
# Printing maximum element
print("Largest element is:", max(list1))
16. Linear search and Binary search
def linearSearch(array, n, x):
for i in range(0, n):
if (array[i] == x):
return i
return -1
array = [24, 41, 31, 11, 9]
x = 11
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element is Present at Index: ", result)
def binarySearch(array, x, low, high):
while low <= high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [2, 4, 5, 17, 14, 7, 11, 22]
x = 22
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print(str(result))
else:
print("Not found")
17. Write a program to compute the number of characters, words and lines in a file.
number_of_words = 0
number_of_lines = 0
number_of_characters = 0
with open("[Link]", 'r') as file:
for l in file:
number_of_words += len([Link]())
number_of_lines += 1
number_of_characters = len(l)
print("No of words: ", number_of_words)
print("No of lines: ", number_of_lines)
print("No of characters: ", number_of_characters)
18. Write a script to Calculate age in year month days of a person taking his/her date of birth as input
and accessing current system date.
from datetime import date
def age(birthdate):
today = [Link]()
age = [Link] - [Link] - (([Link], [Link]) < ([Link],
[Link]))
return age.
19. Write a regular expression to search digit inside a string.
import re
# Sample string
sample_string = "There are 123 apples and 456 oranges in the basket."
# Regular expression to find digits
digit_pattern = [Link](r'\d+')
# Search for digits in the string
matches = digit_pattern.findall(sample_string)
# Print the matches
print("Digits found:", matches)
output: Digits found: ['123', '456']