0% found this document useful (0 votes)
17 views24 pages

Intro To Python 2 - Answer Key

The document provides an answer key for the Sixth Semester B.Tech Degree Examination in Python, covering various topics such as conditional statements, type conversion, file handling, and exception handling. It includes sample code snippets and explanations for each topic, as well as programming exercises related to matrices and functions. Additionally, it discusses the popularity of Python and the precedence of operators.

Uploaded by

Shijin Knox
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)
17 views24 pages

Intro To Python 2 - Answer Key

The document provides an answer key for the Sixth Semester B.Tech Degree Examination in Python, covering various topics such as conditional statements, type conversion, file handling, and exception handling. It includes sample code snippets and explanations for each topic, as well as programming exercises related to matrices and functions. Additionally, it discusses the popularity of Python and the precedence of operators.

Uploaded by

Shijin Knox
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

Sixth Semester B.

Tech Degree Examination


(2018 Scheme)
18.605 Introduction to Python (T)
Answer Key
Time : 3 Hours Max. Marks : 100
PART – A
Answer all questions. Each carries 2 marks
1.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
2. The % symbol in Python is called the Modulo Operator. It returns the remainder of
dividing the left hand operand by right hand operand. It's used to get the remainder of a
division problem.

Eg : 7 % 2 = 1

3 Type Conversion
Type Conversion, just as the name suggests, is the process
of converting the type of objects from one data type into
another as per requirement.

Python supports various built-in type conversion functions


such as int(), long(), float(), str() etc,.

This type of conversion is also called as Explicit Type


Conversion or Type Casting.
float x;

Type Coercion

The automatic type conversion from one data type to


another is called as Type Coercion. This is also called as
Implicit Type Conversion.

The major difference between Type Conversion and Type


Coercion is that, type conversion is done manually using
built-in functions where as type coercion is done
automatically.
4.
nested conditional is where one conditional is nested within another conditional. The if,
elif and else statements in nested conditional have varying depths.
Example of nested conditional

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

if num==0:

print(num, "is zero")

else:

if num<0:

print(num, "is negative")

elif num>0:

print(num, "is positive")

5. for i in range(1, 101):


if((i%3==0) & (i%5!=0)):
print(i)
6. data = [34, 78, 3, [54, 43, 19, 30], 564]
i) data[2] = 90
ii) print(data[3][2])
7. Creating Python Dictionary

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

Accessing Elements from Dictionary


# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

Changing and Adding Dictionary elements


# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

Removing elements from Dictionary


# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print([Link](4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print([Link]())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items


[Link]()

8. The self variable is used to represent the instance of the class which is often
used in object-oriented programming. It works as a reference to the object.
Python uses the self parameter to refer to instance attributes and methods of
the class.

def __init__(self, Alex):

[Link] = Alex #name created in constructor

def get_student_name(self):

return [Link]

9.

Mode Description

r Opens a file for reading. (default)

Opens a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.

x Opens a file for exclusive creation. If the file already exists, the operation fails.

Opens a file for appending at the end of the file without truncating it. Creates a new
a
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)

10. In Python, exceptions can be handled using a try statement.


The critical operation which can raise an exception is placed inside
the try clause. The code that handles the exceptions is written in
the except clause.
We can thus choose what operations to perform once we have caught the
exception. Here is a simple example.

# import module sys to get the type of exception


import sys

randomList = ['a', 0, 2]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

PART – B
Answer one full question from each module. Each question carries 20 marks
Module 1
11. a) Type of condition statement in Python:
 If statement.
 If Else statement.
 Elif statement.
 Nested if statement.
 Nested if else statement.
 Chained conditionals
If statement

If statement is most usually used as a conditional statement.

Syntax

1. if(condition):
2. {
3. #if statement
4. }
f else statement

If else is a conditional statement. The statement itself says that if a given


condition is true or false. True means executing the “if” statement to the output.
False means executing the “else” statement to the output.

Syntax

1. if(condition):
2. {
3. # if statement
4. }
5. else:
6. {
7. # else statement
8. }
Elif statement

Elif is a shortcut of else if condition statements. In Python one or more conditions


are used in the elif statement.

Syntax

1. if(condition):
2. {
3. # if statement
4. }
5. elif(condition):
6. {
7. # elif statement
8. }
9. else:
10. {
11. # else statement
12. }
Nested if statement

In python is using "if" statements inside other if statements it is called nested if


statement.

Syntax

1. if(condition):
2. {
3. if(condition):
4. {
5. # if statement
6. }
7. }
Nested if else statement

In Python is using one “if else” statement inside other if else statements it is
called nested if else statement.

Syntax

1. if(condition):
2. {
3. if(condition):
4. {
5. #if statement
6. }
7. else:
8. {
9. #else statement
10. }
11. }
12. else:
13. {
14. #else statement
15. }

Chained conditionals
Python provides an alternative way to write nested selection such as the one shown in the
previous section. This is sometimes referred to as a chained conditional.

if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x and y must be equal")

b) inp=int(input("Enter any number"))


num=inp%10
# define a flag variable
flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

12. a)
 Why is Python so Popular?
o 1) Easy to Learn and Use
o 2) Mature and Supportive Python Community
o 3) Support from Renowned Corporate Sponsors
o 4) Hundreds of Python Libraries and Frameworks
o 5) Versatility, Efficiency, Reliability, and Speed
o 6) Big data, Machine Learning and Cloud Computing
o 7) First-choice Language
o 8) The Flexibility of Python Language
o 9) Use of python in academics
o 10) Automation

Formal and Natural Languages


Natural languages are the languages people speak, such as English,
Spanish, and French. They were not designed by people (although people
try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific
applications. For example, the notation that mathematicians use is a formal
language that is particularly good at denoting relationships among
numbers and symbols. Chemists use a formal language to represent the
chemical structure of molecules. And most importantly:
Programming languages are formal languages that
have been designed to express computations.

Precedence and Associativity of


b)

Operators in Python
To evaluate expressions there is a rule of precedence in Python. It guides
the order in which these operations are carried out.

he operator precedence in Python is listed in the following table. It is in


descending order (upper group has higher precedence than the lower
ones).

Operators Meaning

() Parentheses

** Exponent
+x , -x , ~x Unary plus, Unary minus, Bitwise NOT

* , / , // , % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<< , >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== , != , > , >= , < , <= , is , is not , in , not


Comparisons, Identity, Membership operators
in

not Logical NOT

and Logical AND

or Logical OR

Associativity of Python Operators

We can see in the above table that more than one operator exists in the same group.
These operators have the same precedence.

When two operators have the same precedence, associativity helps to determine the
order of operations.

Associativity is the order in which an expression is evaluated that has multiple


operators of the same precedence. Almost all the operators have left-to-right
associativity.

For example, multiplication and floor division have the same precedence. Hence, if
both of them are present in an expression, the left one is evaluated first.

# Left-right associativity
# Output: 3
print(5 * 2 // 3)

# Shows left-right associativity


# Output: 0
print(5 * (2 // 3))

Output

3
0

Module 2

13. a) # Program to multiply two matrices


A=[]
n=int(input("Enter N for N x N matrix: "))
print("Enter the element ::>")
for i in range(n):
row=[] #temporary list to store the row
for j in range(n):
[Link](int(input())) #add the input to row list
[Link](row) #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print() #new line
B=[]
n=int(input("Enter N for N x N matrix : ")) #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range (n):
row=[] #temporary list to store the row
for j in range(n):
[Link](int(input())) #add the input to row list
[Link](row) #add the row to the list
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("The Resultant Matrix Is ::>")
for r in result:
print(r)

b) In Python, a function is a group of related statements that performs a


specific task.

Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.

Furthermore, it avoids repetition and makes the code reusable.


Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

14. a) # Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
b) number = 2
while (number<= 10):
print ("The Multiplication Table of: ", number)
count = 1
while (count < 11):
print (number, 'x', count, '=', number * count)
count += 1
number += 1
Module 3

15. a) # function to check string is


# palindrome or not
def isPalindrome(str):

# Run loop from 0 to len/2


for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

# main function
final_list = []
s = ["malayalam", "english", "hindi", "kayak", "deified", "rotator"]
count = 0

while (count < len(s)):


ans = isPalindrome(s[count])
if (ans):
final_list.append(s[count])
count += 1

print (final_list)
b) import operator
# dictionary with mixed keys
my_dict = {'empcode1': 'John', 'empcode2': 'Paul', 'empcode3': 'Aman'}

sorted_d = sorted(my_dict.items(), key=[Link](1))


print('Dictionary in ascending order by value : ',sorted_d)

#another method
print(dict(sorted(my_dict.items(), key=lambda item: item[1])))
16. a)

List Tuple

It is mutable It is immutable

The implication of iterations is time- Implications of iterations are much fa


consuming in the list. in tuples.

Operations like insertion and deletion are


Elements can be accessed better.
better performed.

Consumes more memory. Consumes less memory.

Many built-in methods are available. Does not have many built-in methods

Unexpected errors and changes can easily


occur in lists. Unexpected errors and changes rarely
occur in tuples.

Difference in syntax
As mentioned in the introduction, the syntax for list and
tuple are different. For example:

list_num = [10, 20, 30, 40]


tup_num = (10, 20, 30, 40)

Mutability
One of the most important differences between list and
tuple is that list is mutable, whereas a tuple is immutable.
This means that lists can be changed, and tuples cannot be
changed.

Operations
Although there are many operations similar to both lists
and tuples, lists have additional functionalities that are not
available with tuples. These are insert and pop operations,
and sorting and removing elements in the list.

Functions
Some of the Python functions can be applied to both data
structures, such as len, max, min, any, sum, all, and sorted.

Size
In Python, tuples are allocated large blocks of memory with
lower overhead, since they are immutable; whereas for
lists, small memory blocks are allocated. Between the two,
tuples have smaller memory. This helps in making tuples
faster than lists when there are a large number of
elements.

b) Python String Operations

Concatenation of Two or More Strings

Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals
together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
# Python String Operations
str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

str1 + str2 = HelloWorld!


str1 * 3 = HelloHelloHello

Iterating Through a string

We can iterate through a string using a for loop. Here is an example to


count the number of 'l's in a string.
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')

String Membership Test

We can test if a substring exists within a string or not, using the


keyword in .

>>> 'a' in 'program'


True
>>> 'at' not in 'battle'
False

Built-in functions to Work with Python

Various built-in functions that work with sequence work with strings as well.

Some of the commonly used ones are enumerate() and len() .


str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str))

Python String capitalize()


Converts first character to Capital Letter
Python String casefold()
converts to case folded strings
Python String center()
Pads string with specified character
Python String count()
returns occurrences of substring in string
Python String encode()
returns encoded string of given string
Python String endswith()
Checks if String Ends with the Specified Suffix
Python String expandtabs()
Replaces Tab character With Spaces
Python String find()
Returns the index of first occurrence of substring
Python String format()
formats string into nicer output
Python String format_map()
Formats the String Using Dictionary
Python String index()
Returns Index of Substring
Python String isalnum()
Checks Alphanumeric Character
Python String isalpha()
Checks if All Characters are Alphabets
Python String isdecimal()
Checks Decimal Characters
Python String isdigit()
Checks Digit Characters
Python String isidentifier()
Checks for Valid Identifier
Python String islower()
Checks if all Alphabets in a String are Lowercase
Python String isnumeric()
Checks Numeric Characters
Python String isprintable()
Checks Printable Character
Python String isspace()
Checks Whitespace Characters
Python String istitle()
Checks for Titlecased String
Python String isupper()
returns if all characters are uppercase characters
Python String join()
Returns a Concatenated String
Python String ljust()
returns left-justified string of given width
Python String lower()
returns lowercased string
Python String lstrip()
Removes Leading Characters
Python String maketrans()
returns a translation table
Python String partition()
Returns a Tuple
Python String replace()
Replaces Substring Inside
Python String rfind()
Returns the Highest Index of Substring
Python String rindex()
Returns Highest Index of Substring
Python String rjust()
returns right-justified string of given width
Python String rpartition()
Returns a Tuple
Python String rsplit()
Splits String From Right
Python String rstrip()
Removes Trailing Characters
Python String split()
Splits String from Left
Python String splitlines()
Splits String at Line Boundaries
Python String startswith()
Checks if String Starts with the Specified String
Python String strip()
Removes Both Leading and Trailing Characters
Python String swapcase()
swap uppercase characters to lowercase; vice versa
Python String title()
Returns a Title Cased String
Python String translate()
returns mapped charactered string
Python String upper()
returns uppercased string
Python String zfill()
Returns a Copy of The String Padded With Zeros

Module 4

17. # This is simplest Student data management program in python


# Create class "Student"
class Student:
# Constructor
def __init__(self, name, rollno, m1, m2):
[Link] = name
[Link] = rollno
self.m1 = m1
self.m2 = m2

# Function to create and append new student


def accept(self, Name, Rollno, marks1, marks2 ):
# use ' int(input()) ' method to take input from user
ob = Student(Name, Rollno, marks1, marks2 )
[Link](ob)

# Function to display student details


def display(self, ob):
print("Name : ", [Link])
print("RollNo : ", [Link])
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")

# Search Function
def search(self, rn):
for i in range(ls.__len__()):
if(ls[i].rollno == rn):
return i

# Delete Function
def delete(self, rn):
i = [Link](rn)
del ls[i]

# Update Function
def update(self, rn, No):
i = [Link](rn)
roll = No
ls[i].rollno = roll;

# Create a list to add Students


ls =[]
# an object of Student class
obj = Student('', 0, 0, 0)

print("\nOperations used, ")


print("\[Link] Student details\[Link] Student Details\n" /
/ "[Link] Details of a Student\[Link] Details of
Student" /
/ "\[Link] Student Details\[Link]")

# ch = int(input("Enter choice:"))
# if(ch == 1):
[Link]("A", 1, 100, 100)
[Link]("B", 2, 90, 90)
[Link]("C", 3, 80, 80)

# elif(ch == 2):
print("\n")
print("\nList of Students\n")
for i in range(ls.__len__()):
[Link](ls[i])

# elif(ch == 3):
print("\n Student Found, ")
s = [Link](2)
[Link](ls[s])

# elif(ch == 4):
[Link](2)
print(ls.__len__())
print("List after deletion")
for i in range(ls.__len__()):
[Link](ls[i])

# elif(ch == 5):
[Link](3, 2)
print(ls.__len__())
print("List after updation")
for i in range(ls.__len__()):
[Link](ls[i])

# else:
print("Thank You !")

18. a) fname = input("Enter file name: ")


count = 0
text_file = open("[Link]", "w")
with open(fname, 'r') as f:
for line in f:
words = [Link]()
for word in words:
if (5==len(word)):
count += 1
text_file.write(word)
print (word)
print("Number of words:" + str(count))
text_file.close()

b) Inheritance

 Polymorphism
 Encapsulation
 Abstraction

For more info [Link]

You might also like