Future Vision BIE Future Vision BIE


ONE STOP FOR ALL STUDY MATERIALS & LAB PROGRAMS


E MENU Whatsapp Share Join Telegram, to get Instant Updates
×

NOTE!

Click on MENU to Browse between Subjects...

Advertisement

17CS664 - PYTHON APPLICATION PROGRAMMING

Answer Script for Module 1

Solved Previous Year Question Paper

CBCS SCHEME


PYTHON APPLICATION PROGRAMMING

[As per Choice Based Credit System (CBCS) scheme]

(Effective from the academic year 2017 - 2018)

SEMESTER - VI

Subject Code 17CS664

IA Marks 40

Number of Lecture Hours/Week 3

Exam Marks 60




Advertisement

These Questions are being framed for helping the students in the "FINAL Exams" Only (Remember for Internals the Question Paper is set by your respective teachers). Questions may be repeated, just to show students how VTU can frame Questions.

- ADMIN




× CLICK ON THE QUESTIONS TO VIEW ANSWER

ANSWER :

6.1 FILES

File handling is an important requirement of any programming language, as it allows us to store the data permanently on the secondary storage and read the data from a permanent source. Here, we will discuss how to perform various operations on files using the programming language Python.

6.1.1 Persistence

The programs that we have considered till now are based on console I/O. That is, the input was taken from the keyboard and output was displayed onto the monitor. When the data to be read from the keyboard is very large, console input becomes a laborious job. Also, the output or result of the program has to be used for some other purpose later, it has to be stored permanently. Hence, reading/writing from/to files are very essential requirement of programming.

We know that the programs stored in the hard disk are brought into main memory to execute them. These programs generally communicate with CPU using conditional execution, iteration, functions etc. But, the content of main memory will be erased when we turn-off our computer. We have discussed these concepts in Module1 with the help of Figure 1.1. Here we will discuss about working with secondary memory or files. The files stored on the secondary memory are permanent and can be transferred to other machines using pen-drives/CD.

6.1.2 Opening Files

To perform any operation on a file, one must open a file. File opening involves communication with operating system. In Python, a file can be opened using a built-in function

open()

. While opening a file, we must specify the name of the file to be opened. Also, we must inform the OS about the purpose of opening a file, which is termed asfile opening mode. The syntax of

open()

function is as below -

fhand= open("filename", "mode")

Here,

filename

is name of the file to be opened. This string may be just a name of the file, or it may include pathname also. Pathname of the file is optional when the file is stored in current working directory

mode

This string indicates the purpose of opening a file. It takes a pre-defined set of values as given in Table 2.1

fhand

It is a reference to an object of

file

class, which acts as a handler or tool for all further operations on files.

When our Python program makes a request to open a specific file in a particular mode, then OS will try to serve the request. When a file gets opened successfully, then a file object is returned. This is known as file handle and is as shown in Figure 6.1. It will help to perform various operations on a file through our program. If the file cannot be opened due to some reason, then error message (traceback) will be displayed.

Fig 6.1 A File Handle

Fig 6.1 A File Handle

A file opening may cause an error due to some of the reasons as listed below -

i. File may not exist in the specified path (when we try to read a file)

ii. File may exist, but we may not have a permission to read/write a file

iii. File might have got corrupted and may not be in an opening state

Since, there is no guarantee about getting a file handle from OS when we try to open a file, it is always better to write the code for file opening using try-except block. This will help us to manage error situation.

Mode

Meaning

r

Opens a file for reading purpose. If the specified file does not exist in the specified path, or if you don't have permission, error message will be displayed. This is the default mode of open() function in Python.

w

Opens a file for writing purpose. If the file does not exist, then a new file with the given name will be created and opened for writing. If the file already exists, then its content will be over-written.

a

Opens a file for appending the data. If the file exists, the new content will be appended at the end of existing content. If no such file exists, it will be created and new content will be written into it.

r+

Opens a file for reading and writing.

w+

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

rb

Opens a file for reading only in binary format

wb

Opens a file for writing only in binary format

ab

Opens a file for appending only in binary format

program files

output

6.1.3

Text Files and Lines

A text file is a file containing a sequence of lines. It contains only the plain text without any images, tables etc. Different lines of a text file are separated by a newline character \n. In the text files, this newline character may be invisible, but helps in identifying every line in the file. There will be one more special entry at the end to indicate end of file (EOF).

NOTE:

There is one more type of file called binary file, which contains the data in the form of

bits. These files are capable of storing text, image, video, audio etc. All these data will be stored in the form of a group of bytes whose formatting will be known. The supporting program can interpret these files properly, whereas when opened using normal text editor, they look like messy, unreadable set of characters.

6.1.4 Reading Files

When we successfully open a file to read the data from it, the

open()

function returns the file handle (or an object reference to file object) which will be pointing to the first character in the file. A text file containing lines can be iterated using a for-loop starting from the beginning with the help of this file handle. Consider the following example of counting number of lines in a file.

NOTE:

Before executing the below given program, create a text file (using Notepad or

similar editor) myfile.txt in the current working directory (The directory where you are going store your Python program). Open this text file and add few random lines to it and then close. Now, open a Python script file, say countLines.py and save it in the same directory as that of your text file myfile.txt. Then, type the following code in Python script countLines.py and execute the program. (You can store text file and Python script file in different directories. But, if you do so, you have to mention complete path of text file in the open() function.)

Sample Text file myfile.txt:

hello how are you?

I am doing fine

what about you?

Python script file countLines.py

Python script file

Output:

Line Number 1 : hello how are you?

Line Number 2 : I am doing fine

In the above program, initially, we will try to open the file 'myfile.txt. As we have already created that file, the file handler will be returned and the object reference to this file will be stored in fhand. Then, in the for-loop, we are using fhand as if it is a sequence of lines. For each line in the file, we are counting it and printing the line. In fact, a line is identified internally with the help of new-line character present at the end of each line. Though we have not typed \n anywhere in the file myfile.txt, after each line, we would have pressed enter-key. This act will insert a \n, which is invisible when we view the file through notepad. Once all lines are over, fhand will reach end-of-file and hence terminates the loop. Note that, when end of file is reached (that is, no more characters are present in the file), then an attempt to read will return None or empty character '' (two quotes without space in between).

Once the operations on a file is completed, it is a practice to close the file using a function close(). Closing of a file ensures that no unwanted operations are done on a file handler. Moreover, when a file was opened for writing or appending, closure of a file ensures that the last bit of data has been uploaded properly into a file and the end -of-file is maintained properly. If the file handler variable (in the above example, fhand ) is used to assign some other file object (using open() function), then Python closes the previous file automatically.

If you run the above program and check the output, there will be a gap of two lines between each of the output lines. This is because, the new-line character \n is also a part of the variable line in the loop, and the print() function has default behavior of adding a line at the end (due to default setting of end parameter of print()). To avoid this double-line spacing, we can remove the new-line character attached at the end of variable line by using built-in string function rstrip() as below -

print("Line Number ",count, ":", line.rstrip())

It is obvious from the logic of above program that from a file, each line is read one at a time, processed and discarded. Hence, there will not be a shortage of main memory even though we are reading a very large file. But, when we are sure that the size of our file is quite small, then we can use

read()

function to read the file contents. This function will read entire file content as a single string. Then, required operations can be done on this string using built-in

string functions. Consider the below given example - fhand=open('myfile.txt')

s=fhand.read()

print("Total number of characters:",len(s))

print("String up to 20 characters:", s[:20])

After executing above program using previously created file myfile.txt, then the output would be -

Total number of characters:50

String up to 20 characters: hello how are you?

I

6.1.5 Writing Files

To write a data into a file, we need to use the mode

w

in open() function.

>>> fhand=open("mynewfile.txt","w")

>>> print(fhand)

<_io.TextIOWrapper name='mynewfile.txt' mode='w' encoding='cp1252'>

If the file specified already exists, then the old contents will be erased and it will be ready to write new data into it. If the file does not exists, then a new file with the given name will be created.

The

write()

method is used to write data into a file. This method returns number of characters successfully written into a file. For example,

>>> s="hello how are you?"

>>> fhand.write(s)

18

Now, the file object keeps track of its position in a file. Hence, if we write one more line into the file, it will be added at the end of previous line. Here is a complete program to write few lines into a file -

written into a file

The above program will ask the user to enter 5 lines in a loop. After every line has been entered, it will be written into a file. Note that, as

write()

method doesn't add a new-line character by its own, we need to write it explicitly at the end of every line. Once the loop gets over, the program terminates. Now, we need to check the file f1.txt on the disk (in the same directory where the above Python code is stored) to find our input lines that have been written into it.



Advertisement

ANSWER :

7.1 Finite looping

Finite loop is a for or while loop while will execute for a said number of times. They it Comes out of loop. Usually having a condition inside the body of the loop which becomes False while executing, which is called as a exit condition.

7.2 Infinite looping:

A loop may execute infinite number of times when the condition is never going to become false. For example,

7.2 Infinite looping

Here, the condition specified for the loop is the constant True, which will never get terminated. Sometimes, the condition is given such a way that it will never become false and hence by restricting the program control to go out of the loop. This situation may happen either due to wrong condition or due to not updating the counter variable.

7.3 break & continue:

Refer 1st & 4th Question & Answer or Click Here


ANSWER :

Loading Image

Loading Image



Advertisement

ANSWER :

A segment or a portion of a string is called as slice. Only a required number of characters can be extracted from a string using colon (:) symbol. The basic syntax for slicing a string would be -

st[i:j:k]

This will extract character from ith character of st till (j-1) th character in steps of k. If first index i is not present, it means that slice should start from the beginning of the string. If the second index j is not mentioned, it indicates the slice should be till the end of the string. The third parameter k, also known as

stride

, is used to indicate number of steps to be incremented after extracting first character. The default value of stride is 1.

Consider following examples along with their outputs to understand string slicing.

st="Hello World"

#refer this string for all examples

1.

print("st[:] is", st[:])

#output Hello World

As both index values are not given, it assumed to be a full string.

2.

print("st[0:5] is ", st[0:5]) #output is Hello

Starting from 0th index to 4th index (5 is exclusive), characters will be printed.

3.

print("st[0:5:1] is", st[0:5:1])

#output is Hello

This code also prints characters from 0th to 4th index in the steps of 1. Comparing this example with previous example, we can make out that when the stride value is 1, it is optional to mention.

4.

print("st[3:8] is ", st[3:8]) #output is lo Wo

Starting from 3rd index to 7th index (8 is exclusive), characters will be printed.

5

.

print("st[7:] is ", st[7:])

#output is orld

Starting from 7th index to till the end of string, characters will be printed.

6.

print(st[::2])

#outputs HloWrd

This example uses stride value as 2. So, starting from first character, every alternative character (char+2) will be printed.

7.

print("st[4:4] is ", st[4:4]) #gives empty string

Here, st[4:4] indicates, slicing should start from 4th character and end with (4-1)=3rd character, which is not possible. Hence the output would be an empty string.

8.

print(st[3:8:2])

#output is

l o

Starting from 3rd character, till 7th character, every alternative index is considered.

9.

print(st[1:8:3])

#output is

eoo

Starting from index 1, till 7th index, every 3rd character is extracted here.

10. print(st[-4:-1]) #output is orl

Refer the diagram of negative indexing given earlier. Excluding the -1st character, all characters at the indices -4, -3 and -2 will be displayed. Observe the role of stride with default value 1 here. That is, it is computed as -4+1 =-3, -3+1=-2 etc.

11. print(st[-1:]) #output is d

Here, starting index is -1, ending index is not mentioned (means, it takes the index 10) and the stride is default value 1. So, we are trying to print characters from -1 (which is the last character of negative indexing) till 10th character (which is also the last character in positive indexing) in incremental order of 1. Hence, we will get only last character as output.

12. print(st[:-1]) #output is Hello Worl

Here, starting index is default value 0 and ending is -1 (corresponds to last character in negative indexing). But, in slicing, as last index is excluded always, -1st character is omitted and considered only up to -2nd character.

13. print(st[::]) #outputs Hello World

Here, two colons have used as if stride will be present. But, as we haven't mentioned stride its default value 1 is assumed. Hence this will be a full string.

14.

print(st[::-1])

#outputs dlroW olleH

This example shows the power of slicing in Python. Just with proper slicing, we could able to

reverse the string

. Here, the meaning is a full string to be extracted in the order of -1. Hence, the string is printed in the reverse order.

15.

print(st[::-2])

#output is drWolH

Here, the string is printed in the reverse order in steps of -2. That is, every Iternative character in the reverse order is printed. Compare this with example (6) given above.

By the above set of examples, one can understand the power of string slicing and of Python script. The slicing is a powerful tool of Python which makes many task simple pertaining to data types like strings, Lists, Tuple, Dictionary etc. (Other types will be discussed in later Modules)


ANSWER :

Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with count as 1. If the word is already present in the dictionary we increment its count by 1.

Example #1:


First we create a text file of which we want to count the words. Let this file be

sample.txt

with the following contents:

Mango banana apple pear

Banana grapes strawberry

Apple pear mango banana

Kiwi apple mango strawberry

Note:

Make sure the text file is in same directory as the Python file.

Loading Image

Loading Image


× NOTE: Each Page Provides only 5 Questions & Answer
Below Page NAVIGATION Links are Provided...
All the Questions on Question Bank Is SOLVED

Advertisement

lIKE OUR CONTENT SUPPORT US BY FOLLOWING US ON INSTAGRAM : @futurevisionbie

For immediate Notification Join the Telegram Channel



× SUGGESTION: SHARE WITH ALL THE STUDENTS AND FRIENDS -ADMIN