0% found this document useful (0 votes)
5 views25 pages

APP Solution 2022-1

The document outlines key concepts in Advanced Python Programming, including differences between tuples and lists, the definition and creation of sets, and the properties of dictionaries. It also covers error types such as runtime and logical errors, exception handling, file operations, and various file modes. Additionally, it includes programming exercises related to these topics.

Uploaded by

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

APP Solution 2022-1

The document outlines key concepts in Advanced Python Programming, including differences between tuples and lists, the definition and creation of sets, and the properties of dictionaries. It also covers error types such as runtime and logical errors, exception handling, file operations, and various file modes. Additionally, it includes programming exercises related to these topics.

Uploaded by

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

Subject Code: 4321602 Subject Name: Advanced Python Programming

GUJARAT TECHNOLOGICAL UNIVERSITY


Diploma Engineering – SEMESTER – 2 (NEW) – EXAMINATION – Winter-2022

Q.1 (a) Give the difference between Tuple and List in python. 03

Tuple List
The Tuple is immutable. The List is mutable.
The Tuple is Enclosed in parentheses ( ) The List is Enclosed in square brackets [ ]

The Tuple has Fixed length. The List has Variable length
The Tuple provides less functionality than The List provides more functionality than
the List. a Tuple.
The Tuples are more memory efficient The Lists are less memory efficient than a
because of its immutability. Tuple

(b) Define Set and how is it created in python? 04


- A Set is an unordered collection of data.
- Set is separated by comma ( , ) and enclosed by parentheses [ ( ) ].
- Sets are mutable, which means you can add, remove, or modify elements in a set.
- How is it created in python: -

(c) What is Dictionary in Python? Write a program to concatenate two dictionary


into new one. 07

- A Dictionary represent a group of elements arranged in form of “ key-value ” pair.

- In the dictionary 1 st element considered as key and 2nd or intermediate value is


considered as it’s value.

- The key and its value is separated by colon ( : ) and all key-value is separated by
comma ( , ) and enclosed in curly braces ( { } ).

- Program to concatenate two dictionary into new one: -


Subject Code: 4321602 Subject Name: Advanced Python Programming

OR

(c) What is a list in python? Write a program that finds maximum and minimum
numbers from a list. 07
- A List in python is used to store the sequence of various types of data.

- The in the List are separated with the comma ( , ) and enclosed with the square
brackets ( [ ] ).
Subject Code: 4321602 Subject Name: Advanced Python Programming

Q.2 (a) Explain Nested Tuple with example. 03

- A Tuple inside another tuple it’s called Nested Tuple.

(b) What is random module? Explain with example. 04

- Python has many in-built package & modules.


- Random module helps in generating random numbers.
- The code given below generate a random number between X and Y – 1 (both
inclusive) using the “randrange” function of the random module.
- Example: -

- random.randint(a, b): This function generates a random integer between a and b. In


the example, we generate a random number between 1 and 10 and assign it to random
number.

- random.random(): This function generates a random float between 0 and 1. We


assign the generated float to random float.
Subject Code: 4321602 Subject Name: Advanced Python Programming

- random.randrange(a,b): This function generates a random number between a and


b. In the example, we generate a random number between 1 and 20 and assign it to
random number.

(c) Explain different ways of importing package. Give one example of it. 07

- In Python, there are several ways to import packages or modules. Here are the
different ways of importing packages:

- Importing the entire package/module:

- This imports the entire package/module, and you can access its contents using dot
notation, such as < package_name.module_name.function() >.

- Importing specific items from a package/module:

- This imports a specific module from the package, allowing you to directly access its
contents without using the package name. You can then use the module's functions or
classes directly, like < module_name.function() >.

- Importing with an alias:


-

- This imports the package/module and assigns it an alias or a shorter name. You can
then use the alias to access the package/module's contents.

- Importing specific items with an alias:

- This imports a specific module from the package and assigns it an alias. You can then
use the alias to access the module's contents directly.
- Here's an example that demonstrates these different ways of importing:
Subject Code: 4321602 Subject Name: Advanced Python Programming

OR
Q.2 (a) Write down the properties of dictionary in python. 03
- Properties of Dictionary: -

- Mutable: Dictionaries are mutable, which means you can modify, add, or remove
key-value pairs after they are created.

- No Duplicate Keys: Dictionaries do not allow duplicate keys. If you try to add a key-
value pair with a key that already exists, the previous value will be replaced.

- Example: -

- Unordered: Dictionary elements are not stored in any specific order. The order of
items may vary, and it is not preserved in the dictionary.Unordered: Dictionary
elements are not stored in any specific order. The order of items may vary, and it is
not preserved in the dictionary.
Subject Code: 4321602 Subject Name: Advanced Python Programming

(c) Write a program to define module to find sum of two numbers. Import module to
another program. 07

- sum_module.py

- main_program.py

OUTPUT: -

Q.3 (a) What is Runtime error and Logical error. Explain with example. 03\

1) Runtime Error: - When we start executing a code, it is Being Executing but


suddenly on mid-code, it stops executing the code and says there is an error, it is
known “exception” or “runtime error”.

- “Python compiler” does not detect these type of error, it is detected by “PVM”
( Python Virtual Machine ).
Subject Code: 4321602 Subject Name: Advanced Python Programming

- Example: -

- This will result in a ZeroDivisionError at runtime because division by zero is not


mathematically possible.

2) Logical Error: - It is a type of error that executes the code without problem, but the
result displayed is wrong.

- It is not detected either by ‘‘PVM’’ or ‘‘python compiler’’

- Programmer is responsible for it.

- Example: -

OUTPUT: -

- Logical error raised in above output.


Subject Code: 4321602 Subject Name: Advanced Python Programming

(b) Write points on Except and explaining it. 04

- “Except” is a keyword used to define a block of code that is executed when a specific
exception is raised within a preceding “try” block.

- It allows you to handle and respond to exception in a controled manner.

- The “excerpt” block is where you specify the types of exception you want to catch,
and you can include the appropriate error handling code to address the exception
scenario.

- Built-in Exception Types: Python provides a wide range of built-in exception types
that cover various error conditions. Some common exception types include

- ValueError

- TypeError

- FileNotFoundError

- IndexError, and

- KeyError, among others.

(c) Write a user defined exception that could be raised when the text entered by a
user consists of less than 10 characters. 07

class TException(Exception):
pass
n=10
while True:
try:
a=input("Enter Your String : - ")
print("\r")
l=len(a)
if l<n :
raise TException
break
except TException :
print("You Have Entered Less Than 10 Characters ")
print("\r")
print("Plz Enter 10 OR More Than 10 Characters ")
print("\r")
print("!! CORRECT !!")
Subject Code: 4321602 Subject Name: Advanced Python Programming

OUTPUT: -

OR

Q.3 (a) What are the built-in exceptions and gives its types. 03

- A list of common exceptions that can be thrown from a standard python programme
is given below.

1) SyntaxError:

- Description: Raised when there is a syntax error in the code.


- Example:
Subject Code: 4321602 Subject Name: Advanced Python Programming

2) TypeError:

- Description: Raised when an operation or function is applied to an object of an


inappropriate type.
- Example:

3) NameError:
- Description: Raised when a local or global name is not found.

- Example:

4) ZeroDivisionError:

- Description: Raised when division or modulo operation is performed with zero as


the divisor.

- Example:
Subject Code: 4321602 Subject Name: Advanced Python Programming

(b) Explain Syntax error and how do we identify it? Give an example. 04

- Syntax Error: - It’s one of the most basic types of error in programming whenever
we do not write a proper syntax, It generates syntax error.

- To identify syntax error, The error message usually indicates the line number or
location where the error occurred and provides information about the specific nature
of the error.

- By analyzing this information, developers can identify the cause of the syntax
error and correct it.

- Example: -

- In this case, the error is a missing closing parenthesis in the print statement. If you
attempt to run this code, Python will raise a syntax error with a message similar to:
Subject Code: 4321602 Subject Name: Advanced Python Programming

(c) What is Exception handling in python? Explain with proper example. 07


- Exception handling is way to deal with exceptions.

- It can be done using: -

- 1) try 2) except 3) finally

- 1) try: - The “ try ” block contains the code that have the exceptions.

- To control the exception, it is (exception) sent to accept block.

- 2) except: - It is executed when the preceding “try” block have an exception.

- This block is where you specify the types of exception you want to catch, and you
can include the appropriate except scenario.

- 3) finally: - It is an optional block in way to deal with exception handling.

- It’s always be executed, where the “try-except" block has an exception or not.

- Example: -

OUTPUT: -
Subject Code: 4321602 Subject Name: Advanced Python Programming

Q.4 (a) What kind of different operations we can perform in a file? 03


 1) Opening a File: - To perform operation on a file, you need to open it first using the
“ open() ” function. It takes 2(Two) arguments.
- "filename.txt" is the name or path of the file.
- "mode" specifies the purpose for opening the file, such as 'r' for reading, 'w'
for writing, 'a' for appending, and more.

- Syntax:
file = open("filename.txt", "mode")

- Example: -
f = open(“abc.txt”,‘r’)

 2) Reading from a file: - After opening a file, you can read its content using the
“read()” method. It returns the entire content of the file as a string.
- Syntax:
1) content = file.read() # Read the entire content of the file
2) line = file.readline() # Read a single line from the file
3) lines = file.readlines() # Read all lines of the file and return as a list

- Example: -
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

 3) Writing to a file: - You can write data to a file using the “write()” method. It
replaces the existing content with the new data. If the file doesn’t exist, It will be created.
- Syntax:
file.write("content")

- Example: -
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

 4) Appending to a file: - If you want to add content to an existing file without


overwrite its existing content you can open it in append mode using “a” as the second
argument in “open()”.
Subject Code: 4321602 Subject Name: Advanced Python Programming

- Syntax:
file = open("filename.txt", "a")
file.write("content")

- Example: -
file = open("example.txt", "a")
file.write("Appending new content.")
file.close()

 5) Closing a file: - After performing operation on a file, its important to close the file
using “close()” method
- Syntax:

file.close()

- Example: -

file = open("example.txt", "r")


content = file.read()
print(content)
file.close()

(b) Give list of file modes. Write Description of any four mode. 04
 File opening modes determine the purpose & permissions of file access when
mopening a file in python.
- "r": Read mode - Opens a file for reading. The file must exist.
- "w": Write mode - Opens a file for writing. If the file already exists, it is truncated
(emptied). If it doesn't exist, a new file is created.
- "a": Append mode - Opens a file for appending data. The file pointer is positioned at
the end of the file. If the file doesn't exist, a new file is created.
- "x": Exclusive creation mode - Opens a file for exclusive creation. If the file already
exists, an error is raised.
- "b": Binary mode - Opens a file in binary mode. This mode is used to handle non-
text files like images or binary data.
- "t": Text mode - Opens a file in text mode (default). This mode is used to handle text
files.
- "+": Read and write mode - Opens a file for both reading and writing.
Subject Code: 4321602 Subject Name: Advanced Python Programming

- Description of any four mode: -

- 1) 'r': Read Mode

- This mode is used to open a file for reading.


- The file pointer is positioned at the beginning of the file.
- If the file does not exist, a FileNotFoundError is raised.
- Example:
file = open("example.txt", "r")

- 2) 'w': Write Mode

- This mode is used to open a file for writing.


- If the file already exists, its contents are truncated (cleared) before writing.
- If the file does not exist, a new file is created.

- The file pointer is positioned at the beginning of the file.


- Example:
file = open("example.txt", "w")

- 3) 'a': Append Mode

- This mode is used to open a file for appending.


- If the file exists, the new data is written to the end of the file.
- If the file does not exist, a new file is created.
- The file pointer is positioned at the end of the file.

- Example:
file = open("example.txt", "a")

- 4) 'x': Exclusive Creation Mod

- This mode is used to create a new file, but it raises a FileExistsError if the file
already exists.
- The file pointer is positioned at the beginning of the file.

- Example:
file = open("example.txt", "x")
Subject Code: 4321602 Subject Name: Advanced Python Programming

(c) Write a program to sort all the words in a file and put it in list. 07
Subject Code: 4321602 Subject Name: Advanced Python Programming

OR

Q.4 (a) What is file handling? List files handling operation and explain it. 03
- Files are named locations on a disk to store related information. They are used to
permanently store data in non-volatile memory ( e.g. hard disk ).

- Files Handling Operation: -

- 1) Creating a file: File handling allows you to create a new file in the file system.
The file can be empty or contain initial data.

- 2) Opening a file: Once a file is created, you can open it to perform operations on its
contents. Opening a file establishes a connection between the file and your program.

- 3) Reading from a file: You can read data from a file using various methods. For
example, you can read the entire contents of a file or read it line by line.

- 4) Writing to a file: File handling enables you to write data to a file. You can write
text, numbers, or other types of data to a file. This operation can overwrite existing
data or append data to the end of the file.

- 5) Appending to a file: In addition to overwriting or replacing existing data, you can


append new data to the end of an existing file without affecting the existing contents.

- 6) Closing a file: After reading from or writing to a file, it's important to close the
file. Closing a file releases system resources associated with it and ensures that
changes made to the file are saved.

(b) Explain object serialization. 04


- The process of serializing is to convert the data structure into a linear form, which
can be stored or transmitted through the network.

- In python, serialization allows the developers to convert the complex object structure
into a stream of bytes that can be saved in the disk or can send through the network.

- The developer can refer to this process as Marshalling.

- Whereas, Deserialization is the reverse process of serialization in which the user


takes the stream of bytes and transforms it into the data structure.

- This process can be referred to as unmarshalling.

- In python three modules in the standard library allows the developer to serialize and
deserialize the objects:

- 1) The pickle module 2) The marshal module 3) The json module


Subject Code: 4321602 Subject Name: Advanced Python Programming

(c) Write a program that inputs a text file .The program should print all of the
unique words in the file in alphabetical order. 07

n = input("Enter Your File Name : -

") f = open(n)

l = list()

for line in f:

word =

line.split() for

element in word:

if element in l:

continue

else:

l.append(element)

l.sort()

print(l)

My File: -
File Name: - tilak.txt

Content: - Hi I Am Tilak,Tilak Is Back


Subject Code: 4321602 Subject Name: Advanced Python Programming

Q.5 (a) Explain the use of the following turtle function with an appropriate example.
(a) turn () (b) move (). 03

- (a) turn: - This method rotates the turtle by the specified angle in degrees.

- 1) right (angle): - It turns the turtle clockwise.

- Example: -

turtle.right(90)

- It will turns the turtle 90 degrees to the right side.

- 2) left (angle): - It turns the turtle anti-clockwise.

- Example: -

turtle.left(90)

- It will turns the turtle 90 degrees to the left side.

- (b) move (): - This method moves the turtle forward and backward by the specified
distance in Pixels.

- 1) forward (amount): - It moves the turtle forward by the specified amount.

- Example: -

turtle.forward(100)

- It will moves the turtle forward to 100 pixels.

- 2) backward (amount): - It moves the turtle backward by the specified amount.

- Example: -

turtle.backward(100)

- It will moves the turtle backward to 100 pixels.


Subject Code: 4321602 Subject Name: Advanced Python Programming

(b)Explain the various inbuilt methods to change the direction of the turtle. 04
- There are two inbuilt methods to change the direction of the turtle in turtle in Turtle.

- 1) right (angle): - It turns the turtle clockwise.

- Example: -

turtle.right(90)

- It will turns the turtle 90 degrees to the right side.

- 2) left (angle): - It turns the turtle anti-clockwise.

- Example: -

turtle.left(90)

- It will turns the turtle 90 degrees to the left side.

(c) Write a program to draw square, rectangle and circle using turtle. 07
 APP Turtle1 PR 21.py
import turtle
t=turtle.Turtle()
t.shape("turtle")
t.fd(200)
t.lt(90)
t.fd(200)
t.lt(90)
t.fd(200)
t.lt(90)
t.fd(200)
 APP Turtle2 PR 21.py
import turtle
t=turtle.Turtle()
t.shape("turtle")
t.circle(125)
 APP Turtle3 PR 21.py
import turtle
t=turtle.Turtle()
t.shape("turtle")
t.fd(300)
t.lt(90)
t.fd(150)
t.lt(90)
t.fd(300)
t.lt(90)
t.fd(150)
Subject Code: 4321602 Subject Name: Advanced Python Programming

- OUTPUT: -
Subject Code: 4321602 Subject Name: Advanced Python Programming

OR

Q.5 (a) What are the various types of pen command in turtle Explain them all. 03
- In the turtle graphics module, there are several pen related commands that allow
you to control the appearance and behaviour of the drawing pen.

- Here are the main pan commands in turtle: -

- penup ( ): - It pick up the turtles pan.

- pendown ( ): - It put down the turtles pen.

- Color ( ): - It changes the colour of the turtles pen.

Example: -
turtle.color(“Blue”)
- pensize ( ): - You can increase or decrease thickness of your pen.

Example: -
turtle.pensize(10)

- seed ( ): - You can increase or decrease the speed of a turtle to move slower or
faster

Example: -
turtle.speed(15)

- penup ( ): - It pick up the turtles pan.

- pendown ( ): - It put down the turtles pen.


Subject Code: 4321602 Subject Name: Advanced Python Programming

(b) Draw circle and triangle shapes using turtle and fill them with red color. 04

 APP Turtle2 PR 21.py


import turtle
t=turtle.Turtle()
t.shape("turtle")
t.circle(125)

 APP Turtle2 PR 21.py

from turtle import*

# Set the fill color to red


fillcolor("red")

# Draw a circle
begin_fill()
circle(100)
end_fill()

# Move to a new position for drawing the triangle


penup()
goto(-50, -100)
pendown()

# Draw a triangle
begin_fill() OUTPUT: -
for _ in range(3):
forward(100)
left(120)
end_fill()
Subject Code: 4321602 Subject Name: Advanced Python Programming

(c) Write a program to draw smiling face emoji using turtle. 07

import turtle as t

t.speed(5)

#circle
t.pencolor("black")
t.fillcolor("yellow")
t.begin_fill()
t.circle(150)
t.end_fill()

t.up()
t.goto(60,180)
t.down()

#eye
t.fillcolor("white")
t.begin_fill()
t.circle(15)
t.end_fill()

#retina
t.fillcolor("black")
t.begin_fill()
t.circle(8)
t.end_fill()

t.up()
t.goto(-60,180)
t.down()

#eye
t.fillcolor("white")
t.begin_fill()
t.circle(15)
t.end_fill()

#retina
t.fillcolor("black")
t.begin_fill()
t.circle(8)
t.end_fill()

#nose
t.fillcolor("red")
Subject Code: 4321602 Subject Name: Advanced Python Programming

t.begin_fill()
t.up()
t.goto(0,130)
t.down()
t.circle(8)
t.end_fill()

t.up()
t.goto(0,60)
t.down()

#right smile
t.pensize(6)
for i in range(60):
t.lt(1)
t.fd(1)
t.up()
t.goto(0,60)
t.down()

t.rt(59)

#left smile
for i in range(60):
t.rt(1)
t.bk(1)

OUTPUT: -

You might also like