Shell Scripting Programs

Shell Scripting Programs

1) Write a shell script to ask your name, program name and enrollment number and print it on the screen.

Echo “Enter your name:”
Read Name
Echo “Enter your program name:”
Read Prog
Echo “Enter your enrollment number:”
Read Enroll
Clear
Echo “Details you entered”
Echo Name: $Name
Echo Program Name: $Prog
Echo Enrolment Number: $Enroll

2) Write a shell script to find the sum, the average and the product of the four integers entered

Echo “Enter four integers with space between”
Read a b c d
Sum =`expr $a + $b + $c + $d`
Avg =`expr $sum / 4`
Dec =`expr $sum % 4`
Dec =`expr \ ($dec \* 1000 \) / 4`
Product =`expr $a \* $b \* $c \* $d`
Echo Sum = $sum
Echo Average = $avg. $dec

Echo Product = $product

Python Interview Questions

                                              

How do you remove duplicates from a list?
a. sort the list
b. scan the list from the end.
c. while scanning from right-to-left, delete all the duplicate elements from the list
How do you check the file existence and their types in Python?
os.path.exists() – use this method to check for the existence of a file. It returns True if the file exists, false otherwise. Eg: import os; os.path.exists(‘/etc/hosts’)
os.path.isfile() – this method is used to check whether the give path references a file or not. It returns True if the path references to a file, else it returns false. Eg: import os; os.path.isfile(‘/etc/hosts’)
os.path.isdir() – this method is used to check whether the give path references a directory or not. It returns True if the path references to a directory, else it returns false. Eg: import os; os.path.isfile(‘/etc/hosts’)
os.path.getsize() – returns the size of the given file
os.path.getmtime() – returns the timestamp of the given path

Differentiate between append() and extend() methods. ?
Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of the list.
append(element) – adds the given element at the end of the list which has called this method.
extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.
Differentiate between .py and .pyc files?
Both .py and .pyc files holds the byte code. “.pyc” is a compiled version of Python file. This file is automatically generated by Python to improve performance. The .pyc file is having byte code which is platform independent and can be executed on any operating system that supports .pyc format.
Note: there is no difference in speed when program is read from .pyc or .py file; the only difference is the load time.
Explain different ways to trigger / raise exceptions in your python script ?
The following are the two possible ways by which you can trigger an exception in your Python script. They are:
1.       raise — it is used to manually raise an exception general-form:
raise exception-name (“message to be conveyed”)
Eg: >>> voting_age = 15
>>> if voting_age < 18: raise ValueError(“voting age should be atleast 18 and above”) output: ValueError: voting age should be atleast 18 and above 2. assert statement assert statements are used to tell your program to test that condition attached to assert keyword, and trigger an exception whenever the condition becomes false. Eg: >>> a = -10
>>> assert a > 0 #to raise an exception whenever a is a negative number output: AssertionError
Another way of raising and exception can be done by making a programming mistake, but that’s not
usually a good way of triggering an exception

Explain how can you access a module written in Python from C?
You can access a module written in Python from C by following method,
Module =  =PyImport_ImportModule(“<modulename>”);

Mention the use of the split function in Python?
The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
·          Script file’s mode must be executable and
·          the first line must begin with # ( #!/usr/local/bin/python)


What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.


Merging two sorted list
We have two sorted lists, and we want to write a function to merge the two lists into one sorted list:
a = [3, 4, 6, 10, 11, 18]
b = [1, 5, 7, 12, 13, 19, 21]


Here is our code:
a = [3, 4, 6, 10, 11, 18]
b = [1, 5, 7, 12, 13, 19, 21]
c = []

while a and b:
    if a[0] < b[0]:
        c.append(a.pop(0))
    else:
        c.append(b.pop(0))
       
# either a or b can be not empty
print c + a + b


The output:
[1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 18, 19, 21]


A little bit more compact version using list.extend():
a = [3, 4, 6, 10, 11, 18]
b = [1, 5, 7, 12, 13, 19, 21]

a.extend(b)
c = sorted(a)
print c


Note that the list.extend() is different from list.append():
[1, 3, 5, 7, 9, 11, [2, 4, 6]]  # a.append(b)
[1, 3, 5, 7, 9, 11, 2, 4, 6]    # a.extend(b)


What is a Class? How do you create it in Python?
A class is a blue print/ template of code /collection of objects that has same set of attributes and behaviour. To create a class use the keyword class followed by class name beginning with an uppercase letter. For example, a person belongs to class called Person class and can have the attributes (say first-name and last-name) and behaviours / methods (say showFullName()). A Person class can be defined as:
class Person():
#method
def inputName(self,fname,lname): self.fname=fname self.lastname=lastname
#method
def showFullName() (self):
print(self.fname+" "+self.lname)person1 = Person() #object instantiation person1.inputName("Ratan","Tata") #calling a method inputName person1. showFullName() #calling a method showFullName()
Note: whenever you define a method inside a class, the first argument to the method must be self (where self – is a pointer to the class instance). self must be passed as an argument to the method, though the method does not take any arguments.

What is JSON? How would convert JSON data into Python data?
JSON – stands for JavaScript Object Notation. It is a popular data format for storing data in NoSQL
databases. Generally JSON is built on 2 structures.
1.        A collection of <name, value> pairs.
2.        An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert json data into python using load() of json module.

 Explain how Python does Compile-time and Run-time code checking?
Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exists.