0% found this document useful (0 votes)
809 views16 pages

Unit 3 Important Q&a

The document provides answers to various questions related to Python. It discusses the rules for Python variable names, advantages of Python like being easy to code, free and open source, portable etc. It provides examples of range function, reading and writing CSV files. It also discusses random module and provides short notes on data types in Python with examples of int, float, string, list, tuples and dictionaries. Finally, it explains exception handling in Python with an example and discusses Python functions and modules with examples of defining, calling and using arguments in functions.

Uploaded by

harini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
809 views16 pages

Unit 3 Important Q&a

The document provides answers to various questions related to Python. It discusses the rules for Python variable names, advantages of Python like being easy to code, free and open source, portable etc. It provides examples of range function, reading and writing CSV files. It also discusses random module and provides short notes on data types in Python with examples of int, float, string, list, tuples and dictionaries. Finally, it explains exception handling in Python with an example and discusses Python functions and modules with examples of defining, calling and using arguments in functions.

Uploaded by

harini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT 3

SHORT ANSWERS:

1. Mention the Rules for Python variables names?

Ans: 1. A variable name must start with a letter or the underscore character

2. A variable name cannot start with a number

3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)

4. Variable names are case-sensitive (age, Age and AGE are three different variables)

Example:Legal variable names:

• myvar = "John"
my_var = "John"

Illegal variable names:

• 2myvar = "John“ # started with number


my-var = "John“ # - it is minus not underscore

2. Mention the advantages of Python?

Ans: i) Easy to code:


Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in python
language and anybody can learn python basics in a few hours or days. It is also a developer-
friendly language.

ii) Free and Open Source:

• Python language is freely available at the official website.

• Since it is open-source, this means that source code is also available to the public.

• iii) Python is Portable language:


Python language is also a portable language. For example, if we have python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and
Mac then we do not need to change it, we can run this code on any platform .
3. Write a Short note on range function with suitable example?

Ans: range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments


by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
  print(x)

output

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

4. Write a Short note on CSV files?

Reading and Writing CSV Files in Python

CSV (Comma Separated Values) format is the most common import and export format for
spreadsheets and databases. It is one of the most common methods for exchanging data between
applications and popular data format used in Data Science.

EXECUTED CODE

for reading csv file

with open('mycsv.csv','r',newline='') as f:
thereader=csv.reader(f)
for line in thereader:
print(line)

OUTPUT
for writing csv file

import csv

with open('mycsv.csv','w',newline='') as f:
thewriter=csv.writer(f)
thewriter.writerow(['col1','col2','col3'])
for i in range(1,100):
thewriter.writerow(['one','two','three'])
OUTPUT

5. Write short notes on Random Module?

Ans: Random Number

• Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:

Example

• Import the random module, and display a random number between 1 and 9:

• import random
print(random.randrange(1, 10))

output:

LONG ANSWERS:
1. Explain the different Data types of python with suitable examples?

Ans: Python Data Types:

• Variables can store data of different types.

• Python has the following data types built-in by default, in these categories:

1.Getting the Data Type

To get the data type of any object, use  type() function:

Example

Python Numbers

There are three numeric types in Python:

1.Int 2.float 3.complex

Variables of numeric types are created when you assign a value to them:

1.Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited


length.

Example

Integers:

x = 1
y = 35656222554887711
z = -3255522

2.Float

Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Example
o x = 1.10
y = 1.0
z = -35.59

3.Complex

Complex numbers are written with a "j" as the imaginary part:

Example

x = 3+5j
y = 5j
z = -5j

Strings

Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')

Lists:
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
• List items need not all have same type
• Lists are created using square brackets[]
Example
• Creating List, finding the type & Length

Tuples
• A tuple is a sequence data type that is similar to lists.
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable. Also called as read only list.
• Tuples are written with round brackets.i.e.,parathesis
Example
1. Create a Tuple:

Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values: Example

Create and print a dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
Output

2. Explain Exception handling in Python with suitable example?


Exception Handling in Python
Python provides very important feature to handle any unexpected error in your Python programs
and to add debugging capabilities in them.

What is Exception?

An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.

When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.

Handling an exception

If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem as elegantly as possible.

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Example

The try block will generate an exception, because x is not defined:

try:
  print(x)
except:
  print("An exception occurred")

Example

a = [1, 2, 3]
try: 
    print "Second element = %d" %(a[1])
  
    # Throws error since there are only 3 elements in array
    print "Fourth element = %d" %(a[3]) 
  
except IndexError:
    print "An error occurred"
output

Second element = 2
An error occurred

The try-finally Clause

You can use a finally: block along with a try: block. The finally: block is a place to put any
code that must execute, whether the try-block raised an exception or not. The syntax of the try-
finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Note − You can provide except clause(s), or a finally clause, but not both. You cannot
use else clause as well along with a finally clause.

Example:

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
If you do not have permission to open the file in writing mode, then this will produce the
following result −
Error: can't find file or read data

3. Explain about Python functions & Modules with suitable examples?


Ans: Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.


Creating a Function

In Python a function is defined using the def keyword:


Example

def my_function():
  print("Hello from a function")
Calling a Function

To call a function, use the function name followed by parenthesis:


Example

def my_function():
  print("Hello from a function")

my_function()

output

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
Example

The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:

def my_function(fname):
  print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")

output

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed
into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")

output

If you try to call the function with 1 or 3 arguments, you will get an error
Python Modules
What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example

Save this code in a file named mymodule.py

def greeting(name):
  print("Hello, " + name)
Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Output:
4. Explain in detail about File handling in Python?

Ans: File Handling in Python

Files

Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the computer is
turned off), we use files for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
 Open a file
 Read or write (perform operation)
 Close the file
Opening Files in Python

Python has a built-in open() function to open a file. This function returns a file object, also called
a handle, as it is used to read or modify the file accordingly.

We can specify the mode while opening a file. In mode, we specify whether we want to read r,
write w or append a to the file. We can also specify if we want to open the file in text mode or
binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like images or executable files.
Mode Description
r Opens a file for reading. (default)
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it
exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
a Opens a file for appending at the end of the file without truncating it. Creates a new file if
it does not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (reading and writing)
Writing to Files in Python
In order to write into a file in Python, we need to open it in write w, append a or exclusive
creation x mode.
We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due
to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. This
method returns the number of characters written to the file.
This program will create a new file named test.txt in the current directory if it does not exist. If it
does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.
Reading Files in Python
To read a file in Python, we must open the file in reading r mode.
There are various methods available for this purpose. We can use the read(size) method to read
in the size number of data. If the size parameter is not specified, it reads and returns up to the end
of the file.
We can read the text.txt file we wrote in the above section in the following way:
We can see that the read() method returns a newline as '\n'. Once the end of the file is reached,
we get an empty string on further reading.

Executed code for reading or writing


fw = open('sample.txt','w')
fw.write('writing some stuff in my text file\n')
fw.write('i like python programming\n')
fw.close()

fr=open('sample.txt','r')
text = fr.read()
print(text)
fr.close()

OUTPUT
writing a file output
writing some stuff in my text file
i like python programming
Reading a file output
5. Explain Date & Time Operations in Python with suitable examples?

A Python program can handle date and time in several ways. Converting between date formats is a
common chore for computers. Python's time and calendar modules help track dates and times.

What is Tick?

Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in
seconds since 12:00am, January 1, 1970(epoch).

There is a popular time module available in Python which provides functions for working with times, and
for converting between representations. The function time.time() returns the current system time in
ticks since 12:00am, January 1, 1970(epoch).

Example:

OUTPUT:

What is TimeTuple?
Example:

OUTPUT:

Getting current time

To translate a time instant from seconds since the epoch floating-point value into a
timetuple, pass the floating-point value to a function (e.g., localtime) that returns a time-
tuple with all valid nine items.
EXAMPLE

OUTPUT:

Getting formatted time

You can format any time as per your requirement, but a simple method to get time in a readable
format is asctime() −
EXAMPLE:

OUTPUT:

You might also like