Python Important Questions with Answers Ch. Vijayananda Ratnam 1 a) Describe the features of Python. Python’s Features Include: Easy-to-Learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy-to-read: Python code is more clearly defined and visible to eyes. Easy-to-maintain: Python’s source code is fairly easy-to-maintain. A broad standard library: Python’s bulk of the library is very portable and cross-platform compatible on UNIX, and Windows. Interactive Mode: Python has support for an interactive mode which allows interactive testing and debugging of code. Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows system, such as windows MFC, Macintosh, and the X Window system of UNIX. Scalable: Python provides a better structure and support for large programs than shell scripting. Dynamically Typed: We need to specify the data type of variable while creation. Python can understand the data type of variable after storing the value. It is called dynamically typed. 1 b) What is IDLE? Describe in detail about the functioning of IDLE? Python - IDLE IDLE (Integrated Development and Learning Environment) is an integrated development environment (IDE) for Python. The Python installer for Windows contains the IDLE module by default. IDLE can be used to execute a single statement just like Python Shell and also to create, modify, and execute Python scripts. IDLE provides a fully-featured text editor to create Python script that includes features like syntax highlighting, autocompletion, and smart indent. It also has a debugger with stepping and breakpoints features. To start an IDLE interactive shell, search for the IDLE icon in the start menu and double click on it. 1 Python Important Questions with Answers Ch. Vijayananda Ratnam Fig. Python IDLE This will open IDLE, where you can write and execute the Python scripts, as shown below. Fig. Python IDLE You can execute Python statements same as in Python Shell as shown below. Fig. Python IDLE To execute a Python script, create a new file by selecting File -> New File from the menu. 2 Python Important Questions with Answers Ch. Vijayananda Ratnam Enter multiple statements and save the file with extension ‘.py’ using File -> Save. For example, save the following code as hello.py. Fig. Python Script in IDLE Now, press F5 to run the script in the editor window. The IDLE shell will show the output. Fig. Python Script Execution Result in IDLE Thus, it is easy to write, test and run Python scripts in IDLE. 2 a) Who uses python today? What are Python’s technical strengths? Apart from individual users, Google makes extensive use of Python in its web search system, and employs Python’s creator Guido van Rossum. The YouTube video sharing service is largely written in Python. 3 Python Important Questions with Answers Ch. Vijayananda Ratnam Disney uses Python in many of their creative processes. Mozilla uses Python to explore their extensive code base and releases tons of open source packages built in python. Drop box file hosting service is implemented using Python, Guido van Rossum now working here. The popular Bit Torrent peer-to-peer file sharing system is a Python program. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing. JPMorgan Chase, UBS, Getco, and Citadel apply Python for financial market forecasting. NASAuses Python for scientific programming tasks. iRobot uses Python to develop commercial robotic vacuum cleaners. The NSA uses Python for cryptography and intelligence analysis. Instagram’s backend is completely written in Python. Pinterest and Quora use Python for their backend systems. Python’s Technical Strengths: 1. It is Object-Oriented and Functional 2. It is Free 3. It is Portable 4. It is Powerful 5. It is Mixable 6. It is Relatively Easy to Use 7. It is Relatively Easy to Learn 2 b) What are different applications of Python? Give examples We can build following type of applications using python. 1. 2. 3. 4. 5. 6. 7. Web / Internet applications. Desktop / Stand-alone applications. Scientific application. Systems Programming. Educational Applications. Business Applications. Database Applications And More: Gaming, Images, Data Mining, Robots, Excel... Python is commonly applied in more domains than can be covered here. For example, you’ll find tools that allow you to use Python to do: Game programming and multimedia with pygame, cgkit, pyglet, PySoy, Panda3D, and others Serial port communication on Windows, Linux, and more with the PySerial extension 4 Python Important Questions with Answers Ch. Vijayananda Ratnam Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya, and more Robot control programming with the PyRo toolkit Natural language analysis with the NLTK package Instrumentation on the Raspberry Pi and Arduino boards Mobile computing with ports of Python to the Google Android and Apple iOS platforms Excel spreadsheet function and macro programming with the PyXLL or DataNitro add-ins Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow, and more Artificial intelligence with the PyBrain neural net library and the Milk machine learning toolkit Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog Network monitoring with zenoss, written in and customized with Python Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD, and others Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF, and so on Data visualization with Mayavi, matplotlib, VTK, VPython, and more XML parsing with the xml library package, the xmlrpclib module, and third-party extensions JSON and CSV file processing with the json and csv modules 3 a) List and explain few most commonly used built-in types in python. There are different types of data types in Python. Some built-in Python data types are: 1. Numeric types: int, float, complex 2. Text type: str 3. Boolean type:bool 4. Sequence types:list, tuple, range 5. Mapping type: dict 6. Set types: set, frozenset 1. Numeric Types Python supports three different numerical types − int − They are often called just integers or ints, are positive or negative whole numbers with no decimal point. float − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250). 5 Python Important Questions with Answers Ch. Vijayananda Ratnam complex − These are of the form “a + bJ”, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Examples: 2. Text Sequence Types – String In Python, str represents string datatype.A String is a sequence of characters that are enclosed with in single or double quotes. If the strings are spanned over multiple lines, then they can be denoted by the use of triple """ or '''quotes. We will now see an example of creating single-line and multi-line strings – The triple double or single quotes are useful to embed a string insideanother string. str="""This is unit covers 'Core Python' concepts""" 3. bool Datatype The bool datatype represents Boolean values i.e. True and False. A blank string like ' 'isalso represented as False. Conditions will be evaluated internally either True and False. Examples: >>> 10>5 #True >>>10<5 #False Python internally represents Boolean True as 1 and Boolean False as 0. So, they are treated as numbers. The following statements will prove that Boolean valuesas numbers: >>>True + True #displays 2 because True is 1 and False is 0 >>>True - False #displays 1 >>>True + 12 #displays 13 6 Python Important Questions with Answers >>>True - 10 >>> 10 – False Ch. Vijayananda Ratnam #display -9 #displays 10 4. Sequence Types A sequence represents a group of elements or items. There are three types of sequences inPython. 1. list 2. tuple 3. range list Datatype Lists in Python are similar to arrays in C. A list represents group of elements. A list canstore different types of elements. Lists can grow dynamically at runtime.Lists are mutable (i.e.: modifiable). Lists are represented using square brackets [ ] and the elements are separatedby commas. Syntax list_name = [item1,item2,…,itemN] Example lst = [] #empty list lst =[1,1.34,"Vijay",2+3j,-45] #list with different types of elements tuple Datatype A tuple is similar to list. A tuple contains a group of elements which can be of differenttypes. The elements in the tuple are separated by commas and enclosed in parenthesis(). Tuples are immutable (i.e: not modifiable) that means a tuple can be treated as aread-only list. Syntax tuple_name = (item1,item2,item3,…,itemN) Example: tpl = (10,12.5,-30, "Vijay",2+3j) range Datatype The range data type generates a sequence of numbers. The numbers in the range are not modifiable. Generally, range is used for repeating a for loop for a specific number oftimes. Syntax range(begin, end, step) It generates a range of numbers from begin to end-1 with a difference of step. Example: range(5) ─ generates range of integers from 0 to 4. range(10,16) ─generates range of integers from 10 to 15. range(10,20,2) ─ generates range of integers from 10 to 19 with a difference of 2. 5. Mappings/Dictionaries 7 Python Important Questions with Answers Ch. Vijayananda Ratnam A map represents a group of elements in the form of key-value pairs so that when the key is given, we can retrieve the value associated with it. The ‘dict’ data type is example for a map. The dict represents a dictionary that contains pair of elements such that the first element represents the key and the next element becomes its value. The key and its value should be separated by colon (:) and every pair should be separated by comma. All the elements should be enclosed inside curly brackets {}. Example d = {501:"Vijay",502:"Anand",503:"Chaitanya",504:"Raju",505:"Krishna"} Here, d is name of the dictionary, 501 is the key and its associated value is "Vijay" and same is for the remaining elements. We can create an empty dictionary as: d = {} 6. Sets A Set is an unordered collection of elements. The order of elements is not maintained in the sets. Set elements are unique that means duplicate elements are not allowed. There are two subtypes in sets: o set datatype o frozenset datatype set Datatype a set can be defined with curly braces {} and the elements are separated by commas.Sets are mutable. Sets are unordered so we cannot retrieve the elements using indexingor slicing. Syntax set_name = {item1,item2,…,itemN} Example: >>> s = set({10,40,20,30,10,40,20,50}) >>> print(s) {50, 20, 40, 10, 30} When you observe the above example, The set ‘s’ not maintaining the order The duplicate elements were removed It is also possible to convert a list into set by using set() function. >>> l = [10, 20, 10, 20, 30, 40, 50] >>> print(l) [10, 20, 10, 20, 30, 40, 50] >>> s = set(l) >>> print(s) 8 Python Important Questions with Answers Ch. Vijayananda Ratnam {40, 10, 50, 20, 30} In the above example, list 'l' is converted into set 's' by using set() function. frozenset Datatype A fozenset is same as set datatype except that a frozenset is immutable. We can create a frozenset by passing a set to frozenset() function. Example s={50,60,70,80,90} print(s) #{70,80,50,90,60} fs=frozenset(s) print(fs) # frozenset({80, 50, 70, 90, 60}) Determining the Datatype of a Variable type() function is used to know the datatype of a variable or object. Syntax: type(var_name/object) Example: >>> a = 10 >>> type(a) <class 'int'> 3 b) Explain various formatted I/O functionsin python with example. To handle I/O, Python provides two types of functions. They are: 1. print function 2. input function print() statement: It is used to display output or results on screen, this function can be used in different formats. When the print() function is called, it will throw the cursor to the next line. It means that a blank line will be displayed. print(string) statement: When a string is passed to the print() function, the string is displayed as it is. Example: >>> print('Core Python') Core Python We can use escape sequence characters inside the print() function like \n, \t, etc. Example: Example: print('Core\nPython') print('Core\tPython') Core Core Python Python We can use repetition operator (*) to repeat the strings in the output as: Example: >>>print('Hi'*3) 9 Python Important Questions with Answers Ch. Vijayananda Ratnam HiHiHi We use ‘+’as string concatenation operator means joins one string at the end of another string without giving any space between them Example: print('City='+'Amaravathi') City=Amaravathi We also use comma (,) as string combining operator but it adds one white space between them. Example: print('City=','Amaravathi') City=Amaravathi print(variable_list, sep='separator_char', end='ending_char') print() function also display the values of multiple variables by separating them with a separator and ending with a ending character. The list of variables must be separated by comma. Example: >>>a,b=5,6 >>>print(a,b) # by default two values are separated by single space. 56 >>>print(a,b,sep='-') #display two values separated by dash(-) 5-6 >>>print(a,b,sep='-',end='@') #print two values separated by '-' and ends with '@' 5-6@ print('string', variable_list) This is the most common form of print() function is to use strings along with variables inside a print() function Example: a=5 print(a,' is an odd number') 5 is an odd number print(formatted string) The special operator % (percent) used to display the output as we like. It joins the string with a variable or value in the following format. Syntax: print('formatted string' %(variable_list)) 10 Python Important Questions with Answers Ch. Vijayananda Ratnam In the formatted string, we use different format specifiers to represent different types of values such as numbers, strings etc. Examples: Format specifier Statement Output %i or %d print(Int: %i % 4) Int:4 print('Int zero padded: %03d' % 4) Intzero padded: 004 print('Int space padded: %3d' % 4) Int space padded: 4 %f print('Float: %f' % 2.4) Float: 2.400000 print('Float: %.2f' % 2.456) Float: 2.46 %e or %E print('Float in Sci.form: %e' %2.4) Float in sci.form: 2.400000e+00 print('Float in Sci.form: %.2E' %2.4) Float in sci.form: 2.40E+00 %x or %X print('Hexa decimal: %x' % 255) Hexa decimal: ff print('Hexa decimal: %X' % 255) Hexa decimal: FF (capitalized) %o print('Octal: %o' % 8) Octal: 10 %s print('String: %s' % 'Python') String: Python print('Left padded str:(%10s)' % Left padded str:( Python) 'Python') print('Right padded str:(%-10s)' % Right padded str:(Python ) 'Python') print('Truncated str: %.3s' % 'Python') Truncated str: Pyt print('List as str: %s' % [1,2,3]) List as str: [1, 2, 3] print('Dictvalue as str: %(age)s' % Dictvalue as str: 20 {'age':20}) %c print('Char: %c' % 65) Char: A 2. input function To accept input from keyboard, Python provides the input() function. This function takes a value from the keyboard and returns it as string. Syntax: var=input() For better understanding of what to enter, user can write a message inside the input() function as: var = input(message) Example: >>>name = input('Enter your name:') 11 Python Important Questions with Answers Ch. Vijayananda Ratnam Vijayanand >>>print('Your name is ', name) Your name is Vijayanand Accepting multiple inputs To accept more than one input in the same line, we use the for loop along with the input() function in the following format: var_list = [i for i in input().split()] Example: To accept two strings at a time: >>> str1, str2 = [i for i in input('Enter two strings: ').split()] Enter two strings: Python Java >>> print(f"String1: {str1}\nString2: {str2}") String1: Python String2: Java Method -2: This method reads multiple values and stores it in a list. Here datatype is required type of data. list_var=list(map(datatype, input().split())) Example 4 a) Explain arithmetic and membership operators in detail. Arithmetic Operators These are used to perform mathematical operations. Most of them are binary operators since they operate on two operands at a time except unary minus and plus. They can be applied to any integers, floating-point numbers and complex types. Python supports 7 arithmetic operators. They are +, -, *, **,//,/, %. Let us take a=13 and b=4 and see the effect of various arithmetic operators. The following table lists the arithmetic operators: Operator Meaning Example Result + Addition - (Adds two values) a+b 17 Subtraction – (Subtract one value from another) a-b 9 12 Python Important Questions with Answers * / // ** % Ch. Vijayananda Ratnam Multiplication – (Multiply a times b) Floating point division (a by b) Integer division (a by b) Exponentiation (a to the power of b) Modulo division (returns remainder ) a*b a/b a//b a**b 52 3.25 3 28561 Example - 1: Python program that illustrates the arithmetic operators (arith.py) a,b=[int(i) for i in input('Enter a ,b values:').split()] print('Sum is :',a+b) print('Subtraction is :',a-b) print('Multiplication is :',a*b) print('FP Division is :',a/b) print('Integer Division is :',a//b) print('The Modulo Division is :',a%b) print('Exponentiation is :',a**b) Output Enter a ,b values:10 3 Sum is : 13 Subtraction is : 7 Multiplication is : 30 FP Division is : 3.3333333333333335 Integer Division is : 3 The Modulo Division is : 1 Exponentiation is : 1000 Membership Operators The membership operators in Python are used to test whether a value is found within a sequence. There are two membership operators in Python: 1. in 2. not in The in operator This operator returns True if an element found in the sequence otherwise returns False. Example >>>s = ['a', 'b', 'c', 'd'] >>> 'a' in s True >>> 'z' in s False The not in operator This works in reverse manner for in operator. It returns True if an element is not found 13 Python Important Questions with Answers Ch. Vijayananda Ratnam in the sequence, otherwise returns True. Example >>>s = ['a', 'b', 'c', 'd'] >>> 'z' not in s True >>> 'a' not in s False 4 b) Discuss about logical and bitwise operators in detail? Logical operators Operators which are used to combine two or more relational expressions are known as logical operators. Python supports three logical operators – logical AND (and), logical OR (or), logical NOT (not). All of these operators when applied to expressions yield either True or False. In the case of logical operators, False indicates 0 and True indicates any Non-zero value. Let us take x=1 and y=2 and see the effect of various logical operators. The table lists the logical operators: Operator Meaning Example and If x if False, it returns x, otherwise returns y x and y or If x if False, it returns y, otherwise returns x x or y not If x if False, it returns True, otherwise False not x following Result 2 1 False These are also known as short-circuit logical operators. When we use 'or' operator if left hand side expression is True, then the result will be True, no matter what is the result of right hand side expression. In the case of 'and' if the left hand side expression results False, then the result will be False, no matter what is the result of right hand side expression. Example - 3: Python program that illustrates the Boolean operators (logic_op.py) x=10 y=20 print('x and y = %s' %(x and y)) print('x or y = %s' %(x or y)) print('not x = %s' %(not x)) 14 Python Important Questions with Answers Ch. Vijayananda Ratnam Output x and y = 20 x or y = 10 not x = False 5 a) Discuss about relational andidentity operators in detail? Relational operators A relational operator, also known as a comparison operator, is an operator that compares two operands. The operands can be variables, constants or expressions. Relational operators always return either True or False depending on whether the conditional relationship between the two operands holds or not. Python has six relational operators. The following with their meanings Operator Meaning < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to table shows these operators along Example 4<5 returns True 4>5 returns False 100<=100 returns True 50>=100 return False 4==5 return False 4!=5 return True Example - 2: Python program that illustrates the relational operators (rel_op.py) a,b=[int(i) for i in input('Enter a,b values:').split()] print('%d > %d = %s' %(a,b,a>b)) print('%d < %d = %s' %(a,b,a<b)) print('%d >= %d = %s' %(a,b,a>=b)) print('%d <= %d = %s' %(a,b,a<=b)) print('%d == %d = %s' %(a,b,a==b)) print('%d != %d = %s' %(a,b,a!=b)) Output Enter a,b values:4 5 4 > 5 = False 4 < 5 = True 4 >= 5 = False 4 <= 5 = True 4 == 5 = False 4 != 5 = True 5 b) Explain in detail about Python type conversion and type casting? Type conversion is a process of converting one data type to another data type. It is also called as Type casting. It can be of two types: They are 1. Implicit Conversion 2. Explicit Conversion. Implicit Conversion When the type conversion is performed automatically by the compiler withoutprogrammer’s intervention, such type of conversion is known as Implicit type 15 Python Important Questions with Answers Ch. Vijayananda Ratnam conversion or automatic type promotion. In this, all the lower data types are converted to its next higher data type. Example: Program that illustrates implicit type conversion (implicit.py) c=True n=10 f =12.0 s=n+f+c print("Sum = ",s) Output: Sum=21.0 Here Boolean and Integer type are automatically converted in to Floating point values. Explicit Conversion It is intentionally performed by the programmer as per his requirement in a Python program. The explicit type conversion is also known as type casting. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type. To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: target_type(variable / value ) Here the target type specifies the destination type to which the value has to be converted. When a floating-point value is assigned to an integer type, the fractional component is lost. For example, if the value 12.34 is assigned to an integer, the resulting value will simply be 12.The 0.34 will have been truncated. >>>a=12.34 >>>int(a) 12 #converts float to int and returns 12. Example: Program that illustrates explicit type conversion (Explicit.py) n=15 print('Binary equivalent of %d is %s' %(n,bin(n))) print('Octal equivalent of %d is %s' %(n,oct(n))) print('Hex equivalent of %d is %s' %(n,hex(n))) print('Binary equivalent of %d is %s' %(n,float(n))) Output Binary equivalent of 15 is 0b1111 16 Python Important Questions with Answers Ch. Vijayananda Ratnam Octal equivalent of 15 is 0o17 Hex equivalent of 15 is 0xf Binary equivalent of 15 is 15.0 UNIT-II 1 a) What are the different conditional statements available in Python? Explain with suitable examples. They allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. They are also called as Conditional or Decision Making Statements. 1. The if statement The if statement is used to execute one or more statements depending on whether a condition is True or not. The syntax of if statement is: if condition: statements First, condition is tested, if the condition is True, then statements given after colon (:) are executed. Otherwise, statements will not be executed. Example: A Python program that illustrates if statement (test.py) a=2 if a>0: print(a,' is positive') Output 2 is positive 2. The if..else statement This is an extension to simple if. This is used to route the execution through two different paths. The general form of if..else statement will be as follow: if condition: statements else: statements If condition is True, it executes if part statements otherwise, it executes else part statements. Example: A Python program to test whether a given number is even or odd (even.py). n = int(input('Enter number to check:')) if n%2==0: print(n, 'is even') else: print(n, 'is odd') 17 Python Important Questions with Answers Ch. Vijayananda Ratnam Output Enter number to check:4 4 is even Enter number to check:67 67 is odd 3. The if..elif..else statement (chained conditionals) Sometimes we need to test more than one condition. One way to express such a computation like that is a chained conditional. It used to test a sequence of conditions. It looks like this: if condition1: statement_1 elif condition2: statement_2 elif condition3: statement_3 .. . elif condition_N: statement_N else: statement The if statements are executed in a sequential manner. As soon as one of the conditions is True, the statement associated with that is executed, and the rest of the ladder is bypassed. If none of the conditions is True, then the final else statement will be executed. Example: A Python Program to check whether a given number is positive or negative (Type.py). Output: n = int(input('Enter number to check: ')) Enter number to check: 4 if n>0: 4 is positive. print(n,'is positive.') elif n<0: Enter number to check: -3 print(n, 'is negative.') -3 is negative. else: print('It is zero.') Enter number to check: 0 It is zero. 1b) Write a Python program that interchanges the first and last characters of a given string. str = input("Enter a string : ") swap_str = str[-1:] + str[1:-1] + str[:1] print(swap_str) Output: Enter a string : python nythop 18 Python Important Questions with Answers Ch. Vijayananda Ratnam 2 a) Explain about iteration statements with examples. Python offers two kinds of loops, the for loop and the while loop. These statements create what we commonly called loops. A loop repeatedly executes the same set of instructions until a termination condition is met. Advantages Reduce length of Code Take less memory space. Burden on the developer is reducing. Time consuming process to execute the program is reduced. 1. while loop The while loop is a pre-test or entry-controlled loop. It uses conditional expression to control the loop. The while loop evaluates (checking) the condition before every iteration of the loop, so it can execute zero times if the condition is initially false. The initialization of a loop control variable is generally done before the loop separately. while condition: statements inc/dec loop_control variable How while loop works? Initially the while loop evaluates (checking) the condition. If the condition is True, statements inside the body of while loop is evaluated. Then, again the condition is evaluated. The process goes on until the condition is False. When the condition is False, the while loop is terminated. Example: Python program to print 1 to 10 numbers using while loop (numbers.py). i=1 while i<=10: print(i,end=' ') i+=1 Output 1 2 3 4 5 6 7 8 9 10 2. for loop It is the most general looping construct in Python. The for loop is useful to iterate over the elements of the sequence. The for loop can be work with sequence like string, list,tuple, range etc. The for loop is commonly used when the number of iterations areexactly known. The syntax of a for loop is: for var in sequence: statements 19 Python Important Questions with Answers Ch. Vijayananda Ratnam How for loop works? Initially, first element of the sequence is assigned to the variable var then the statements are executed. Next, second element of the sequence is assigned to the variable var then the statements are executed second time. This process will be continued as many times as there are number of elements in the sequence. Example: Python program to print individual characters of a string (for.py). str='Python' for char in str: print(char) Output P y t h o n 2 b) Implement a python program to check whether the given number is prime or not n = int(input("Enter a number : ")) f=0 for i in range(2,n//2+1): if n%i==0: f+=1 if f==0: print(n,'is prime') else: print(n,'is not a prime') Output: Enter a number : 17 17 is prime 3a) Describe Python jump/loop control statements with examples. Python supports three jump statements: break, continue, and return. These statements transfer control from one location to another with in a program. 1. break statement The break statement can be used inside a for loop or while loop to come out of the loop. when break statement is encountered inside a loop, the loop is immediately terminated, and program control is transferred to next statement following the loop. 20 Python Important Questions with Answers Ch. Vijayananda Ratnam Its syntax is quite simple, just type keyword break. break Example: Python program that illustrates the use of break statement (break.py) x=1 while x<=5: if x==3: #if x is 3 then come out from loop. break print('x=',x) x+=1 print('Outside the Loop') Output x=1 x=2 Outside the Loop 2. continue statement The continue statement can be used in a loop to go back to the beginning of the loop that means when continue statement is encountered inside a loop, it stops the current iteration and places the loop in next iteration. continue When continue is executed, the subsequent statements in the loop are not executed. Example: Python program that illustrates the use of continue statement (continue.py) x=0 while x<5: x+=1 if x==3: #if x is 3 then continue to next iteration. continue print('x =',x) Output x=1 x=2 x=4 x=5 3. return statement The return statement is used to explicitly return a value from method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. return (expression/value) 21 Python Important Questions with Answers Ch. Vijayananda Ratnam Example: Python function that returns the sum of two numbers (return.py) def add(x,y): return x+y # result is returned from here a = int(input('Enter a value:')) b = int(input('Enter b value:')) print('Sum =',add(a,b)) Output Enter a value: 3 Enter b value: 4 Sum = 7 3 b) Write a python program to find no of digits in a given number n = int(input("Enter a number : ")) digits=0 while n!=0: digits+=1 n = n//10 Output: Enter a number : 1234 Total digits: 4 print('Total digits:',digits) 4 a) Differentiate elif v/s nested if else in python. elif statement Sometimes we need to test more than one condition. One way to express such a computation like that is a chained conditional. It used to test a sequence of conditions. It looks like this: if condition1: statement_1 elif condition2: statement_2 elif condition3: statement_3 .. . elif condition_N: statement_N else: statement The if statements are executed in a sequential manner. As soon as one of the conditions is True, the statement associated with that is executed, and the rest of the ladder is bypassed. If none of the conditions is True, then the final else statement will be executed. Example: A Python Program to check whether a given number is positive or negative (Type.py). n = int(input('Enter number to check: ')) if n>0: 22 Python Important Questions with Answers Ch. Vijayananda Ratnam print(n,'is positive.') elif n<0: print(n, 'is negative.') else: print('It is zero.') Output: Enter number to check: 4 4 is positive. Nested if-else statements Nested “if-else” statements mean that an “if” statement is present inside another if block. Python provides this feature as well, this in turn will help us to check multiple conditions in a given program. Syntax: if(condition): #outer if statements if(condition): #inner if statements else: statements else: statements The above syntax clearly says that the if block will contain another if block in it and so on. If block can contain ‘n’ number of if block inside it. Example: Python program to check grater among three numbers(greater.py). a,b,c =list(map(int,input('Enter three integers:').split())) if a>b: if a>c: print(a,'is big') else: print(c,'is big') else: if b>c: print(b,'is big') else: print(c,'is big') Output: Enter three integers:2 1 3 3 is big 4 b) Write a Python program to find the given year is leap year or not. Year = int(input("Enter the number: ")) 23 Python Important Questions with Answers Ch. Vijayananda Ratnam if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)): print(Year, "is a Leap Year"); else: print (Year, "is not a Leap Year") Output: Enter the number: 2000 2000 is a Leap Year 5 a) Discuss various Python Built-in functions for manipulating Strings. Built-in String methods for Strings: 1. capitalize ():Returns a proper case string i.e., with its first character capitalized and the rest of the letters are in lowercased. Example: >>> str = 'duCKdUcK Go' >>>str.capitalize() 'Duck duck go' 2. upper():Returns a string in the upper case. Symbols and numbers remain unaffected. Example: >>> str = 'duCKdUcK Go' >>>str.upper() 'DUCK DUCK GO' 3. lower():Returns a string in the lower case. Symbols and numbers remain unaffected. Example: >>> str = 'duCK dUcK Go' >>>str.lower() 'duck duck go' 4. title():Returns a string where each word starts with an uppercase character, and the remaining characters are lowercase. Example: >>> str = 'duCKdUcK Go' >>>str.title() 'Duck Duck Go' 5. swapcase():Returns a copy of the string with uppercase characters converted to lowercase and vice versa. Symbols and letters are ignored. Example: >>> str = 'duCK dUcK Go' >>>str.swapcase() 'Duck DuCk gO' 24 Python Important Questions with Answers Ch. Vijayananda Ratnam 6. ljust(): Returns the left justified string with the specified width. If the specified width is more than the string length, then the string's remaining part is filled with the specified fill_char. Example: >>> str='python' >>>str.ljust(10,'*') 'python****' 7. rjust(): Returns the right justified string with the specified width. If the specified width is more than the string length, then the string's remaining part is filled with the specified fill_char. Example: >>> str='python' >>>str.rjust(10,'*') '****python' 8. center(): Returns a new centered string of the specified length, which is padded with the specified character. The default character is space. Example: >>> str='python' >>>str.rjust(10,'*') '**python**' 9. split():method breaks the string into a list of smaller sub-strings based on some separator. The default separator is white space. Syntax string.split(separator) Example: >>>s= 'www.google.com') >>>s.split('.') ['www', 'google','com'] s='I am the student VVIT' >>>s.split() ['I', 'am', 'the', 'student', 'VVIT'] 10. join():method combines the list of strings into a single string. Syntax: separator.join(sequence) Example: >>>lst=['+91','987','654','3210'] >>> s='-'.join(lst) >>> print(s) +91-987-654-3210 25 Python Important Questions with Answers Ch. Vijayananda Ratnam 11. find() - Returns the index of the first occurrence of a substring in the given string (case-sensitive). If the substring is not found it returns -1. Syntax: string.find(substring, begin, end) Example: >>> str='Python Programming' >>>str.find('o') 4 >>>str.find('o',6,10) 9 >>>str.find('z') -1 12. index():Returns the index of the first occurrence of a substring in the given string.It willreturn ValueError Exception if the substring not found Syntax: string.index(substring,begin,end) Example: >>> str='Python Programming' >>>str.index('m') 13 >>>str.index('m',0,4) Traceback (most recent call last): File "<pyshell>", line 1, in <module> ValueError: substring not found 13. count():method returns the number of occurrences of a sub-string in the given string. Syntax: string.count(substring, begin, end) Example: >>> s='Core Python' >>>s.count('o') 2 >>>s.count('o',5,11) 1 >>>s.count('p') 0 14. replace(): method replace a sub-string in a given string with another sub-string. Syntax: string.replace(old, new [, n]) 26 Python Important Questions with Answers Ch. Vijayananda Ratnam This will replace n number of occurrences of old substring with new substring in the given string from beginning to ending. If n is omitted, all occurrences are replaced Example >>> s='There is a beautiful girl' >>>s.replace('girl','flower') 'There is a beautiful flower' >>> s='Core Python' >>>s.replace('o','a',1) 'Care Python' >>> s = 'Manager' >>>s.replace('Man','Dam') 'Damager' 15. startswith(): method returns True if the String starts with a specific substring, otherwise returns False. Example str='Core Python' >>>str.startswith('Core') True >>>str.startswith('ore') False 16. endswith(): method returns True if the String ends with a specific substring, otherwise returns False. Example str='Core Python' >>>str.endswith('on') True >>>str.endswith('one') False 5 b) Write a Python script to check the given string is Palindrome or not? str = input('Enter a string:') if str==str[::-1]: print(f"pallindrome") else: print(f"not a pallindrome") Output: Enter a string: madam Palindrome 6 a) Explain with an example, how * and + operators work with strings. 27 Python Important Questions with Answers Ch. Vijayananda Ratnam The * operator The * is called as string repetition operator that means it creates multiple copies of a string. For example, str * n repeats the string for n times. Example >>>s='Python' >>>print(s*3) 'PythonPythonPython' It also possible to repeat the part of string obtained by slicing as: >>>print(s[0:2]*3) 'PyPyPy' The + operator It is called as string concatenation operator since it concatenates the strings. We use '+' on strings to attach one string at the end of another string. Example >>>s1='Core' >>>s2='Python' >>>s3=s1+s3 # concatenate s2 at the end of s1 and store it on s3. >>>print(s3) 'CorePython' 6 b) Write a Python program that counts the number of occurrences of a letter in aString. str = input('Enter a string:') ch = input('Enter character to be found:') cnt = str.count(ch) print(f"{ ch } appears {cnt} times") Output: Enter a string: kakinada Enter character to be found:k k appears 2 times UNIT-III 1 a) Define list and explain any five list methods in python? In Python, the list is a mutable sequence type. A list object contains one or more items of different data types in the square brackets [] separated by a comma. The following declares the lists variable. Example: mylist=[] print(mylist) # Empty list 28 Python Important Questions with Answers Ch. Vijayananda Ratnam items=[1, "Jeff", "Computer", 75.50, True] print(items) Output: [] [1, 'Jeff', 'Computer', 75.5, True] Methods in Lists: Method lst.append(x) lst.insert(i,x) lst.remove(x) lst.pop() lst.index(x) lst.count(x) # List with heterogeneous data Description Appends element ‘x’ at the end of the list. Inserts element ‘x’ to the list in the position specified by i. Removesanelement‘x’ from the list. Removes last element from the list. Returns the first occurrence of element ‘x’ in the list. Returns number of occurrences of element ‘x’ in the list. Example: lst=[10,5] #List with 2 elements print('Original List:',lst) lst.append(17) #Appending 17 at end print('After adding 17: ',lst) lst.insert(1,29) #Inserting 29 at index position 1 print('After adding 29: ',lst) lst.remove(10) print('After deleting 10: ',lst) lst.pop() print('After deleting last element :',lst) pos = lst.index(5) print('5 is at position : ',pos) Output: Original List: [10, 5] After adding 17: [10, 5, 17] After adding 29: [10, 29, 5, 17] After deleting 10: [29, 5, 17] After deleting last element: [29, 5] 5 is at position: 1 1 b) Explain about different types of arguments in Python. There are 4 types of arguments in Python. They are: 1. Positional arguments 2. Default arguments 3. Keyword arguments (Named arguments) 4. Arbitrary arguments (Variable-length arguments *args and **kwargs) 29 Python Important Questions with Answers Ch. Vijayananda Ratnam 1. Positional Arguments Theseare the arguments where values get assigned to the arguments by their positionwhen the function is called. For example, the 1st positional argument must be 1st when the function is called. The 2nd positional argument needs to be 2nd when the function is called, etc. By default, Python functions are called using the positional arguments. Example: Program to add 2 numbers using positional arguments. def add(a, b): #function definition print(a + b) add(50, 10) # Output 60 #function call In the positional arguments, number and position of arguments must be matched. If we change the order, then the result may change. Also, if we change the number of arguments, we will get an error. 2. Default Arguments In a function, arguments can have default values. We assign default values to the argument using the ‘=’ (assignment) operator at the time of function definition. You can define a function with any number of default arguments. The default value of an argument will be used inside a function if we do not pass a value to that argument at the time of the function call. Due to this, the default arguments become optional during the function call. It overrides the default value if we provide a value to the default arguments during function calls. Example: Let’s define a function simple_interest() with three arguments principle, time and roi (rate_of_interest). In this function, roi is default argument with default value. If you call a function without roi, then the default values of roi is used. The principle and time parameters do not have default values and are required (mandatory) during a function call. # function with default argument roi. def simple_interest(principle, time, roi=8.5): i = (principle*time*roi)/100 print('Interest amount:', i) simple_interest(1000,5) #without passing default argument i.e. roi 30 Python Important Questions with Answers simple_interest(1000,5,12) Ch. Vijayananda Ratnam #passing default argument Output: Interest amount: 425.0 Interest amount: 600.0 If you pass value of roi argument while calling a function, then those values are used instead of default values. 3. Keyword Arguments Keyword arguments are those arguments where values get assigned to the arguments by their keyword (name) when the function is called. It is preceded by the variable name and an (=) assignment operator. It is also called asnamed argument. Example: # function with 2 keyword arguments def student(name, age): print('Student Details:', name, age) student('Tony', 20) student(name='John', age=21) student('Bell', age=19) # default function call # both keyword arguments # 1 positional and 1 keyword Output: Student Details: Tony 20 Student Details: John21 Student Details: Bell 19 4. Variable-length arguments In Python, sometimes, there is a situation where we need to pass multiple arguments to the function but we don’t know the number of arguments needed for the function in advance. Such types of arguments are called arbitrary arguments or variable-length arguments. There are two types of arguments: 1. arbitrary positional arguments (*args) 2. arbitrary keyword arguments (**kwargs) The *args and **kwargs allow you to pass multiple positional arguments or keyword arguments to a function. Arbitrary positional arguments (*args) We can declare a variable-length argument with the * (asterisk) symbol. Place an asterisk (*) before a parameter in the function definition to define an arbitrary positional argument. 31 Python Important Questions with Answers Ch. Vijayananda Ratnam We can pass multiple arguments to the function. Internally all these values are represented in the form of a tuple. Let’s understand the use of variable-length arguments with an example. Example: def percentage(*args): # function with variable-length arguments sum = 0 for i in args: sum = sum + i # get total avg = sum / len(args) # calculate average print('Average =', avg) percentage(56, 61, 73) Output: Average = 63.33 Arbitrary keyword arguments (**kwargs) The **kwargs allow you to pass multiple keyword arguments to a function. Use the **kwargs if you want to handle named arguments in a function. Keyword arguments passed to a kwargs are accessed using key-value pair (same as accessing a dictionary in Python). Example: def percentage(**kwargs): # function with variable-length keyword arguments sum = 0 for k,v in kwargs.items(): sub_name = k # get argument name sub_marks = v # get argument value print(sub_name, "=", sub_marks) sum+=v print ('Percentage=',sum/3) # pass multiple keyword arguments percentage(Maths=56, English=61, Science=73) Output: Maths = 56 English = 61 Science = 73 Percentage= 63.3 2 a) What are built-in dictionary functions? Explain. A dictionary represents a group of elements arranged in the form of key-value pairs. The first element is considered as “key‟ and the immediate next element is taken as its 32 Python Important Questions with Answers Ch. Vijayananda Ratnam “value‟. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted in curly braces { }. d= {"Regd.No": 511, "Name":"Tony", "Branch": "CSE" } Here, the name of dictionary is “d”. The first element in the dictionary is a string “Regd.No”. So, this is called “key”. The second element is 556 which is taken as its “value”. Methods with example: 1. keys():returns a list of all the available keys in the dictionary. d={'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} print(dict.keys()) Output: dict_keys(['Name', 'Rollno', 'Dept', 'Percentage']) 2. values( ):returns list of dictionary's values from the key value pairs. d={'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} print(dict.values()) Output dict_values(['Harry', 530, 'CSE', 97]) 3. items():returns a list of dictionary's (key, value) as tuple. d={'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} print(dict.items()) Output: dict_items([('Name', 'Harry'), ('Rollno', 530), ('Dept', 'CSE'), ('Percentage', 97)]) 4.pop(key): Removes and returns the value of specified key. d={'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} d.pop('Percentage') print(d) Output: {'Name': 'Harry', 'Rollno': 530, 'Dept': 'CSE'} 5. copy():returns a shallow copy of dictionary. d = {‘Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} new_d=d.copy() print(new_d) Output: {‘Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} 6. clear(): Removes all key-value pairs from dictionary ‘d’. d = {‘Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} 33 Python Important Questions with Answers Ch. Vijayananda Ratnam d.clear() print(d) Output {} 7. get(k[,v]):Returns the value associated with key ‘k’. If key is not found, it returns ‘v’.If key is not found and ‘v’ is not specified , it returns ‘None’. d = {'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} print('Name: ', d.get('Name')) print('Age: ', d.get('Age',21)) print('Age: ', d.get('Age')) Output: Name: Harry Age: 21 Age: None 8. update():inserts new item to the dictionary. d = {'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97} d.update({'Age':21}) print(d) Output {'Name':'Harry','Rollno':530,'Dept':'CSE','Percentage':97, 'Age': 21} 2 b) Describe anonymous functions with examples. Anonymous (or) Lambda Function Sometimes we need to declare a function without any name. The nameless property function is called an anonymous or lambda function. Lambda functions are single-line functions that can take multiple arguments but have a single expression and return value. There are three main components of the lambda function: 1. keyword: lambda 2. arguments before the colon 3. expression/return statements after colon Syntax: lambda: argument_list:expression 34 Python Important Questions with Answers Ch. Vijayananda Ratnam When we define a function using the lambda keyword, the code is very concise so that there is more readability in the code. A lambda function can have any number of arguments but return only one value after expression evaluation. Let’s see an example to find sum of three numbers using lambda function >>>sum = lambda a,b,c:a+b+c >>>print(sum(1,2,3)) 6 We are not required to write explicitly return statements in the lambda function because the lambda internally returns expression value. Lambda functions are more useful when we pass a function as an argument to another function. We can also use the lambda function with built-in functions such as filter, map, and reduce because this function requires another function as an argument. 3 a) Explain various operations performed on Lists? In Python, the list is a mutable sequence type. A list object contains one or more items of different data types in the square brackets [] separated by a comma. The following declares the lists variable. Operations on Lists: 1. Creating a List: Creating a list is as simple as putting different comma-separated values between square brackets. student = [511, “Tony”, 84, 96, 84, 75, 84 ] We can create empty list without any elements by simply writing empty square brackets as: student=[ ] 2. Accessing Values in list: To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. To view the elements of a list as a whole, we can simply pass the list name to print function. Example: student = [511, “Tony”, 84, 96, 84, 75, 84 ] print(student) print(student[0]) # Access 0th element print(student[0:2]) # Access 0th to 1st elements print(student[2: ]) # Access 2nd to end of list elements print(student[ :3]) # Access starting to 2nd elements print(student[ : ]) # Access starting to ending elements print(student[-1]) # Access last index value print(student[-1:-7:-1]) # Access elements in reverse order 35 Python Important Questions with Answers Ch. Vijayananda Ratnam Output: [556, “Tony”, 84, 96, 84, 75, 84] Tony [556, “Tony”] [84, 96, 84, 75, 84] [556, “Tony”, 84] [556, “Tony”, 84, 96, 84, 75, 84] 84 [84, 75, 84, 96, 84, “Tony”] 3. Updating and deleting lists: Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the elements of a list depending upon our requirements. Appending an element means adding an element at the end of the list. To, append a new element to the list, we should use the append() method. Example: lst=[1,2,4,5,8,6] print(lst) # [1,2,4,5,8,6] lst.append(9) print(lst) # [1,2,4,5,8,6,9] Updating an element means changing the value of the element in the list. This can be done by accessing the specific element using indexing or slicing and assigning a new value. Example: lst=[4,7,6,8,9,3] print(lst) # [4,7,6,8,9,3] lst[2]=5 # Updates 2nd element in the list print(lst) # [4,7,5,8,9,3] lst[2:5]=10,11,12 # Update 2nd element to 4th element in the list print(lst) # [4,7,10,11,12,3] Deleting an element from the list can be done using ‘del’ statement. The del statement takes the position number of the element to be deleted. Example: lst=[5,7,1,8,9,6] del lst[3] # Delete 3rd element from the list i.e., 8 print(lst) # [5,7,1,9,6] Note:If we want to delete entire list, we can give statement like del lst. 4. Concatenation of Two lists: We can simply use ‘+’ operator on two lists to join them. For example, ‘x’ and ‘y’ are two lists. If we write x+y, the list ‘y’ is joined at the end of the list ‘x’. 36 Python Important Questions with Answers Ch. Vijayananda Ratnam Example: x=[10,20,32,15,16] y=[45,18,78,14,86] print(x+y) # [10,20,32,15,16,45,18,78,14,86] 5. Repetition of Lists: We can repeat the elements of a list ‘n’ number of times using ‘*’ operator. Example: x=[10,54,87] print(x*2) # [10,54,87,10,54,87] 6. Membership in Lists: We can check if an element is a member of a list by using ‘in’ and ‘not in’ operator. If the element is a member of the list, then ‘in’ operator returns True otherwise returns False. If the element is not in the list, then “not in” operator returns True otherwise returns False. Example: x=[10,20,30,45,55,65] a=20 print(a in x) # True a=25 print( a in x) # False a=45 print( a not in x) # False a=40 print( a not in x) # True 7. Aliasing and Cloning Lists: Giving a new name to an existing list is called ‘aliasing’. The new name is called ‘alias name’. To provide a new name to this list, we can simply use assignment operator (=). Example: x = [10, 20, 30, 40, 50, 60] y=x # x is aliased as y print(x) # [10,20,30,40,50,60] print(y) # [10,20,30,40,50,60] x[1]=90 # modify 1st element in both lists print(x) # [10,90,30,40,50,60] print(y) # [10,90,30,40,50,60] Obtaining exact copy of an existing object (or list) is called “cloning‟. To Clone a list, we can take help of the slicing operation [:]. Example: x = [10, 20, 30, 40, 50, 60] 37 Python Important Questions with Answers Ch. Vijayananda Ratnam y=x[:] # x is cloned as y print(x) # [10,20,30,40,50,60] print(y) # [10,20,30,40,50,60] x[1]=90 # modify 1st element in x print(x) # [10,90,30,40,50,60] print(y) # [10,20,30,40,50,60] 3 b) Discuss in detail about recursion along with costs and benefits. Recursion is the process of defining something in terms of itself. A Function that calls itself again and againis called recursive function.Each recursive function has two parts: Base Case Recursive Structure Any recursive function will look like Base Case: The smallest version of the problem for which we already know the solution or a terminating condition to stop a recursive function from executing endlessly. Recursive Structure: Finding the solution to a problem via the solution of its smaller sub-problems. Here function must call itself to break the current problem down to a simpler level. For example, print numbers from N to 1 in decreasing order def countdown(n): if n<1: #Base case return print(n) countdown(n-1) #Recursive Structure n = int(input('Enter a number:')) countdown(n) Costs/Disadvantages A recursive program has greater space requirements than an iterative program as each function call will remain in the stack until the base case is reached. It also has greater time requirements because each time the function is called, the stack grows and the final answer is returned when the stack is popped completely. 38 Python Important Questions with Answers Ch. Vijayananda Ratnam Benefits/Advantages: For a recursive function, you only need to define the base case and recursive case, so the code is simpler and shorter than an iterative code. Some problems are inherently recursive, such as Graph and Tree Traversal. 4 a) What is package in Python? Explain, how can you use package in your program with an example code? A python package is a collection of modules. (Or) A package is a directory of Python modules that contains an additional __init__.py file, which distinguishes a package from a directory that is supposed to contain multiple python scripts. Advantages: 1. Naming conflicts can be solved easily. 2. We can identify our components uniquely. 3. Improves the Modularity of the application. 4. The readability of the application will be improved. 5. Maintainability of the application will be improved. For example, Create and access a user defined package ArithmeticPackage where the package contains a module named ArithmeticDemo, which in turn contains a methods called sumtwo() , subtwo(), multwo() and divtwo() which takes two numbers as parameter and returns the result. 39 Python Important Questions with Answers Ch. Vijayananda Ratnam To create a package in Python, we need to follow these three simple steps: 1. First, we create a directory and give it a package name, preferably related to its operation. 2. Then we put the classes and the required functions in it. 3. Now we can use the package that is created. To do this make a python file in the same directory where package is located and add code to it. 4. Now execute the program. ArithmeticDemo.py Program in ArithmeticPackage Folder def sumtwo(a,b): return a+b def subtwo(a,b): return a-b def multwo(a,b): return a*b def divtwo(a,b): return a/b Usage of Module in Package: import ArithmeticDemo as ad print(ad.sumtwo(10,20)) print(ad.subtwo(20,10)) print(ad.multwo(20,10)) print(as.divtwo(20,10)) Output: 30 10 200 2.0 4 b) Differentiate list vs dictionary in terms of indexing Property Definition List List refers to the collection of index-value pairs like that array in C. Creation List is initialized with [], and elements are separated by ','. Accessing List values can be accessed by numeric indices. 40 Dictionary Dictionary refers to the hashed structure of various pairs like key-value pairs. Dictionary is created by placingelements in {}, data is added askey:value pair, and each pair is separated by ','. Dictionary items can be accessed by using key:values. Key valuescan be of any data type. Python Important Questions with Answers Ch. Vijayananda Ratnam Ordering of Elements The order of elements in the list is always maintained. Properties List is ordered, mutable, and allows duplicate values. Store the data Lists are used to store the data, which should be ordered and sequential. We don’t have any guarantee of maintaining the order of the available elements. Dictionary is unordered and mutable, but the dictionarydoesn't allow duplicate values as keys. It stores large amounts of data for easy and quick access. 5 a) Explain about built-in functions of tuple. These are an ordered collection of elements of different data types. We represent them by writing the elements inside the parenthesis separated by commas. Tuples are ordered and immutable. We access elements by using the index starting from zero. For example, >>>t = (22, 45, 23, 78, 6.89) >>>print(t) (22, 45, 23, 78, 6.89) Tuple Functions: 1. len(): returns the number of elements present in a tuple. For example, >>>t = (22, 45, 23, 78, 6.89) >>>len(t) 5 2. count():returnsthetotal number of occurrences of an element in a tuple. For example, >>>t = (22, 45, 23, 78, 22, 22, 6.89) >>>t.count(22) 3 >>>t.count(54) 0 3. index(): returns the position of the first occurrence of an element in a tuple if it found otherwise returns ValueErrori.e. element not found. For example, >>>t = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) >>> print(tup.index(45)) 2 41 Python Important Questions with Answers Ch. Vijayananda Ratnam >>> print(tup.index(33)) ValueError: tuple.index(x): x not in tuple 4. sorted( ): returns sorted list an output. Moreover, it does not make any changes to the original tuple. For example, >>> t = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) >>> sorted(t) [1, 2, 2.4, 3, 4, 22, 45, 56, 890] 5. min():returns the smallest element in the tuple. For example, >>> t = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) >>> min(t) 1 6. max():returns largest element in the tuple. For example, >>> t = (22, 3, 45, 4, 2.4, 2, 56, 890, 1) >>> max(t) 890 7. sum():returns sum of all the elements present in the tuple. For example, >>> t= (22, 3, 45, 4, 2, 56, 890, 1) >>> sum(t) 1023 5 b) Write a brief note on PIP. Explain installing packages via PIP. PIP is the package manager for python. In other words, it is a tool that allows us to install the python packages and dependencies that aren’t distributed as part of the Python's Standard Library. Pip has become the standard package manager for Python. Installing PIP Python 2.7.9 and later (python2 series), and Python 3.4 and later (python 3 series) already comes with pip. If you are using latest Python version, then pip comes pre-installed with it.You can verify if pip is available by running the following command in your console: C:/> pip --version If you get an output like this 42 Python Important Questions with Answers Ch. Vijayananda Ratnam pip 20.2.3 from c:\python39\lib\site-packages\pip (python 3.9) Installing a Package If you’re using Windows, you’ll be able to install a Python package by opening the Windows Command Prompt, and then typing this command: pip install package_name For example, to install the Pandas package, type the following command in the Command Prompt: pip install pandas Uninstall a Package To uninstall a package using PIP, simply type the following command in the Command Prompt: pip uninstall package_name For example, to uninstall the Pandas package, type the following command in the Command Prompt: pip uninstall pandas 6 a) Define Module? What are the two ways of importing a module?Explain. Modules: A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name. For instance, create a file called fibo.py in the current directory with the following contents: # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result Now enter the Python interpreter and import this module with the following command: >>>import fibo 43 Python Important Questions with Answers Ch. Vijayananda Ratnam This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name, you can access the functions: >>>fibo.fib(10) 112358 >>> fibo.fib2(10) [1, 1, 2, 3, 5, 8] >>>fibo.__name__ 'fibo' from statement: A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. (They are also run if the file is executed as a script.) Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname. Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module‟s global symbol table. There is a variant of the import statement that imports names from a module directly into the importing module‟s symbol table. For example: from .. import statement: >>> from fibo import fib, fib2 >>>fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined). There is even a variant to import all names that a module defines: >>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 6 b) Explain about higher order functions with examples. In Python, higher-order functions are functions that can accept other functions as arguments, return functions as results, or both. 44 Python Important Questions with Answers Ch. Vijayananda Ratnam In Python, functions are considered first-class objects, meaning they can be assigned to variables, passed as arguments to other functions, and returned as values from functions. There are 3 different functions, namely: 1. map() 2. filter() 3. reduce(). 1. map() function:Itis a built-in Python function that allows you to apply a specific function to each item in an iterable (such as a list or a tuple) and returns an iterator that contains the results. It provides a convenient way to perform operations on all elements of a collection without the need for explicit loops.The general syntax of the map() function is as follows: map(function, iterable) Where: function: A function or lambda function that you want to apply to each element of the iterable. iterable: An iterable object (e.g., list, tuple, etc.) containing the elements to which the function will be applied. Consider the following example, where we have a list of numbers, and we want to square each number in the list: >>>nos = [1, 2, 3, 4, 5] >>>squares= list(map(lambda x:x**2, nos)) >>> print(squares) [1, 4, 9, 16, 25] 2. filter( ) function:Itis a built-in Python function that allows you to filter elements from an iterable based on a specified conditionand returns new iterable with the filtered elements.The general syntax of the map() function is as follows: filter(function, iterable) Consider the following example, where we have a list of numbers, and we want to return all the even numbers in the list: >>>nos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>enos= list(filter(lambda x:x%2==0, nos)) >>> print(enos) [2, 4, 6, 8, 10] 3. reduce( ) function:Itis a built-in Python function that allows you to filter elements from an iterable based on a specified conditionand returns new iterable with the filtered elements.The general syntax of the map() function is as follows: 45 Python Important Questions with Answers Ch. Vijayananda Ratnam filter(function, iterable) Consider the following example, where we have a list of numbers, and we want to return all the even numbers in the list: >>>nos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>enos= list(filter(lambda x:x%2==0, nos)) >>> print(enos) [2, 4, 6, 8, 10] UNIT – IV 1 a) Demonstrate the creating class in python with an example. What is Class in Python? The class is a user-defined data structure that binds the data members and methods into a single unit. Class is a blueprint or code template for object creation. Using a class, you can create as many objects as you want. For example, if we design a class based on the states and behaviours of a Person, then States can be represented as instance variables and behaviours as class methods. Create a Class in Python In Python, class is defined by using the class keyword. The syntax to create a class is given below. class class_name: <statement 1> <statement 2> . . <statement N> Where, class_name: It is the name of the class statements: Attributes and methods Define a class in Python In this example, we are creating a Person Class with name, gender, and profession instance variables and show as a method. class Person: def __init__(self, name, gender, profession): # data members (instance variables) self.name = name self.gender = gender 46 Python Important Questions with Answers Ch. Vijayananda Ratnam self.profession = profession # Behavior (instance methods) def show(self): print('Name:', self.name, 'Gender:', self.gender, 'Profession:', self.profession) def work(self): print(self.name, 'working as a', self.profession) 1 b) Explain the procedure to read and write from the file. In Python, any file operations can be performed in the following three steps: Procedure: Step 1: Open the file using the open() function. Step 2: Perform read, write, append operations. Step 3: Close the file. Reading File File object includes the following methods to read data from the file. 1. read(chars): reads the specified number of characters starting from the current position. 2. readline(): reads line by line from file. 3. readlines(): reads all lines until the end of file and returns a list object. The following C:\myfile.txt file will be used in all the examples of reading and writing files. C:\myfile.txt first line. second line. third line. The following example performs the read operation using the read() method. f = open('myfile.txt','r') # opening a file st= f.read() # reading a file print(st) f.close() # closing file object Output: first line. second line. third line. Writing to a File The file object provides the following methods to write to a file. 47 Python Important Questions with Answers Ch. Vijayananda Ratnam 1. write(s): Write the string s to the stream and return the number of characters written. 2. writelines(lines): Write a list of lines to the stream. Each line must have a separator at the end of it. Example: The following example creates a new file if it does not exist or overwrites to an existing file. f = open('myfile.txt','w') f.write("Hello") # Writing to file f.close() Note: It opens myfile.txt in write mode and overrides the existing contents of a file with ‘Hello’. 2 a) Discuss about constructors in python. What is Constructor in Python? In OOP, A constructor is a special method used to create and initialize an object of a class. This method is defined in the class. The constructor is executed automatically at the time of object creation. Syntax of a constructor def __init__(self): # body of the constructor In Python, we have the following types of constructors. 1. Non-parametrized constructor 2. Parameterized constructor 1. Non-Parametrized Constructor A constructor without any arguments is called a non-parameterized constructor. This type of constructor is used to initialize each object with default values. This constructor doesn’t accept the arguments during object creation. Instead, it initializes every object with the same set of values. For example, consider a college that has name and address. In this case, while creating object, we need to initialize the college name, address with some default values. In such cases, use the non - parameterized constructor. class College: def __init__(self): self.name = "VVIT" self.address = "Nambur" # no-argument constructor # a method for printing data members 48 Python Important Questions with Answers Ch. Vijayananda Ratnam def show(self): print('Name:', self.name, 'Address:', self.address) clg = College() clg.show() # creating object of the class # calling the instance method using the object Output Name: VVIT Address: Nambur 2. Parameterized Constructor A constructor with defined parameters or arguments is called a parameterized constructor. We can pass different values to each object at the time of creation using a parameterized constructor. The first parameter to constructor is self that is a reference to the being constructed, and the rest of the arguments are provided by the programmer. A parameterized constructor can have any number of arguments. For example, consider a college that contains hundreds of employees. In this case, while creating each employee object, we need to pass a different name, age, and salary. In such cases, use the parameterized constructor. Example: class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary # Parameterized constructor def show(self): print(self.name, self.age, self.salary) # creating object of the Employee class emp1 = Employee('Anand', 32, 55000) emp1.show() emp2= Employee('Vijay', 25, 85000) emp2.show() Output: Anand 32 55000 Vijay 25 85000 2 b) Write a python program to copy the contents of one file to another. 49 Python Important Questions with Answers Ch. Vijayananda Ratnam s_file = input("Enter name of the source file: ") d_file = input("Enter name of the destination file: ") f1 = open(s_file, "r") f2 = open(d_file, "w") txt = f1.read() f2.write(txt) print("File copied successfully") f1.close() f1.close() Output: Enter name of the source file: file1.txt Enter name of the destination file: file2.txt File copied successfully!!! 3 a) Explain about different access modifiers in python with example programs. These access modifiers define how the members of the class can be accessed outside the class.Access modifiers play an important role to protect the data from unauthorized access as well as protecting it from getting manipulated. Python makes the use of underscores to specify the access modifier for a specific data member and member function in a class. There are three types of access specifiers or access modifiers 1. Public 2. Private 3. Protected 1. Public Access Modifier All the variables and methods (member functions) in python are by default public which means they can be accessed from anywhere outside or inside the class. Any instance variable in a class followed by the ‘self’ keyword i.e.,self.var_name is public accessed. syntax: self.var_name Example: class Student: def __init__(self, age, name): self.name = name self.age = age std = Student("Tony", 21) print(std.name) print(std.age) # constructor is defined # public Attribute # public Attribute # Object creation 50 Python Important Questions with Answers Ch. Vijayananda Ratnam Output: Tony 21 2. Private Access Modifier These members are only accessible from within the class. We cannot access them outside of the class. In python, private members and methods are declared using double underscores(‘__’) as prefix before their names. It is not possible to inherit the private members of any class (parent class) to derived class (child class). Syntax: self.__var_name Example: class Student: def __init__(self, name): self.name = name self.__adhaar = 98765432102 # public Attribute # private Attribute def show(self): print(self.name) print(self.__adhaar) std = Student("Tony") std.show() print(std.__adhaar) Output: Tony 98765432102 AttributeError: 'Student' object has no attribute '__adhaar' 3. Protected Access Modifier The members declared as Protected are accessible from outside the class and its child or subclass. In python, protected members and methods are declared using single underscore(‘_’) as prefix before their names. Syntax: self._var_name Example: class Employee: def __init__(self, name, sal): self._name = name self._sal = sal # Base class # protected attribute # protected attribute 51 Python Important Questions with Answers Ch. Vijayananda Ratnam class Hr(Employee): #Derived class def task(self): print('We manage employees') hr = Hr('Vijay',10000) print(hr._name) print(hr._sal) Output: Vijay 12000 3 b) How do you manipulate a file pointer in Python? Explain with an example. The seek() and tell() methods are used for manipulating the current position of the file pointer in a file. 1. seek() method The seek() is used to move the file pointer from one location to another location within the file. You can use it to reposition the file pointer to a specific location, so that subsequent reads or writes will start from that position. Syntax: file.seek(offset) The offset can be positive (to move the pointer forward) or negative (to move the pointer backward) When we open a file initially the file pointer position is at 0 i.e. beginning of file. The seek() method returns the new file pointer position by adding an offset value to the current file pointer position. Example: f = open("myfile.txt", "r") # assume file has following 3 lines of data # first line. # second line. # third line. # Move the fp 12 positions ahead from current position f.seek(12) # read 6 bytes print(f.read(6)) f.close() 52 Python Important Questions with Answers Ch. Vijayananda Ratnam Output: second 2. tell() method The tell() method returns the current position of the file pointer, in bytes from the start of the file. The position is an integer that represents the number of bytes from the beginning of the file. Syntax: file.tell() Example: f = open("myfile.txt", "r") # assume file has following 3 lines of data #Move the file pointer to the 6th character f.seek(6) print('Current position: ',f.tell()) f.close() Output: Current position: 6 4 a) Briefly explain various types of inheritance with an example. Inheritance means acquiring the properties and methods of one class to another class. (Or) It is the concept of deriving a new class from an existing class. The class which inherits another class is known as the Child class, while the class which is inherited by other classes is called as the Parent class. Python supports five types of Inheritance: 1. Single Inheritance 2. Multiple Inheritance 3. Hierarchical Inheritance 4. Multilevel Inheritance 5. Hybrid Inheritance 1. Single Inheritance: When one child class is derived from only one parent class. This is called Single inheritance. This means that there is only one subclass that is derived from one superclass. Single inheritance is usually declared as follows: class Child_class_name(Parent_class_name): #Child class specific code 53 Python Important Questions with Answers Ch. Vijayananda Ratnam Example: Python program to that illustrates Single Inheritance class Employee: #Base class def __init__(self): self.eno=0 self.ename='' def input(self): self.eno=int(input('Enter employee no:')) self.ename=input('Enter employee name:') class Salary(Employee): def __init__(self): Employee.__init__(self) self.sal=0 #Derived class def read(self): self.sal=int(input('Enter Salary:')) def show_details(self): print('EMP DETAILS\n---------------') print('Emp No: ',self.eno) print('Emp Name: ',self.ename) print('Salary: ',self.sal) s = Salary() s.input(); s.read(); s.show_details(); Output: Enter employee no:1234 Enter employee name:Vijay Enter Salary:15000 EMP DETAILS --------------Emp No: 1234 Emp Name: Vijay 54 Python Important Questions with Answers Ch. Vijayananda Ratnam Salary: 15000 2. Multiple Inheritance: When a class can be derived from more than one base class is called Multiple inheritance. Multiple inheritance is usually declared as follows: class Child_class_name(Parent_class_name1, Parent_class_name2): #Child class specific code Where A and B are Base classes, C is Derived class Example: Python program to that illustrates Multiple Inheritance class Mother: # Base class1 m_name = "" def mother(self): print(self.m_name) class Father: f_name = "" def father(self): print(self.f_name) # Base class2 class Son(Mother, Father): # Derived class def parents(self): print("Father :", self.f_name) print("Mother :", self.m_name) # Driver's code s1 = Son() s1.f_name = "Tony" s1.m_name = "Cathy" s1.parents() Output: Father : Tony Mother : Cathy 3. Multilevel Inheritance: In multilevel inheritance, one class is derived from another 55 Python Important Questions with Answers Ch. Vijayananda Ratnam class which in turn derived from another base class. Multi-level inheritance is usually declared as follows: class Child_class_name(Parent_class_name): #Child class specific code Where A is Base classes, C is Derived class and B is an Intermediate class Example: Python program to that illustrates Multi-level Inheritance. class Car: # Base class1 def __init__(self): print('Vehicle Type: Car') class Maruti(Car): def __init__(self): Car.__init__(self) print('Company: Maruti') # Intermediate class def speed(self): print('Speed: 80 KMPH') class Maruti800(Maruti): def __init__(self): Maruti.__init__(self) print('Model: Maruti 800') # Child class def speed(self): print('Speed: 120 KMPH') # Driver's code m = Maruti800() m.speed() Output: Vehicle Type: Car Company: Maruti 56 Python Important Questions with Answers Ch. Vijayananda Ratnam Model: Maruti 800 Speed: 120 KMPH 4. Hierarchical Inheritance: When more than one class is derived from a single base this type of inheritance is called Hierarchical inheritance. Hierarchical inheritance is usually declared as follows: class Child_class_name1 (Parent_class_name): #Child class specific code class Child_class_name2 (Parent_class_name): #Child class specific code class Child_class_name3 (Parent_class_name): #Child class specific code Where A is Base classes and B, C & D are Derived classe. Example: Python program to that illustrates Multi-level Inheritance. class Vehicle: # Base class def __init__(self): print('Vehicle Type: Motor Vehicle') class TwoWheeler(Vehicle): def __init__(self): Vehicle.__init__(self) print('It has two wheels') # Child class1 class ThreeWheeler(Vehicle): def __init__(self): Vehicle.__init__(self) print('It has three wheels') # Child class2 class FourWheeler(Vehicle): def __init__(self): Vehicle.__init__(self) print('It has four wheels') # Child class3 # Driver's code 57 Python Important Questions with Answers Ch. Vijayananda Ratnam two = TwoWheeler() print('------------') two = ThreeWheeler() print('------------') four = FourWheeler() Output: Vehicle Type: Motor Vehicle It has two wheels -----------Vehicle Type: Motor Vehicle It has three wheels -----------Vehicle Type: Motor Vehicle It has four wheels 5. Hybrid Inheritance:Combination of two or more types of inheritance is called hybrid inheritance. Example: Python program to that illustrates Hybrid Inheritance. class University: def __init__(self): self.univ = "JNTUK" def display(self): print(f"University: {self.univ}") class Course(University): def __init__(self): University.__init__(self) self.course = "B.Tech" def display(self): print(f"Course: {self.course}") University.display(self) class Branch(University): def __init__(self): 58 Python Important Questions with Answers Ch. Vijayananda Ratnam self.branch = "ECE" def display(self): print(f"Branch : {self.branch}") class Student(Course, Branch): def __init__(self): self.name = "Tony" Branch.__init__(self) Course.__init__(self) def display(self): print(f"Student Name: {self.name}") Branch.display(self) Course.display(self) # Object Instantiation: ob = Student() # Object named ob of the class Student. print() ob.display() # Calling the display method of Student class. Output: Student Name: Tony Branch : ECE Course :B.Tech University : JNTUK 4 b) Explain about write() and writelines() functions in Python. 1. write() function The write() method writes a specified text to the file. Where the specified textwill be inserted depends on the file mode and stream position. When we open a file in write mode i.e., "w" mode then the text will be inserted at the current file stream position. The default stream position is beginning of the file i.e., 0. When we open a file in append mode i.e., "a" mode then the text will be inserted at the current file stream position. The default stream position is at the end of the file. Syntax: file.write(string) Here, passed parameter is the content to be written into the opened file. Example 1: f = open("myfile.txt", "w") f.write("\nGood Morning.") f.close() 59 Python Important Questions with Answers Ch. Vijayananda Ratnam Note : It creates myfile.txt and write Good Morning at beginning of file. 2. writelines() function The writelines() method writes the contents of a list to the file. Since the newline character is not automatically written to the file, it must be provided as a part of the string. Syntax: file.writelines(list) Example: f = open("myfile.txt", "a") f.writelines(["\nGood Afternoon",”\nGood Night”]) f.close() Note: It opens myfile.txt in append mode and write Good Afternoon and Good Night at end of the file. 5 a) How to implement method overriding in Python? Explain. Method overriding means providing an alternative method definition to the existing base class method in child class. (Or) Method overriding is the ability of a subclass to provide a different implementation of a method that is already defined in its superclass. The method in child class is called overriding method and method in base class is called overridden method. Example: Python program that illustrates Method overriding. class Animal: name = "" def eat(self): print("I can eat") class Dog(Animal): def eat(self): #Overridden method # inherit from Animal #Overriding method 60 Python Important Questions with Answers Ch. Vijayananda Ratnam print("I like to eat bones") labrador = Dog() labrador.eat() Output: I like to eat bones. In the above example, the same method eat() is present in both the Dog class and the Animal class.Now, when we call the eat() method using the object of the Dog subclass, the method of the Dog class is called.This is because the eat() method of the Dog subclass overrides the same method of the Animal superclass. 5 b) Explain the prototypes of read(), readline() and readlines() functions in Python. Python allows you to read the contents of a file using methods such as: 1. read() 2. readline() 3. readlines() 1. read() function The read() method returns the specified number of bytes from the file and return it as string. Syntax file.read(size) where is size is the number of bytes to be returned. Default is -1 which means the whole file. Example:Read the contents of the file "myfile.txt" f = open("myfile.txt", "r") txt = f.read(10) print(txt) f.close() Output: first line 2. readline() function The readline() method reads a single line from a file and returns it as a string. This means that if you use readline(), you can read the contents of a file line by line, which can be useful for processing large files that do not fit in memory. Syntax: file.readline() 61 Python Important Questions with Answers Ch. Vijayananda Ratnam Example: Read the contents of the file “myfile.txt”using readline() method. f = open("myfile.txt", "r") line = f.readline() while line: print(line.strip()) line = f.readline() Output: first line second line third line 3. readlines() function The readlines() methodreads the entire contents of a file and returns it as a list of strings, where each element of the list is a single line of the file. Syntax: file.readlines() Example: Read the contents of the file “myfile.txt” using readlines() method. f = open("myfile.txt", "r") lines = f.readlines() print(lines) Output: ['first line\n', 'second line\n', 'third line'] UNIT-V 1 a) Explain try..except block in detail. (or) Describe in detail how exceptions are handled in Python. Give relevantexamples. An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions.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. Syntax Here is simple syntax of try..except...else blocks – try: place your code here; 62 Python Important Questions with Answers Ch. Vijayananda Ratnam except Exception1: If there is Exception1, then execute this block. except Exception2: If there is Exception2, then execute this block. else: If there is no exception then execute this block. If the exception occurs, the program flow is transferred to the except: block. The statements in the except: block is meant to handle the cause of the exception appropriately. otherwise except block is skipped. Example: Program that raises IOError when the required file is not available on the disk. try: f_name = input('Enter file name:') f = open(f_name, "r") txt = f.read() print(txt) except IOError: print(f_name," is not found.") Output: Enter file name: myfile.txt myfile.txt is not found. 1 b) Demonstrate GUI based programming with an example. (Or) Discuss the importance of GUI based programs with an example. A Graphical User Interface (GUI) is more user-friendly and easier to interact with. They are very attractive and visually impactful, making users more convenient for usage.They do not need prior computer skills or knowledge to perform computer operations. Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below. Tkinter −Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter. wxPython − This is an open-source Python interface for wxWindows http://wxpython.org. JPython −JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org. Tkinter Programming Tkinter is the standard GUI library for Python. Python when combined with Tkinter 63 Python Important Questions with Answers Ch. Vijayananda Ratnam provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps − Step 1:Import the tkinter module. Step 2:Create the GUI application main window. Step 3:Add one or more widgets to the GUI application. Step 4:Enter the main event loop to take action against each event triggered by the user. Example import tkinter as tk win = tk.Tk() # Code to add widgets win.mainloop() This would create a following window − 2 a) How to handle multiple exceptions in Python? Explain with an example. To catch multiple exceptions individually, we can write multiple catch blocks. Syntax: try: # try block statement except Exception1: Statements except Exception2: Statements . . . except ExceptionN: Statements The other way is to use a single except block and write all the exceptions as a tuple inside parenthesis as: 64 Python Important Questions with Answers Ch. Vijayananda Ratnam except (Exceptionclass1, Exceptionclass2,.. ): Statements Example: Program for handling multiple exceptions separately try: l = [10, 30, 40] r = l[4]/0 print(r) except IndexError: print('Index out of range') except ZeroDivisionError: print('Denominator should not be zero') except: print('Unknow Error') Output: Index out of range Example: Program that handles multiple Exception in a single except block. import math as m try: r = m.exp(1000) print(r) except (ZeroDivisionError,ValueError,OverflowError): print('Arithmetic Error') Output: Arithmetic Error 2 b) Explain about Radiobutton widget in tkinter. How to create two radiobutton sets (one for gender and another for Indian or not) on the same canvas. The Radiobutton widget is used to implement one-of-many selection in the python application. It shows multiple choices to the user out of which, the user can select only one of them. Syntax w = Radiobutton(master, options) Some of most frequently used options are: 1. text - The text to be displayed on the radiobutton. 2. value - The value of each radiobutton is assigned to the control variable when it is turned on by the user. 3. variable - It is the control variable which is used to keep track of the user's choices. It is shared among all the radiobuttons. 4. Command - This option is set to the procedure which must be called every-time when the state of the radiobutton is changed. 65 Python Important Questions with Answers Ch. Vijayananda Ratnam Example: import tkinter as tk win = tk.Tk() win.title('Radios') win.geometry('300x200') r1 = tk.IntVar() r2 = tk.IntVar() lbl1 = tk.Label(win,text='Gender:') lbl1.grid(row=0,column=0) rbtn1 = tk.Radiobutton(win,text="Male",variable=r1,value=1) rbtn1.grid(row=0,column=1) rbtn2 = tk.Radiobutton(win,text="Female",variable=r1,value=2) rbtn2.grid(row=1,column=1) lbl2 = tk.Label(win,text='Nationality:') lbl2.grid(row=2,column=0) rbtn3 = tk.Radiobutton(win,text="Indian",variable=r2,value=3) rbtn3.grid(row=2,column=1) rbtn4 = tk.Radiobutton(win,text="Other",variable=r2,value=4) rbtn4.grid(row=3,column=1) win.mainloop() Output: 3 a) Explain in detail about creating user-defined exceptions with the help of a sample program. Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions which are called “User-defined exceptions” or “Custom exceptions‟. 66 Python Important Questions with Answers Ch. Vijayananda Ratnam Steps required to create Custom exception Step 1:Since all exceptions are classes, the programmer is supposed to create his own exception as a class. Also, he should make his class as a sub class to the in-built “Exception” class. Syntax: class MyException(Exception): def __init__ (self, arg): self.msg = arg Here, MyException class is the sub class for “Exception‟ class. This class has a constructor where a variable “msg‟ is defined. This “msg‟ receives a message passed from outside through “arg‟. Step 2: The programmer can write his code; maybe it represents a group of statements or a function. When the programmer suspects the possibility of exception, he should raise his own exception using “raise‟ statement as: raise MyException(‘message’) Here, raise statement is raising MyException class object that contains the given “message”. Step 3. The programmer can insert the code inside a “try” block and catch the exception using“except‟ block as: try: code except MyException as ex: print(me) Here, the object “ex‟ contains the message given in the raise statement. All these steps are shown in below program. Example: Python program to create an Exception named "InsufficientFundsException" and raise it when Bank Account having balance lessthan 2000. class InsufficientFundsException(Exception): def init (self, msg): self.msg = msg def check(dict): for k,v in dict.items(): if v<2000: raise InsufficientFundsException ("Balance is less in the account of "+k) bank={"Ravi":5000,"Raju":1990,"Ramu":8500} try: 67 Python Important Questions with Answers Ch. Vijayananda Ratnam check(bank) except InsufficientFundsException as ex: print(ex) Output: Balance is less in the account of Raju. 3 b) Write a Python program that creates a GUI with a textbox, Ok button and Quit button. On clicking Ok, the text entered in textbox is to be printed in Python shell; on clicking Quit, the program should terminate. import tkinter as tk def show(): print(e.get()) win = tk.Tk() win.title('Test Page') win.geometry('100x100') e = tk.Entry(win,bd=1) e.pack() ok_btn = tk.Button(win,text="Ok",command=show) ok_btn.pack(side=tk.LEFT) quit_btn = tk.Button(win,text="Quit",command=quit) quit_btn.pack(side=tk.RIGHT) win.mainloop() Output: 4 a) Explain how to raise and handle an exception with an example. 68 Python Important Questions with Answers Ch. Vijayananda Ratnam Built-in errors are raised implicitly. However, a built-in or custom exception can be raised manually by using raise keyword.The general syntax for the raise statement is as follows. raise Exception (arg) Here, Exception is the type of exception (For example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. Example:The following code accepts a number from the user. The try block raises a ValueError exception if the number is outside the allowed range. try: x,y=100,2 z=x/2 if z > 10: raise ValueError(z) except ValueError: print(z, "is out of allowed range") else: print(z, "is within the allowed range") Output: 50.0 is out of allowed range. 4 b) Compare the GUI-based programs with Terminal-based programs. What is GUI? A Graphical User Interface (GUI) is a visual representation of communication that makes it easy for users to interact with electronic devices. GUI combines many graphical representations, including graphic icons such as menus, cursors, tabs, mouse, windows, and scroll bars. Communication between the user and the electronic device is performed by interacting with these graphical icons. Graphical user interfaces have become a standard user-centred design when it comes to software application programming. They provide users the capacity to interact and operate electronic devices, more so, computers. Apple’s Macintosh and Microsoft Windows operating systems are excellent examples of GUI. What is CUI? Character / Command-line interface (CUI) is a command-line program that relies on text inputs to perform operating system functions. CLI was the standard way of interacting with computing devices in the early days of computing. 69 Python Important Questions with Answers Ch. Vijayananda Ratnam Still, system administrators and software developers use CLI to install software, access features missing in the graphical interface, and configure computers. are the most common types of CLIs in use today. The differences between Graphical User Interface (GUI) and Character User Interface (CUI) CUI GUI 1. CUI stands for Character User 1. GUI stands for Graphical User Interface. Interface. 2. In CUI user interacts with applications 2. In GUI user interacts with applications by making use of commands. by making use of graphics such as icons and images. 3. Only one task can run at a time. 3.More than one task can run simultaneously. 4. A CUI will require less computer 3. A GUI will require a lot of more system resources. resources because each element that needs to be loaded such as icons fonts etc. 5. CUI appearance is not easily changeable. 5. GUI is highly customizable. 6. CUI is of high speed. 6. GUI is of low speed. 7. Usage is difficult, requires expertise. 7. Usage is easy. 8. Bash shell (for Mac OS and Linux) and 8. Apple’s Macintosh and Microsoft MS-DOS (for Windows) are the best Windows are the best examples for GUI. examples for CUI Drawbacks of CUI A large number of commands makes it challenging to use CUI, even for experienced users. CUI leaves a small room for error. Mistyped commands may not get processed correctly. In case of mistyped instructions, you may need to start from scratch again. Drawbacks of GUI • GUI is not resource optimized. The aim is to make a user-friendly interface, and as such, it uses more computer memory. • Applications based on GUI require more RAM to run than those based on other interface types. • Users need to use the help file to find hidden commands. • Compared to other interface types, GUI uses more processing power. 5 a) Explain the difference between else block and finally block in exception handling? Explain with an example. else and finally: In Python, keywords else and finally can also be used along with the try and except clauses. 70 Python Important Questions with Answers Ch. Vijayananda Ratnam While the except block is executed if the exception occurs inside the try block, the elseblock comes into execution only when there is no exception raised in the try block. The finally block consists of statements which should be processed regardless of an exception occurring in the try block or not. As a consequence, the error-free try block skips the except clause and enters the finally block before going on to execute the rest of the code. If, however, there's an exception in the try block, the appropriate except block will be processed, and the statements in the finally block will be processed before proceeding to the rest of the code. Syntax: try: #statements in try block except: #executed when error in try block else: #executed if try block is error-free finally: #executed irrespective of exception occurred or not Example:The example below accepts two numbers from the user and performs their division. It demonstrates the uses of else and finally blocks. try: x,y =[int(x) for x in input('Enter two integers:').split()] z=x/y except ZeroDivisionError: print("except ZeroDivisionError block") print("Division by 0 not accepted") except: print('Some error occurred.') else: print("Division = ", z) finally: print("Executing finally block") x, y=0,0 print ("Out of try, except, else and finally blocks.") Case 1:The first run is a normal case. The out of the else and finally blocks are displayed because the try block is error-free. Output 1: Enter two integers:10 2 Division = 5.0 71 Python Important Questions with Answers Ch. Vijayananda Ratnam Executing finally block Out of try, except, else and finally blocks. Case 2: The second run is a case of division by zero, hence, the except block and the finally block are executed, but the else block is not executed. Output 2: Enter two integers:10 0 except ZeroDivisionError block Division by 0 not accepted Executing finally block Out of try, except, else and finally blocks. 5 b) Explain about Checkbutton widget in tkinter. How to create three checkbuttons (one for Telugu, Second for English and third for Hindi) on the same canvas. The Checkbutton widget is used to track the user's choices provided to the application. The Checkbutton is mostly used to provide multiple choices to the user among which, the user needs to choose one or many. Syntax w = checkbutton(master, options) Some of most frequently used options are: 1. text - The text to be displayed on the checkbutton. 2. variable - It represents the associated variable that tracks the state of the checkbutton. 3. onvalue - The associated control variable is set to 1 by default if the button is checked. We can change the state of the checked variable to some other one. 4. offvalue - The associated control variable is set to 0 by default if the button is unchecked. We can change the state of an unchecked variable to some other one. 5. command - It is associated with a function to be called when the state of the checkbutton is changed. Example: win=tk.Tk() win.title('Check buttons') win.geometry('250x100') chkVar1 =tk.IntVar() chkVar2 =tk.IntVar() chkVar3 =tk.IntVar() lbl = tk.Label(win,text="Languages Known:") lbl.grid(row=0,column=0) c1 = tk.Checkbutton(win,text='Telugu',variable=chkVar1,onvalue=1,offvalue=0) c1.grid(row=0,column=1) 72 Python Important Questions with Answers Ch. Vijayananda Ratnam c2 = tk.Checkbutton(win,text='English',variable=chkVar2,onvalue=1,offvalue=0) c2.grid(row=1,column=1) c3 = tk.Checkbutton(win,text='Hindi',variable=chkVar3,onvalue=1,offvalue=0) c3.grid(row=2,column=1) win.mainloop() Output: 73