0% found this document useful (0 votes)
11 views22 pages

Python

The document contains various Python programming tasks and explanations, including checking for palindromes, calculating sums, finding GCDs, and working with lists and tuples. It also covers concepts like the filter function, list methods, slicing, modules, and file reading methods. Additionally, it discusses features of Python, lambda functions, and comparisons between data structures like lists and dictionaries.

Uploaded by

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

Python

The document contains various Python programming tasks and explanations, including checking for palindromes, calculating sums, finding GCDs, and working with lists and tuples. It also covers concepts like the filter function, list methods, slicing, modules, and file reading methods. Additionally, it discusses features of Python, lambda functions, and comparisons between data structures like lists and dictionaries.

Uploaded by

tusharshivarkar8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
‘Write a python program to check whether a given string is Palindrome or not. 2. Write a python program to find sum of natural numbers. 1 Frogran to check whether @ given string ie Polindrone oF aot string = input ("Enter a strin rev_string = for ch in string: rev_string = ch + rev_string Af string == rev_atring: print(*the string is Palindrone.“) eles print("The string is not Palindrome. ¥ Program to find sun of natural panbers = int (input ("Enter @ number: *)) aun = 0 aed while i <= ‘sum = sun + i deded print("sum of natural nunbers =", sum) 3. Write a python function to check whether a number is perfect or not. 4. Write a python program to convert a list toa tuple. ¥ Ponction to check whether a number ie perfect or not Got is_perfect(num): sum = 0 gel while 4 < nut Se mum $ 4 == 0: aefed Sf eum == nuns return True elses ‘return False 2 = int(input(“mnter a number: *)) if is perfect(n): PFint("he nunber is Perfect.) cise! ‘print("the number is not Perfect.") Program to convert @ list to a tuple ween n= Ant(input (“Enter number of elenents in the List: *)) print("Bnter elenents:") for 4 in ranga(n): ‘ele = input() st -append(ele) ‘tup = tuplerist) print(*The tuple is: top) 1. Write a python program to check if a given string as palindrome or not. 2. Write a program to find GCD of number using recursion. ‘string = input("Enter a string: ") reverse_string = "" for ch in string: reverse_string = ch + reverse_string if string == reverse_string: print("The string is a paZindrome.") else: print("the string is not a palindrone.") return ged(b, a & b) uml = int(input("Enter first mumber: ")) nun2 = int(input("Enter second number: “)) result = gcd(numl, nun2) print("Gcp is:", result) 3. Write a python program to find factorial of a number. 4. Write a python program to check if a given number is Armstrong. ‘num = int (input ("Enter a number: ")) fact = 1 Af num < 0: print("Factorial not defined for negative munbers") else: for i in range(1, num + 1): fact = fact +i print("Factorial ie:", fact) ‘nun = int (input ("Enter @ number: ")) seme sm digits = len(str(nun)) while temp > 0: digit = temp $10 sun = sun + (digit ** digits) temp = temp // 10 if sum == num: print("The number is an Armstrong number.") else: print ("The number is not an Armstrong munber.") 1. Explain the filter function with example “The flter( function in Python is used to extract elements from an iterable such a8 a list, tuple or set based on a ‘given condition. It takes two arguments: a function and an iterable. The function is applied to each element, and ‘nly those elements for which the function returns Trae ‘ae included in the result. The output of filter is am {nerator, which is usually converted into a list or tuple for use. For example, if we want to get even numbers from a list, we can define a function that checks whether ‘a number is divisible by 2 and then apply flter0 to mums = (2, 2,3, 4, 5, 6, even_mums = list (filter(is_even, nuns)) Print(even_nums) # Output: [2, 4, 6, 8, 10] 2. Explain any two list methods with example List methods are built-in functions in Python that help in performing operations on lists. One commonly used method is append(), which adds a new clement to the end of the list. For example, if we have a list of fruits and we use append("‘orange”), the new fruit will be added at the end. ‘Another useful method is remove(), which deletes the first ‘occurrence of a specified element from the list. For instance, if list contains duplicate elements and we use remove(“apple”), only the first occurrence of “apple” will be removed. ‘These methods make list manipulation easy and efficient. # Example of append() method fruits = ("apple", “banana") fruits append("orange") print (fruits) # Output: [‘apple', "banana’, orange" # Brample of renove() method fruits = ["apple", “banana”, fruits. remove("apple") Print(fruits) # Output: ["banana’, ‘apple’, ‘mange'] capple*, “mango"] 4, Explain the concept of slicing with suitable example Slicing in Python is wied to extract a portion of a sequence such as a string, list, or tuple. It is done using the syntax sequence[start stop step], where start indicates the beginning index, stop indicates the cading index (exclusive), and step defines the increment. Slicing allows lexble access to parts (of data without modifying the original sequence. For example, if we have a string “Python Programming”, using s[0:6] will return "Python", while s[::-1] will return the reversed string. ‘Thus, slicing is « powerful way to manipulate sequences efficient. ¥ Beample of slicing 2 = “Python Programming” 2 Python Programing Python to rgamn (every 2nd char) gninnargorP nohty? Hi 5. What are modules? Explain with example how to import modules. ‘A module in Python is a file that contains Functions, classes, land variables which can be reused in other programs. Modules help in organizing code and improving reusability. Python ‘provides many built-in modules such as math, random, and datetime. To use a module, we import it using the import keyword. For example, using import math allows us to access functions like [Link]() and constants like [Link]. We can also import specific functions using from module name import fanction_name, or use an alias with import module_name as ‘alias. This makes programs more structured and easier to manage, @ Seample 1: inport entire module import math print([Link](16)) # Output: 4.0 rint (math-pi) # output: 3.141592653509793 @ Banple 2: Inport specific function ‘from math import factorial print(tactorial(S)) __# Output: 120 @ Bvample 3: Inport with alias import math ao = print (a-pow(2, 3)) # output: 8.0 For instance, if we have "I love Python” and replace “Python” ‘with "Java", the result becomes “I love Java". These methods are useful for formatting and modifying string data. ¥ Bxanple of upper() method s = “hello python print(s-upper() 4 output: HELIO PYTHON ¥ Example of replace() method = °T love Python" peine(sreplace("Python", “Java")) Output: T love Java. 6. Which methods are used to read from file? Explain any two of them with example. Python provides several methods to read data from files, including readO, readline, and readlines(. The read() method reads the entire content of the file at single string, which is ‘useful when we need all data at once. On the other hand, readline() reads only one line ata time, making it useful for rocessing large files step by step. For example, using read ‘will display the full fle content, whereas readline() will return ‘one line each time itis called. These methods help in efficient file handling depending on the requirement. 7 erample of resd() wethod £ = opent("sample. txt", "E") fontene = creed) prine(comeent) Ecclose() Brample of Feadline() wethod £ = open("eample-txt", “r") Line = f-readiined) print(2ine) Ecclose() 1. Explain features of Python. Python is simple, readable, and easy to learn. It supports object-oriented and functional programming. It is an interpreted language with dynamic typing. Python also has a large tadard library and strong community support. 2, What is purpose of range() function? The range() function generates a sequence of numbers. It is mainly used in loops like for to iterate a fixed number of times. It can take start, stop, and step values. 3. What is indentation? Indentation refers to spaces at the beginning of a line of code. In Python, it defines blocks of code instead of braces. Proper indentation is madatory for correct execution, 11. What is variable-length argument? Variable-length arguments allow passing multiple values to a function, Lst-]bt = [1d, 26,'36, 46; 50] for i. in Lst: print(i) This loop-prints each element of the list one by by one 13, What is a slice operator? The slice operator is used to extract a part of a sequence, itis written using * (colon). Example: list 1:4] returns elements from index 1 to 3, 14. How to add multiple elements at the end of list? ‘We use the extend() method to add multiple elements. It takes another list as input. Example: list .extend(6, 7,8}). 4. Define anonymous function. An anonymous function is a function without a name. It is defined using the lambda keyword. Itis used for short, simple operations. 15. Explain the remove() method. ‘The cemove() method deletes a specific element from a list. It removes the first occurrence of the value. If the element is not found, it raises an error, 5. Compare List and dictionary. A list is an ordered collection of elements accessed by index. A dictionary stores data in key-value pairs. Lists allow duplicate values, while dictionary keys must be unique. 16. Write a lambda function to add 10 to a given integer, x = lamba a: a+10 print (x5)) This function takes a number and returns the value increased by 10, 6. What is lambda function? A lambda function is a small anonymous function defined using ‘lambda’. It can have multiple arguments but only one 17. Explain the remove() method. ‘The remove() method deletes a specific element from a list. It removes the first occurrence of the value. If the element is not found, it raises an error. 9, Compare for and while loop? A for loop is used when the number of iterations is known. A while loop runs as long asa condition is true. for is generally used 18, What is Regular Expression? * * * ‘Common methods include match(), search(), findall(, and. sub(), These are used for pattern matching and string processing. They Question 1 1. Whatis the purpose of range() function? The range() function generates a sequence of numbers, often used in loops. uestion 11 11. What is indentation? Indentation is used to define the blocks of code in Python. 2. What is a list? Explain with suitable example. A list is a collection of items. Example: my_list = [1, ‘apple’, 3.14] 12. List the features of Python? Python features simplicity, readability, ‘dynamic typing, and a large standard library. 3. What is copysign() function? It returns a float with the magnitude of the first number and the sign of the second mumber. 13. What are break and continue statements? Break exits a loop prematurely; continue skips to the loop's next iteration. 4, How are tuples created? Tuples are created by placing elements inside parentheses, e.g., (10, 20, ‘car’). 5. What is ‘wb’ mode in file handling? ‘wh’ mode is used for writing files in binary (write binary). 6. How to create a package? Create a directory with an _init__py file and modules. 14, List any two built-in exceptions? Examples: IndexError, ValueError. 15. What is the purpose of range() function? ‘The range() function generates a sequence of numbers, often used in loops. 16. What does the following function return: clock() and gmtine()? clock( returns the processor times gmitine() returns current UTC time. 7. What is the use of finally block? The finally block ensures code runs regardless of exceptions. 17. Compare for and while loop. For loop iterates over a sequence; while loop iterates as long as a condition is true. 8. What is ‘wb’ mode in file? <1 Create a directory with an _init__py file and modules. 18. Define text and binary files. Text files contain readable text; binary files hold data in binary format. 9. Give the use of index() method of string. The index() method finds the first occurren- ce of a substring. 19. Define list and dictionary. A list is an ordered collection of items; a dictionary is a collection of key-value pairs. 10. Python is a scripting language. Comment. Yes, Python is an interpreted language, often used for scriptins. 20. What is lambda function? A lambda function is an anonymous, function defined with the keyword lambda. 2 Define string. A string is a sequence of characters enclosed within single quotes (° "), double quotes (" oF triple quotes =. Example: "Python’, ‘Hello’ Which character prefixed before a string as raw string? ‘The character ‘r’ or “R’ is prefixed before a string to represent it as a raw string Example: r'C:\newitest” ‘What is the purpose of range() function? ‘The range() function is used to generate a sequence of numbers. It is commonly used in loops. Example: range(1, 10, 2) generates 1, 3, 5, 7, 9. Give syntax for if else statement. if condition: # statements else: # statements ‘What is looping statements? Looping statements are used to execute a block of code repeatedly based on a condition, Examples: for loop, while loop. List types of type conversions. Implicit type conversion (Gi) Explicit type conversion Give the use of index() in string. ‘The index) method is used to find the position of the first occurrence of a substring in a string. It raises an error if the substring is not found. Example; "Pythonindex('’) —+ 2 ‘What are break and continue statements? break: Used to terminate the loop immediately and transfer control to the statement after the loop. continue: Used to skip the current iteration and continue with the next iteration of the foop. Compare for and while loop (any two points). eine for loop ‘while Joop ‘Usege | Usd wen the numberof Used when the number of erations is known or | erations & ot own and trating over a scqunce | depends on x condition. No aed fale | Condon ard conrol separately vrlale must be inte Taiaiaon Recabily Tess readable for complex oops 10. Define list. AA list is an ordered, mutable (changeable) collection of items. lems can be of different data types. Example: [1, '', 3.5, True] uu. 12. 13. 4. 15, 16. 4 18. 19. Define tuple. A tuple is an ordered, immutable (unchangeable) collection of items, It is writen using parentheses (). Example: (10, ‘apple’, 3.14) ‘What is function? ‘A function is a block of code that performs a specific task and can be reused. It helps to ‘organize code and avoid repetition. Define set. ‘A set is an unordered collection of unique elements. Tt does not allow duplicate values. Example: {1, 2, 3,4) Define dictionary. ‘A dictionary is an unordered collection of key-value pairs. Keys are unique and immutable. ‘Example: {‘name'; ‘John’, ‘age’: 25} ‘What is the purpose of reduce()}? ‘The reduce() function applies a given function of two arguments cumulatively to the items of an iteable, from left to right, to reduce the iterable to a single ‘accumulated value, (Defined in functools module) ‘What is the use of + and * operators in list. ++ operator: Used to concatenate two lis. Example: [1, 2] + [3, 4] + [1, 2, 3, 4] * operator: Used to repeat the list for a given number of times. Example: (1, 2] ©3 (1, 2,142, 162] Which methods are used to add and remove lerents from set? ‘Add elements: al), update() [Remove elements: remove(), discard). popQ. clear() ‘What is the purpose of stack diagrams? Stack diagrams are used to represent the flow of program execution, the funetion calls, and the ‘memory allocation of variables and their values daring runtime. Define recursion. Recursion is a technique where a function calls itself to solve a smaller instance of the same problem until a base condition is met. ‘Tuples are ordered and unchangeable. State true or false. ‘True. ‘Tuples maintain the order of elements and once crested, their values cannot be modified. (A) Short Answer Questions: 1. What is Python? Python is a high-level, interpreted, general-purpose programming language. It was created by Guido ‘van Rossum and first released in 1991. 2. Define variable. A variable is a named location in memory used to store data. The value stored in a variable ean ‘change during program execution 3. What is constant? A constant is a value that does not change during. the execution of a program. In Python, constants ‘are usually written in uppercase lewers by ‘convention. 4. Which functions is used to perform 1/O task in Python? ‘The input() function is used to read data from the user (input) and the prini() function is used to display daua on the screen (output 5. Define data type. Data type specifies the type of value a variable can hold and the operations that can be performed on it. Examples: int, float, str lis, tuple, etc. 6. List comments in Python. Python supports two types of comments: G) Single-tine comment: starts with # Gi) Multiline comment: enclosed in tiple quotes Conte my 7. Give purpose of identifiers. Identifiers are used to name variables, functions, classes, modules, etc. They help to identify different elements in a Python program. 8 What is indentation? Indentation is the spacing (labs or spaces) at the beginning of a line of code. In Python, indentation is used to define the block of code. 9, What is dry run in Python? Dy nun is a method of manually executing a program step-by-step with sample data on paper to trace the logic and outpot without using a computer. 10. List features of Python. {@_ Simple and easy io learn (Gi) Interpreted language (Gi) Object-oriented (iv) Portable (cron-platform) (9). Extensive standard library (i) Open source (i) Great suppor for modules and packages 11. What is keyword? Keywords are reserved words in Python that have special meaning and cannot be used as identifiers (variable names, function names, et) Example: if, else, for, while, def, retu, class, etc. 12, Python is a scripting language. Comment this statement. Python is a scripting language because it is interpreted, does not require compilation, and is designed for waiting and running scripts quickly and. IL is often used for automation and scripting tasks, 13, List editors used for Python programming, Some editorvIDEs used for Python programming are: (@ IDLE Python's builtin TDF) (i) PyCharm (Gi) Visual Stadio Code Gv) Jupyter Notebook (© Sublime Text 14, Give the purpose of an operator. Operators are used to perfor operations on variables and values. They help in calculations, ‘comparisons, and logical operations. 15, What is statement and expression? ‘A statement is an instruction that performs an action, Example: print("Helio") ‘An expression is @ combination of values, variables, and operators that evaluates to a single value. Example: a+b * 5 16. Define operator precedence. Operator precedence determines the oder in which operators are evaluated in an expression, Operators with higher precedence are evaluated first. Example: +, / have higher precedence than +, ~. 17, What is type casting? ‘Type casting is the process of converting a variable from one data type to another. Example: in(.5),float(10), str(100) 18, Define control flow in a program, Control flow is the order in which statements in a rogram are executed. It determines the sequence of execution based on conditions and loops. 19, Give purpose of selection statements. Selection statements (if, if-else, elif-else) are used to make decisions in a program. They allow the program to execute different blocks of code based (on conditions. 20. What is the role of % operator? ‘The % operator is the modulus operator. tis used to find the remainder when the first operand is divided by the second operand, Example: 10% 3 = 1 1. Define module. ‘A module is a single Python file containing Python definitions and statements. It can define functions, classes, and variables that can be used in other programs. ‘Example: [Link] 2. Define package. ‘A package is a collection of related modules organized in a directory hierarchy. It must contain an init__.py file to be recognized as a package. Example: A folder “mypkg” containing init__.py, [Link], mod2py. 3. What is exception? ‘An exception is an event that occurs during the execution of a program that disrupts the normal flow of instuetions. Python uses exceptions to handle runtime errs, Example: ZeroDivisionError, FileNotFoundError, 4. Which function is used for creating files? “The open() function with mode 'w" (write) is used to create a fie. ‘Example: f = open("[Link]", "w") 5. Define directory. ‘A directory is a container that stores files and other directories. Ic helps in organizing data in a fle system. Example: C:\Users\Documents 6. Define file. AA file is. a named collection of data stored on a storage device. It can contain text, numbers, images, or any other data. Example: [Link], dataccsv 7. What is RegEx? [Regex (Regular Expression) is a sequence of characters that defines a search pattem, used for pattem matching in stings. ‘The re module in Python is used 10 work with Regular Expressions, Example: “\d+" matches one or more digits. 8. What is user defined exception? User defined exception is a custom exception created by the programmer by extending the Exception class, Its used to raise applicaton-specific errors. Example: class MyBmror{ Exception): pass raise MyError("This is a uscr defined exception") 9. List funetions in math module. Some commonly used functions in the math module are: sqrt), ceil(, floort), pow0, factorial(), sin(), cost), tant), Jog(), 108100, exp0. pi 10. Give the purpose of match). ‘The match) function fiom the re module checks for a match only at the beginning of the string. It tums a match object if the patiem matches, otherwise retums None. Example: [Link](s"abe", *abedef”) —+ Match object 11. Give the syntax for handling exceptions. sade that aay raise exception except Eitept lenny 7 1, What is variable-length argument tuples? \Variable-length argument tuples allow a function to accept any number of positional arguments. They are specified by placing an asterisk (2) before the parameter name. Example: def func(*args): 2, What is the use of in Operator? “The in operator is used 0 check whether a value ‘exists in @ sequence (lke list, tuple, sting, set, ictionary). It etums True if found, otherwise False Example: 3 in (1, 2, 3] + Trwe 3. List operations on dictionary. Operations on dictionary include: ‘Accessing values (dictkey)) ‘Adaing items Updating tems Deleting items ‘Traversing items (keys(), values), items()) 4. Define void function. ‘A void function is a funetion that does not return any ‘value. It performs an action but does not send any result back to the caller. Example: def show(): print("Hello") 5. Define argument in function, ‘An argument is the value passed to a function when it fs called, It is used to transfer data to the function's parameters. Example: 6. Which function is used for creating Frozenset? ‘The frozenset() function is used to create an immutable (unchangeable) set. Example: f% = frozenset(1, 2, 31) List characteristic of dictionary. + Unordered collection of key-value pairs + Keys are unique and immutable + Values can be of any data type + Mutable (can be changed) + Defined using curly braces {} 8 _Compare list and tuple, (any two point). f addca, b): Point List ‘Tuple 1, | Mustitiy | Mabie an be digs | tamale tamot be dango) 2 | Symax | Died wing square | Defies wing prenieses trackes I 9. Define anonymous function. ‘An anonymous function is a function without a name. Its created using the lambda keyword and is used for short, simple functions. Example: add = lambda a, b: a +b Repetition “Membership (i, no in) Length dent) ‘Count (count) Index ndexo) 1 2 2B. 14, Give the purpose of a stack diagram. ‘A stack diagram is used to visualize the flow of program execution, function calls, return values, and. the memory allocation of variables in the call stack. ‘What are the built-in functions used for type conversion? Python provides the following built-in functions for type conver ‘ntQ, float), complex(), str), list), tuple(), set), dict), bool) What is flow of execution? Flow of execution is the order in which statements in a program are executed, from star to finish, based on control flow (sequence, selection, and iteration). ‘What is difference between del and pop() in list. Point det op) Purpose | Deletes an clement by | Removes and retums index or the entre list | the element st the specified index (efit last element) Does not zetum any value Returns the removed clement 15, 16, 17. 18, 19. What is use of dict() function? ‘The dici( function is used to create a dictionary. It can create a dictionary from key-value pairs, sequences, or another mapping object. Example: dict(name="John", age=25) What is use of set() function? “The setQ) function is used to create a set object. It removes duplicate values and stores only unique elements. Example: stl, 2,2. 3) + {1 2.3) List any two builtin exceptions. + ZeroDivisionError: Raised when division by zero is tempted. + ValueError: Raised when a function receives an argument of correct type but inappropriate value. ‘What is the purpose of datetime module. ‘The datetime module is used to work with dates and times. It provides clases like date, time, datetime, timedella to perform operations on date and tin. Example: [Link]() List standard types of packages. + Buutin packages (standard ibrary) + Third-party packages User-defined packages |. Define text and binary files. ‘Text files: Store data in human-readable form (charscter) “They are opened in text mode. Example: xt files Binary files: Store data in binary form (bytes). They are ‘opened in binary mode. Example: jpg, exe files (B) Long Answer Questions: 1. Explain Python programming language with its applications. Python is high-level, interpreted, general-purpose programming language. I was crouod by Guido van Rossum and fist relesed in 1991. Python suppor ‘muldple programming paradigms including procedural biect-orented, and functional programming. Te has simple and oasyto-rd symtak, which makes ‘+ Data Science and Analytics: Python is widely used for data analysis, visualization, and machine leaming ‘+ Artificial Intelligence: Libraries like TensorFiow. ‘Keras, PyTorch are used for Al and doop learning. ‘+ Automation and Seripting: Python is used for ‘automating tasks such as file handling, data processing, system axiministration ‘+ Sclentific and Numeric Computing: NumPy, SciPy, Pandas are sed in acientific research and engineering. ‘+ Desktop GUT Applications: Tkinier, PyQt, WxPython are used to ereate desktop applications. ‘+ Game Development: Python can be used with Nbraies like Pygame, ‘+ Networking: Python is used in network programming, socket programming. and security tools. 2, How to declare a variable? Lists rules for declaring variables. ‘Variable Declaration: In Python, a variable is declared by simply assigning a value to 4 name using the assignment operator Syntax: variable_name = valve ‘Example: x=10 y= "Hello" pias ads fr dear vain ‘Variable names ean contain leters (4-2, AZ), digits (©), and underscores CD. 2. Variable name must start with eter or ae Lnderscore, not with a digit. 3. Variable names are case-sensitive (ope, Age and AGE are diferent 4. Variable names cannot be a Python keyword (ike If, else, while, et) 5. No special characters are allowed except underscore, 6. Variable names should be meaningful and follow good naming conventions. 3. Give short history for Python. Python was created by Guido van Rossum in the late 1980s and first released in 1991. It was designed to be an easy-to-read, high-level programming language ‘with an emphasis on code readability. Python is named after the BBC TV sbow “Monty Python's Flying Circus” Initially, Python was developed as a successor to the ‘ABC language, with the goal of improving its exception handling and interfacing with the Amocbs operating system, Python 2.0 was released in 2000 with many new features sich as list comprehensions and garbage collection. Python 3.0 was released in 2008, which introduced ‘major changes that ae not backward compatible with Python 2.x. Today, Python 3 is the most widely used ‘4. Write short note on: Comments in Python. ‘Comments are used in Python to explain the code and make i ‘move readable, Pyibon supports two types of comment: 1. Single-tine Comments: Single-tine comments start with the ash (#) symbol Everything aber # on that Une Is ignored by the Ierprse. Exam 2 Multtine Comments: “Moline comments are enclosed in triple quotes (*" oF PS)" The interpreter ignores the content inside the triple Example: ih Priten. Comments are veel for: 2 Temporaiy dmbling 8 block of code daring testing 5. How to write and run python scripts? Explain in detail Weiting «Python Seip ‘Open a tat ear oF IDE (ike IDLE, PyCharm, VS Cade, Notopa 3. Save the le with a py extension (2 programy) 4. Python code written ina fle ir called sori. Running 9 Python Seript: Method 1: Using Command Prompt (Terminal) Te Open Command romps (Windows) or Terminal (Lirus/Mae), 2 Navigate to the decoy where the Python scripts mved ting the ee command, 23. Rn the script using the following command 4. The oupur will be dlpayed nthe conse Method 2: Using IDE (eg. IDLE, PyCharm, VS Code) Open dhe scp in the IDE. 3, Ourput will be displayed In the consotefoutput window. Example: peineisiatie Pyehnt*) Ouxpot: Bello, Python! Advananges: Tay wrt and rin Plato Independant 1 Sipps merece mode for tating code ‘6 What is interpreter? How it works? ‘igh-tovel programming language line by ne. Python tan Imerpretedangvage 4 Tne Python Viral Machine (PVM) executes the bytecode ‘3 The ouput Is prodieed ‘Adratane iter, [Browse rpc imme + Tieracive execution Is posible. 7. Explain the folowing features of Python programming: (). Simpler Python ie a simple ind ear-to-undertand syria Similar wo Tenglish. I educes the ost f peograre (W Platform tndependent: Pytnon programs can run on Siferent platforms (Windows, Linux. Mac. ee) without (4 Tnternetive: Python provides an ieractive shell where ‘we can write and execute code hae by Te testing and dagen, = polbesorybars, excapealation, Wich help in wring modular arn reusable code ‘% Explain about the need for larning Python programming ipemeue "Used in Fickds ike wer devo c AL ae ie Sr i in 1, What is string? How to declare it? Explain with example. A string is @ sequence of characters used to store text in Python. It can contain letters, digits, spaces: and special symbols. Strings are immutable, which means their content cannot be changed after creation ‘Declaration: A string can be declared by enclosing characters in single quotes (""), double quotes °°) or triple quotes (°° "*" or Example: ‘sl = “Hello” 52 = "Python Programming” s3 = 6"'This is a multi-line steing Here, s1, 2 and @ are strings. 2. Explain the following statements: @if Gi) ifelse (iii) break (iv) continue @) ifs The if statement is used to execute a block of code if a given condition is True. 4. Write short note on: Unicode strings. Unicode is a universal character encoding standard that represents text in almost all the languages of the workd Python 3 uses Unicode by default, which means all strings are Unicode strings. Unicode strings ean represent characters from different languages such as English, Hindi, Chinese, Arabic, ete. Example: si = ‘Hello® # English s2= ‘aHRa # Hinds s3 = ORE # Chinese s4= these! # Arabic ‘These strings can be processed like any other string in Python, This helps in developing multilingual applications. 5. Write program to find factorial of a number. Python Program: Example: x10 f= Ant(input("enter @ number: ")) feos. fact = 1 print("x is greater than 5") tence: Gi) if else: ‘The if else statement executes one block Print("Factorial 1s not defined for negative eutbers") fof code if the condition is True and another elif n= print("Factorial of @ is 1") else: ie > 5: print("% 1s greater than 5") else! print("x 4s 5 or ess") (ii) break: The break statement is used 1 terminate the loop immediately when itis encountered. Example: for 4 in ran ified break: print (i) ‘Output: @ 1-2 Gv) continue: The continue statement skips the current iteration and moves to the next iteration of the loop. Example: De ye continue print) Output: 0134 3. Describe manipulation of string with example. ‘Swing manipulation means performing various ‘operations on sirings. Some common operations are: concatenation, repetition, indexing, slicing, length, 9. searching and replacing. "y ‘Helle Worse" eH 1 Inde: Accening scarcer using index. s = "Python print(s[@}) # Outout: © Prine(sis]) 9 Output: 9 4. Slicing: Extracting part of «sting ‘Python Progranming” prine(s{ere]) # Output: Python Prine(s(7:])& Output: Programing ‘5. Length: Finding length of a suing. Sse bytnen” Print(len(s)) # output: 6 6 Cort onverton: python" "8 dupper(s PYTHON Brine ieie0)) 4 Pyehon for £ An range(1, #1): fact = fact *§ print(*Factorial of", ny “Ast, fact) ‘Explanation: ‘The program takes a number as input from the user. If the number is negative, it shows a message. If the ‘number is 0, factorial is 1. Otherwise, it muliplies all the numbers from 1 to n using a loop and displays the factorial. Examp! Input: 5 ‘Output: Factorial of $ is 120 6. What is nested loop? How to use it in program? ‘A nested loop is a loop inside another loop. The inner loop executes completely for each iteration of the outer loop. [Nested loops are used when we need to repeat a block of ‘code multiple times in a structured manner, such as in pattems, matrices, and tables. Example: 4 Program to print a multiplication table for i in range(1. 11): print(n, "x", 4, "=", ned) Output: axis 4x208 axae22 4x 10 = 40 # outer Loop 4 Inner 100p In this program, the inner loop prints the table for each value of i controlled by the outer loop. 15. 16. 7. Explain the following terms: (@ Tuple, (ii) List, (iii) Set, (iv) String, (s) Dictionary @ Tuple: A tuple is an ordered collection of items similar to a list, but it is immutable, which means. its elements cannot be changed afier creation. It is written using parentheses () Example: t = (10, 20, 30, "Python") (il) List: A list is an ordeted and mutable collection of items. It can store elements of different data types. Lists are written using square brackets []. Example: 1 = (10, 20, 30, "Python") Gif) Set: A set is an unordered collection of unique items. Duplicate values arc not allowed. Sets are written using curly braces (). Example: S iv) String: A string (enclosed in single quotes quotes * ", or triple quotes ” Strings are immutable. Example: str = "Hello Python" (¥) Dictionary: A dictionary is a collection of key-value pairs. Each key must be ‘nique, and values can be of any data type. Dictionaries are written using curly braces () with keys and values separated by colon (: Example: D How to performs input and output ‘operations in Python? Explain in detail. Python provides built-in functions for input and ‘output. (@ Input: The input( function is used to take input from the user. By default, it reads input as a string. The general form is: variable = input promt") Example: ‘pane = input("Enter your name: 10, 20, 30, 40) sa sequence of characters wh, double ore, ("name”: "Ravi", “age”: 20) age = intCinout("enter your age: *)) Here, name is a string and age is converted 10 integer using int(. Gil) Output: The output in Python is displayed using the print() function. It can print cone Or more values on the scree! princtvaluel, value, «| a) Example: prine(*Wane:", nave) Print(*Age:", age) By default, values are separated by a space and a new line is added at the end. ‘Write applications of Python in detail. Python is a versatile language and is used in many areas. In web development, Python frameworks like Django and Flask help in building dynamic websites. In data science and analytics, libraries such as NumPy, Pandas, Matplotlib, and Seaborn are widely’ used for data manipulation, analysis, and visualization, Python is also used in machine leaming and artificial intelligence with libraries like Scikit-leam, TensorFlow, and Keras. In 18. 19. Give four examples of Python implementation. Four examples of Python implementation are: 1. Web Development — Building websites using frameworks like Django and Flask. 2. Data Analysis - Analyzing data using libraries such as Pandas and NumPy. 3. Mschine Leaming - Building models using Scikit-learn, TensorFlow, and Keras. 4, Automation (Scripting) ~ Automating repetitive tasks like file handling, web scraping, and sending emails. ‘Write short note on: Multi-line statements, Jn Python, a multi-line statement is a statement that spans more than one line. Python allows this for improving readability of long statements. There are two ways to write multi-line statements: (Using Backslash (\): Place a backslash at the end of the line to continue the statement in the next line. Example: total = 10 + 20+ 30+\ 40 + 50 Gi) Using Parentheses ( ), Brackets [ ] or Braces { }: Enclose the statement within parentheses, brackets, or braces. Python automatically treats it as a_ single statement even if it spans multiple ines, Example: total = (10 + 20+ 30+ 40+ 50) Milticine statements are most commonly used in expressions, lists, dictionaries, and function calls. ‘What is operator? Explain with example. List types of operators. ‘An operator is a symbol that performs an operation on one or more operands (values or variables) and produces a result. Example: In the expression a+b, + is the ‘operator that adds two operands a and b. ‘Types of Operators in Python “Type of Operator [Description 1. Arithmetie | Perform mathematical Operators operations 2 Comparison | Compare two valves (Relational) | and rum True or ‘Operators False. 3, Logical Operaiors | Combine conditional Assignment | Assign valoes to Operators variables, 5. Identity Chock identey Game | is, i not Operators memory location). © Membership | Check membership n | in, not in Operators sequence. 7. Bifwise Operators | Perform bit-level es operations. 1, Write the steps to install Python and to run Python code. To install Python, fist visit the official website [Link] and download the latest stable version for your operating system, Run the installer and make sure to check the option ‘Add Python to PATH’ before clicking “Install Now’. After installation, open Command Prompt (Windows) or Terminal (macOS/Linux) and type “python —version” to verify that Python is installed successfully. To run Python code, you can use two ways, For small programs, open the Python IDLE (shell) by typing “python” in the command prompt and write commands directly. For larger programs, open a text editor or IDE (such as IDLE, VS Code, or PyCharm), write your code, save the file with py extension (eg. programpy), and run it from the ‘command prompt using “python [Link]”. ‘The output will be displayed on the screen. 2. What is the role of indentation in Python? Indentation in Python is very important because it is used to define the structure and blocks of code. Python uses indentation to indicate 2 block of statements, such as in loops, functions, conditional statements, and classes. Unlike other programming languages that use braces { }, Python uses whitespace (usually 4 spaces) at the beginning of a line. If the indentation is incorrect, Python will raise an IndentationError. Proper indentation makes the code readable and helps Python understand the logical flow of the program. 3. What is variable? How to crate it? Explain ‘with example. A variable is a name given to a memory location where data is stored. Variables are used to store values that can be used and modified in 2 program. In Python, you can create a variable by assigning a value to it using the assignment operator For example: x (Variable name) 25 (Value) Here, x is the variable name and 25 is the value stored in it. You can create variables without declaring the data type. Python automatically detects the type based on the value assigned. . What are the various data types available in Python programming. Python supports various built-in data types used to store different kinds of values. The ‘main data types are Numeric, which includes int (integer), float (decimal numbers), and complex (numbers with real and imaginary parts). The sequence types include str (string), list (ordered, mutable collection), tuple (ordered, immutable collection), and range (Sequence of numbers). The mapping type is dict (dictionary), which stores data in key-value pairs. The set types include set (unordered collection of unique items) and frozenset (immutable set), The Boolean type has two values: True and False. The None type represents the absence of a value. Data Type Description iat__| Inoger numbers 8, 5,0, 100) ‘oat | Floating pont numbers 2, 3.14,-.00) complex | Complex numbers @g. 23) str | String of charactor (@-8, "Hello”) Tint | Ordered, muabl collection ea. (1.2.3), tuple | Ordered, mutable collostion (123) ict | Key-vae pa (eg, 0 1,“ "Ran ‘set | Unordered collection of unique tems s,1,2,3) frozenset_| Immutable set (eg. frozenset((1,2, 3) ‘bool _ | Boolean values: True or False ‘NoneType | Represents no value (None) 5. What is the difference between interactive mode and script mode of Python. Interactive mode is used to execute Python commands one by one directly in the Python interpreter (shell). It is useful for testing small code snippets and immediate results. In this mode, we type commands and see the ‘output right away. Script mode is used to write a complete program in a file with py extension and then run it. It is suitable for larger programs. In script mode, the entire code is executed at once and the output is shown on the console. 6, What is literal? Explain in detail, AA literal is a fixed value that is written directly in the code. Literals represent the actual data that a program uses. In Python, literals can be of different types such as numeric literals (integers, floats, complex numbers), string literals (text inside quotes), Boolean literals (True, False), and special literals like None. For example: 10, -25, 3.14, “Python”, True, 243), None. Literals do not change during program execution. 1. What is list? How to create it? Explain with example. A list is a collection of items stored in a particular order. Tt is mutable (modifiable), can hold items of different data types and allows duplicate values. Creating a list: A list is created by placing items inside square brackets [] separated by commas, Example: ® Creating lists fruits = ["apple", “banana”, “cherry*] runbers = [1, 2, 3, 4 5] mixed = [18, "Python", 3.14, True] cenpty_list = () # Accessing elements print(frusts[e]) 4 epple print(nunbers(2]) #3 print (mixed(1]) # Python Lists suppor operations like indexing slicing. appending, inserting, deleting, and more. 2, What is function? How to create it? Explain with example. ‘A function is a block of reusable code that performs a specific task. It helps to organize programs into smaller parts, improves readability and reduces repetition. Creating a function: ‘A function is defined using the keyword def. Example: @ Function deFinition ef grect(nane): Stnts function greets. 3 person” ressage = “Hello, “+ name + "I" return message 1 Function ald result = greet(“alice) prine(result) # Output: Hello, Alice! In this example, greet is a function that takes a ‘parameter name and returns a greeting message. 3. Describe any four math functions with example. Python's math module provides many mathematical functions, Here are any four commonly used functions: math. sqrt(x) — Retums the square root of x. Example: ‘npart eth crine(mathesere(ae)) __# ovtput: 4.0 4, What is meant by parameters and arguments? How to use them in function? Explain with example, Parameters are variables listed inside the function True )allcorable) — Reuss True if alt elemens are True alli{true, True, Thee]) —> True fal((True, Folse, Truel) > False ~ Returns True ifany element is Troe. alee, Troe]) > True Faleel) —> Paleo ‘Example program: Brine Cb001 (33 4 output: True Préne(ani({3, 2, 3) # Output: True prineCany(fe, °, 3D) # output: Troe 6. What is lambda function? Explain its forms in detail, ‘A lambda function ea aml, anonymous function Sefinod sing. the keyword lambda. It can have any hhumber oF arguments but only onc expression. it ‘sttomatcally returns the result ofthat expression Syma [Link](x, y) — Reus x raised to power y. prine(mthpow2, 3)) ___# output: 8.0 (Git) math. factorial(x) ~ Retums the factorial of x Example: Example: ("No armament ‘import. math SelnetFO)"e utout: nette (0) Single argoment brine co0s3). ‘e cutpve: 28, print (meh factortai(s)) 9 output: 128 yv) [Link] — Retums the value of = (pi. (Sapte argument 0) Lamia wit Dalia functions (Gommonly wed ‘To use these functions, we must first import the math ‘module using import math. Example: ‘with mpl) iter. sorted te Inport ath funbers = (3.2.3, 4) préne(mathpf) Outputs 3. 141592653580709, Sauares © Lice(aap(iomda x: 0, rumbore)) prinetequares) # output (ir Ar 8, 36] ‘Lambs Ranetions are usefl for short operations where fining fll fonetion using def is not necesy. 1. Describe the term escape character in detail. Escape characters are special characters in Python that start with a backslash (), They are used inside strings to represent characters that are difficult or impossible to type directly or to perform special. formating. Escape characters are interpreted by the Python interpreter and converted into the actual character ‘when the string is processed, ‘Common escape characters: nt Nevline (nove 9 next Line) Xt Horizontal tab Vb + Backspace \\ acksiasn At Single gate \" + doutie quote \p Garage retire Example: jello \nhyehon \ePrograening\” prints) Output: Hello Python Prograning\ 2. List built-in string methods with example. Python provides many builtin methods to work with strings. 1. upper) — Converts string to uppercase. Example: "python" .upper() => “PYTHON 2. lower() ~ Converts string to lowercase. Example: “PYTHON" lover() -> “python” 3. title() — Converts first leter of each word t0 ‘uppercase. Example: “python progranming".title() -» rython Programming” 4. strip — Removes leading and trailing spaces. Example: " hello ".strip() -> “hello” 5. replace(old, new) ~ Replaces all occurrences of old with new. Example: “hello world” replace( "work => hello Python” 6 split(separator) ~ Splits string into a list using ‘separator. Example: "2,bjcT-split(",") -> ['3', "bts 'e] 7. Join(iterable) — Joins elements of an iterable with the string. Example: ",".join(['a's "b's 'e'D >" & find(sub) — Returns index of first occurrence of substring. Example: "hello" find(re") -> 2 9. en() — Returns length of string. Example: len("hello") -> 5 3. With the help of program describe pass statement. ‘The poss statement is @ null statement. It does nothing when executed. It is used as a placeholder for future ‘code when a block is syntactically required but you do ‘ot want 1 write any codeinsideit Example: Python") 2 Gawple of pass statenent in a Function def display(): pass # To be inplenented later print("This 4s outside the function") 4, Describe sequential flow control with example, Sequential flow control means the statements in a program are executed one after another in the order they appear. There is no branching or jumping in the flow of execution Example: a= 10 b= 20 curate print("sum is:*, ¢) print(*Progran Ended") Output: ‘Sum is: 38 Program Ended In this example, each statement is executed sequentially from top to bottom. 5. Write program for greatest number form three ‘numbers using if else statement. € = Float input(“Enter third nunber: if a= band awe: greatest = 2 elif b >= @ and b >= ¢: greatest = b alse: ereatest = « print("Greatest number Enter First nunber: 25 Enter secord number: 40 ‘enter third number: 38 Oupat: Greatest number is: 48 6. With te help of example describe following loops: @ while “The while loop repeats a block of statements as long asthe given condition is True Example: Program fo print ranbers fron i to 5 uting wile et vite 4 <5: prine(t, ende* *) besea Ourpat: 42345 i) for ‘The for loop is used to iterate over a sequence (ist, tuple, string, range, ec.) Example: 7 Prograe to print minbere fron 3 to § using for for 4 an range(a, 6): print (i, endo Output: ‘This is outside the funtion Output: 12345 2 a How to add, update and delete elements in list? In Python, lists are mutable, so we can add, update and delete elements easily. To add elements, we can use append() to add at the end, insert(index, value) to add at a specific position, or extend{iterable) to add multiple elements. To update elements, we assign a new value to an existing index, e.g., list{index] = new_value. To delete elements, ‘we can use remove(value) to delete the first ‘occurrence of a value, pop{index) to remove and return the element at a specific index, or del statement to delete an element or the entire list. Example: Let L = [10, 20, 30]. Add: Leappend(40).—+ (1D, 20,30, 40), insert(1, 15) — [10, 15, 20, 30, 40] Update: L{2] = 25 —» [10, 15, 25, 30, 40] Delete: L-remove(30) —+ [10, 15, 25, 40], [Link](1) — [10, 25, 40] (returns 15) What is dictionary? How to create it? Explain with example. A dictionary in Python is a collection of key-value pairs. Each key must be unique and immutable (such as string, number or tuple), while the value can be of any data type. Dictionaries are unordered, mutable and written using curly braces (} with colon (;) separating keys and values. Dictionary can be created in multiple ways. Bamps curly braces “name': ‘Asha’, 'age': 4# Using diet() constructor ict(name='Asha’, age 20, ‘ety: "Pune'} 0, city="Pune') list of tuples 4 = dict({('name’, “Asha'), (‘age’, 20), (city, Pune’)]) In all cases, d is a dictionary containing three key-value pairs. How to accessing elements in dictionary? Describe with example. Elements in a dictionary are accessed using ‘their keys. We use square brackets [] with the key to get the corresponding value. Ifthe key does not exist, it raises a KeyError. We can also use get() method, which returns the value for the key if present, otherwise returns None or a default valve. ‘age’: 20, ‘city’: Pune’) # Output: Asha # Output: 20 print(d{'name']) rint([Link](‘age')) print([Link](‘country’)) # Output: None print([Link](‘country’, 'Not Found’)) +# Output: Not Found 4, 6. Describe the term composition with example. Composition is a strong form of association in object-oriented programming. It is a “has-a” relationship where one class contains objects of another class as its part. The contained object’s lifetime depends on the owner object. If the owner object is destroyed, the contained objects are also destroyed. Composition promotes ‘encapsulation and code reusability. Example: Consider a class Engine and a class Car. A car has an engine. If the car is deleted, its engine also ceases to exist carl Engine -name | 1 1 | -type = model power In this diagram, Car has one Engine, and Engine cannot exist without Car. ‘What is recursion? Explain recursive function with example. Recursion is a programming technique where a function calls itself to solve a problem by dividing it into smaller subproblems of the same type. A recursive function must have a base case to stop further calls; otherwise it results in infinite recursion. Example Factorial of « number using recursive function. det factorial(n): # Base case else: return n + factorial(a - 1) # Example usage Print(factorial(5)) # Output: 120 Here, factorial(5) calls factorial(4), which calls factorial(3) and so on until n= 0. What is set? How to create it? Explain with example. A set in Python is an unordered collection of unique elements. Sets do not allow duplicate values and are mutable. They are defined using curly braces {) oF the set() constructor. Example: # Using curly braces s={I, 2,3, 4} # Using set() constructor s= set({1, 2, 3, 4I) 4 From a string (creates set of unique characters) s=set("hello") #s= fh, 'e', , 'o'} Sets support operations like add), remove(), tunion(), intersection(), ete. 1 2 3. How to accessing elements in set? Sets in Python are unordered collections, so they do not support indexing or slicing like lists or tuples. Therefore, we cannot access elements using an index. To check whether a specific clement exists in a set, we use the ‘membership operators ‘in’ and ‘not in’. Examy 5 = {10, 20, 30, 40} print(2e in s) print(s@ ins) Output: False Print(1@ not ins) Output: False If we want to access elements one by one, we can convert the set into a list or tuple and then use indexing. # output: True Example: 5 = {10, 20, 30, 40} 1 = List(s) print(@[@}) # Output: 10 (the first element in the converted list) How we can remove elements from dictionary? We can remove elements (key-value pairs) from a dictionary using the following methods: () del statement: Removes the item with the specified key. Raises KeyEtror if the key does not exist. (2) pop(key): Removes the item with the specified key and returns its value. Raises KeyErtor if the key does not exist. (3) pop(key, default): Removes the item with the specified key and returns its value. If the key does not exist, returns the default value. (4) clear(): Removes all items from the dictionary. 3d: 4) # retuns 3, d= (‘a's 1, “d's 4) 4-pop('x', "Not Found’) # returns ‘Not Found’ [Link]() #d=t ‘What are the usage of dictionary copy(), get(), items() and keys() methods? Dictionary in Python provides several useful ‘methods for convenient operations. (1) copy(): Returns a shallow copy of the dictionary. Changes made to the copy do not affect the original dictionary. (2) get(key, default=None): Returns the value for the specified key if it exists; otherwise, returns the default value (None by default, It-does not raise an error ifthe key is absent. {@) items(): Returns a view object that contains key-value pairs as tuples. (4) keys(): Returns a view object that contains all the keys of the dictionary. Example: d= "name": “Asha, ‘age’: 20, ‘city’: ‘Pune') 1 = [Link]() {name "Ash 'age 2, sty: Pane’) print [Link](age’)) _# Output: 20 Print(dget(‘phooe’, ‘Not Found’)) # Output: Not Found printditems()) # Outpr: dit jtems(¢name, "Asha, Cage’, 20), ity’, "Pune")D) “Output det keys( Tame 'age'iy'}) print([Link]()) 4, What is the difference between list, set and dictionary in python? The main differences are: Feature | List Set Dictionary Deiinition | Ordered ealesion | Unordered | Collesion of oF items collection of | key-value unigue items | pais ‘Order | Maintains Does not) Mains insertion oder | maintain onter | insertion order of keys (Python 374) Duplicaes | Allows ‘Does not allow | Keys mast be duplicate items | duplicate items | unigue; values an be dupa ‘Acces [Byindexand | Noindexing, | By keys sling we membership vest ‘Syntax | Defined using | Defined using | Defined wing squave brackets | curly braces {) | curly braces a {with key: vale pairs Mubie | Yes Yes Ye 5. What are negative indexes in list and why are they used? Negative indexes in lists are used to access clements from the end of the list. The last element has index -1, the second last has 2, and so on. They ae used as « convenient ‘way to access elements from the end without knowing the length of the list. Example: 1= THO, 20, 30, 49, 50) print(1{-1]) # Output: 50 (last element) print(1[-2]) # Output; 40 print(1[-5]) # Output; 10 (first element) Negative indexing is especially useful in loops, reversing lists, and when working with dynamic data structures. 6. What is tuple? How to create, access and delete tuple? Explain with example. A tuple in Python is an ordered, immutable collection of items. Once created, its elements cannot be changed. Tuples are represented using parentheses (). ‘tuple without parentheses ‘using tuple) constructor ‘Accessing elements: Elements are accessed using index (positive or negative) and slicing. Example: prlat(tifo]) —# Output: 10 print(ti[-1])# Output: 30 print(tt(t:}) Deleting tuple: Since tuples are immutable, we cannot delete individual elements. But we can delete the entire tuple using the del statement Example: del # print) 4 Deletes the entire tuple 4 This will raise NameError 1. With the help of example explain the use of + and * operators in tuples? In tuples, the + operator is used for concatenation (combining two or more tuples) and the * operator is used for repetition (repeating a tuple a specified ‘umber of times). Example: us. 2.3) = (4, 5) 4 Using + operator (concatenation) wetle print(e3) # Oupue (1, 2,3, 4, 5) 4 Using * operator (repetition) wetted print(t4) # Output: (1, 2, 3, 2, 2, 3,1, 2,3) CN) #4 print(ts) # Output Chi, "RU, i, “hi 2, Which are basic tuple operations? Explain with example. The basie operations performed on tuples are: (1) Indexing: Accessing an element using its index. (2) Slicing: Accessing a range of elements. (3) Coneatenation: Joining two or more tuples using + operator (4) Repetition: Repeating a tuple using * operator. (5) Membership: Checking if an element exists in the tuple using in oF not in (©) Length: Finding number of elements using len) function, Example: t= (10, 20, 30, 40, 50) prine(t{e]) _# Indexing: 10 print(t[1:4]) # Slicing: (20, 30, 40) 2 = (60, 70) print(t + 12) # Concateration: (10, 2, 30,40, $0, 60,70) Print(t * 2) # Repetition: (1,203.40 0, 102.5400) print(30 int) # Members print(100 not in ¢) # Members print(len(t)) — # Length: 5 3. What are built-in dictionary functions? Explain two of them. Python provides several built-in functions that work with dictionaries. ‘Some important ones are: len(), dict(), sorted(), min), max(), any(), all, sum(. Explanation of two functions: (1) len(@): Returns the number of key-value pairs in the dictionary. True Tre Example: ga (a A bs 2, te print(len(d)) # Output: 3 (2) dict(): Creates a dictionary from a sequence of key-value pairs Example: patrs = [Cx', 100), (y', 200), ('2', 300] d= dict(pairs) print(d) 4 Output: ('x": 100, 'y: 200, 2" 300) 4. Explain how to update and delete elements in dictionary. In dictionaries, we can update existing elements or add new elements. We can also delete elements or the entire dictionary. Updating (or Adding) Elements: We assign a new value to an existing key or assign a value to a new key. Example: a= (at: a, tbe 2} aa’) = 30 1 Update existing key ate] = 3 # Add new key prine(s) # Output: (‘as 10, "b's 2, "es 3) Deleting Elements: ‘We can delete elements using del, pop(), popitem() or clear). Example: oe (er, 13) det of 4 Remove key print(d) # Ouput: (es 1, es 3) val = [Link]("e") print(val) prine(d) 4 Remove kay ‘cand rtum its value # Output: 3 # Ouiput: {fa 1) key, value = [Link]() # Remove last inserted item princckey, value) # Output: a1 print(d) # Output: () é.clear() 4 Remove all items o= (xe: 8) print(a) # Ouiput: () 5. Which are properties of dictionary keys? Dictionary keys in Python have the following properties: (1) Keys must be unique. Duplicate keys are not allowed. If we use an existing Key, its value is updated. (2) Keys must be immutable (hashable) objects. ‘They can be of types like int, float, str, tuple, bool, etc., but not list, set or dictionary. (3) Keys are case-sensitive. For example, "Name! and ‘name’ are considered different keys. (4) The order of keys is not fixed (in versions before Python 3.7). In Python 3.7+, dictionaries maintain insertion onder. 6. What is anonymous function? How to create it? Explain with example. ‘An anonymous function is a function without a name. Itis created using the lambda keyword. Anonymous functions are usually small and are used when a function is needed for a short period of time, Syntax: ambeia arguments: expression Example: # Function o add two numbers add'= lambda x, y+ Printiads, 3)) # Output: 8 4 Function to find sqeare of « number square = lambda a: a *-n rint(square(6)) ‘Anonymous functions are commonly used with functions ike Hlter), map() and sorted) # Ouput: 36 1. What is stack diagram? Explain with example. A stack diagram (or call stack) is a visual representation of memory showing the sequence of function calls. It contains {information about function name, parameters, local variables and return address. New function calls are pushed on the top of the stack, and when a function returns, its activation record is popped from the stack. Example Conder the following coe: et acate, ©) cree fetumn ¢ ef maint): rte yin Ll ota. prinete) maint) Stack agra (teeming) Top-+ [ain aa Ti] (ony mints yr trout) Been es 0 Whey atts. ») Tow» [alata waa (tsps a cont) =a sts ee (2 pope ae vento (Wen sin) Top-+ Suck is emoy Explain set union and intersection with example. Union of two sets retims 2 new set containing all elements from both sete without duplicates. Intersection of two sets rlurss new sot containing only the common elements. Example ae, 2,3, 4) B= G4) 5, 6) Union = [Link](s) prine(u) f Intersection Tw Avintersection®) or = A&B printax) # output: (3, 4) 3. Describe actual and formal parameters in detail. Formal parameters ace the variable listed in the function definition. They act ax placeholders for the values that ae aed tothe Bencion. ‘Acts parameters (or arguments) ate the real values oe ‘arables passed to the function when i called. ‘When a function is called, the valves of actual parameters are copied tothe forma or ueale " # output: (1, 2. 3,4, 5. 6) (1, y are etal parameters y Fesult = 26d(x, y) # valves 3 and 7 are passed to and b Be ‘What is difference between call by value and call by reference? Call by Value: In this method, a copy of the actual value is passed to the function. Changes made inside the function do not affect the original value. Example: ef change) keer 10 ass ‘change (a) print(s) 4# Oueput: 5 (original value unchanged) Call by Reference: In this method, the address ofthe actual value is passed to the function. Changes made inside the function affect the original value Example: def change(st): ist{e] = Istfo) + 10 Leost ‘change (L) Print(LC0]) _# Output: 15 (original value changed) ‘What are void and boolean functions? Explain with example. Void Function: A function that does not return any value to the caller is called a void function. In Python, such a function uses the return slatement without any expression oF no seturn statement tall Example: def greet(nane): print("hello,", name) {Fo return statenent greet("Alice") —# Output: Helle, Alice Boolean Function: ‘A function that relums a value of type boolean (Trae or Falke) ie called » boolean function. It is used to make decisions and is often used in conditions. Example: ef is even(n). return a ¥ 2 prine(is_even(4)) eine is_even(7)) # output: True Output: False Describe the use of filter(), map() and reduce) functions. “These are higher-order functions available in the funetools module (reduce) and as built-in functions Alte, map in Python 3). ) Biter: flterTuncton, iterable) returns an iterator containing those items for which the function returns True Example: rims = (1, 2, 3, 4, 5, 6] ‘oven = Lise( fitter lambda x: x 8 2 Prine(even) # Output! [2, 4, 6] @) mapo: ‘map(functlon, erable) applies he function to each tem ‘of he iterble sn return an Herter of rests Example: rms = (1, 2, 3, 4) Suares = List(mapClanbda xc x + x, mms) print(squares)# Output! (1, 4, 9, 16] @) reduces): reduce(function, iterable) applies the function ‘Cumulatvely t the tem of the ierable,eeducing the iterate 10a single valve Example: fron functools import reduce us = (1, 2, 3, 4] Suna) = ‘veduce(Lanbda x: y+ y, runs) rine(sumail)—# Output: 10 uns)) |. What is module? How to create and exploring it? Explain with example. ‘A module is a Python file (py) that contains Yarables, functions, and classes. It helps to organize code into reusable units. How to create: (Create a .py file and write functions or variables in it Example: [Link] @ mymodule-py ef oasis, 8). return a+b et greet(nane): return Hello, {nase}! pr = 9.76159 Exploring (using) a module: ‘Weruse the import statement to use a module. Example: inport mywodule prine([Link](5, 7)) Print([Link](Alice")) # Outpt: Hello, Alice! prineGmpmedule.P2) 4 Oupor: 3.14189 ‘We ean also import specific Items: ‘ron mynodule_ieport ad, PT # Output: 12 prine(eaae2, 3))# Output 5 print) 4 Output: 3.14139 (Or use alias: snpect module os prinece- ase, 6)) 2. What is file? How to read and write to a file? A file is named loewtion on disk used to store {ata permanently Opening a fie: ‘We use epen(Filenane, rode) function Modes: # Oupue 10 vend fwite Hello, woriai\n") Cmestet-Pythen Ss. great.") eChose0) prine(cbate westten £0 file.) ‘from a file: Concent = foreage) prineceontent) Fetose) Reading line by Une: 1 = open('[Link]", 4) for Tine in € prine([Link](>) eerese) Appending to a file: { mopen( ata. txt", 2") fC neite(AaTnis Tine appended“) eose0) What is package? How to create and it? Explain with example. A package is a collection of related modules and sub-puckages ina directory, I contains a special file nity. How to create a package: 1. Create 2 directory (package name). 2. aside i create a fle named — init__.py. 3. Add module Mes (py) inside the package. Example: S eatope py mypackage! ser aaa ep ver nahn Py 4 sxrinsons.o7 ringopspy er taper, Using a package: fron [Link] import dd ‘ron [Link] import upper print(ada(1, 209) 4 Output: 30 Prine(upper(*nelio")) 4 ouput! HELLO 5 A directory (folder) is @ container that can hold files ‘and other directories, Create directory using os module: Anport os create 2 directory ([Link]( my folder") Creates single directory ‘[Link]( my felder/sub folder’, exist_okeTrue) 4 exist obsTeue avoids error iF cirectory already exists print(“Directory created suecesstully.”) List directory contents: print([Link](myafeldee”)) 4 Output: lst of fles and folders Inside ‘ny folder’ (Check if directory exists: Print([Link]('my folder") # Ourpn: Tre ot False ‘What is exception? How to handle it? ‘An exception is an error that occurs during the ‘execution of a program. Python provides @ way to handle such errors gracefully using try. except, else and finally blocks. Example of exception handling: my X= AntCangut(Enter a number: °)) result = 10/ x print(*Resule:", result) ‘except Valuetrror print(*tnvalid input! lease enter a rurber.") ‘except ZeroDivistontsrer: Print("Camot divide by zer0.") cause. rint(“Operation successful.) finally Drine(“This block alnays executes.*) Explanation: = Teno exception occurs, ty block runs, then else, and finally Tr exception occurs, the corresponding except block ~ finally block always runs. ‘What is regular expression? Explain with example. Rogular Expression (regen) is patter used to match ‘combinations of characters in sings. Python has & balit-in re module to work with regen. Common patterns: ‘Any single character SES GP tring $2 Bnd of airing * 0 'or more repetitions a 1 oF more repetitions Any one character in the Brackets Ad : Digic 0-9) Ww ! Word character ( 2, AZ, 0-9, text = "Contact me at sbel23@gmal com oF eal 9875845210." malts = re: flndall(r"[V\,-1+@0W\.-J6", 1030) printenaiis) ‘Outputs [aber 30pm com") Find aL phone monbers (10 digits) phones = re: finial (F°\S(1O}", text Printphones) Output? (9876545210°] match = renmatch(e"=AContact”, text) Print(ooo}Gamtch))—# Output: True 10. State the methods of re package in python? ‘The re (regular expression) package in Python provides the following important methods: ‘Method Description rescempile() | Compiles a regular expression pattern into regex object for repeated use. FesmatehO) | Checks if the pattera matches atthe beginning of the sing. [Link]() | Searches the string for the fist ‘currence of the pattern. re-findallQ) | Finds all occurrences of the pattern and returns them a8 lis e-finditer() | Finds all occurrences apd returns an iterator yiekding maich objects. ersub() | Replaces occurrences ofthe pattera with a specified replacement revaplit() | Splits the string by occurrences of the pattern re fullmiteh() | Chocks if the entire sting matches the pattern ‘What is the difference between exception and syntax error? Bxeeption Syntax Beror TExcepiions occur when = program is syntactieally forrest but cases an ror ‘uring execution. ‘Syntax errors occur when the code violates Python sync ruts. ‘They can be handled using ey, except blocks “They cannot be handled at runtime Program may run partially iff exception is handle. ‘Program will not ran a ‘Examples: ZeoDwasontrer, | Examples missing colon ‘leNotFoundeor, Valuer | wrong indentation, unmatched te parentheses ete. ‘Ooours at ranting. ‘Detected at compile me (before execution), ‘State the use of search method of re package with an example. ‘The [Link]() method searches the entire string for the first eccurrence of the pattern and returns ‘a match object if found; otherwise, it returns None. Example: Seport re tent = "Hy nobile number is 9976540220." pattern = c"\d(10)" pattern for 18 cigite inatch = [Link](pactern, text) iF nacch prine("¥atch found prine(*Stare index ise prine("Wo natch found”) 4» output: 1 Mater found: s676540210 Write the use of seek() and tell() function. seek(offset, whence): Used to change the curent ratch-grovp() natch. stare()) (0 from begioning of Me (defat) 1 frem current position 2 from end of file fetid: Returns the current position of the Me poinee (Ga bytes) from the beginning of the fe Beample f= pent [Link]', *F°) print(? tell} # Output: @ (at stat) seek (i0) # Move to 10h byte om start print(?.tel0) Output 30 Framak(i, 1). Move 5 bytes forward from current prine(t-iell@)—# Ostpur 15 Frzcak('S, 2) # Move 5 Bytes backward from end prane(? tell) Freteee() ‘Position from start (depends on file) n. DR. Which methods are used to read from file? Explain two of them with example. ‘Methods used to read from a file in Python: + read) ‘+ readlineg) ‘+ readlines() ‘+ iterator (for line in file) (1) read(): Reads the entire content of the file as fa single string. Example: f= open(‘[Link]', ‘content = [Link]() print (content) F close() # Output: (isplays whole content of the file) (@) readline(): Reals one Tine from the file at time. Example: e) = epen("[Link]', Linel = [Link]() ine2 = [Link]() print(Linel, ende"*) prine(Line2, end="*) felose() 4 Output: (displays first two lines of the file) (Note: readlines() reads all lines and returns them as a ist.) ey W reads first line 1 reads second line How will you copy and rename file in Python?. Copy a fie: ‘Using shutil module fnport shutil shutil-copy("source. txt", ‘destination. txt") 4 copies source. txt to destination txt ‘Using shuti.copy20 (copies with metadata) shutil copy2(‘[Link]', ‘destination xt") Rename a file: Using os module snport 06 [Link](‘oldnane. txt", ‘newnane. tt") 1 Renanes [Link] to newnane, txt Using pathlib module (Python 3.4+) from pathlid import Path ath ‘[Link]")-renane( “oewnene. txt") Example (copy and rename together): {nport shutil, 05 shut copy( report. tat", “backup_report. txt!) [Link]("[Link]', "Final report. txt") # report. tet is first copied, then renamed 13, What is user defined function? Explain with example, ‘A user defined function is a function that is created by the programmer according to their requirement. Te helps to break program into. smaller” parts, improves readability, and allows code reusability ‘Syntax: def Function nane(perameters): statenents return value # optional Example: @ Function Getinition ef ade(e, 6): sun =a eb return sum # Function call X= dne(lnput ("enter first number: “)) y= int(input("Enter second ruber: ”)) Pesult = addix, y) peine("Sum 45:7, result) Outpnt: Enter first umber: 10 sun is: 38 14, Describe various types of regular expressions. RRegulae expressions (regex) ate used to match patterns in suings. Python provides the re module 1 work with regular expressions. Below are various types with examples © Chnrncter match: (et) = Matcics any single character y habe ave ae) (bes wo 1 Mathes tart of the string. '$ —Matches end ofthe string sample re. Finda. (79y", "Python 3s easy") — [Py] (Gl) Character class: [abe] ~ Mateos any one charvctr from 2,8 of ©. [ore] ~ Matches any lowercase lever ham fn Coto, "edeation) > Ce (Gv) Negated character class: [rape] ~ Matches any character except 2,6, 0¢¢- Example re-finaall('(Peeiou]", "apple > CP's ely -e') (0) Qutantiies: {0 — exactly 9 occurrences {hy} — a leant oocurrences {nie} — between n and m occurrences Example: re.findsl1( at", anabocaa") —+ ('93", “a9'] ow \s = whitespace character Example: re-Findall("\\Et", “Room 281 and 202°) + (ie, “292") (ot) Grouping: mba ab") [abe 15. How to listing files and directories? Describe with ‘We can lis files and dzectories in Python using os module. Lis files and directories in curent directory: Stems ~ o8.1istete(*.*) print(iteme) (G)_Lis files and directories ina specific path: Amport o5 tens = 95.1istatr('C:\python") prine¢itens) ‘This returns a lst containing names of files and subsets 16. Write short note on: Operations on file, File handling in Python allows us to perform various ‘operations on files. 1. Open a file: open( Filename, mode) Modes: ‘read, "w" write, a” — append, x! Soreate, “b? binary 2. Read from file: 4 -read() ~ reas entire He readline) = reads one line ‘areadlines() — reads all lines and returns alist 3. Write to te: [Link](string) ~ writes string to fle fowritelines(list) — writes list of ines 4. Append to file: (Open file in append mode Ca") and waite, 5. Close fk Feclose() —closes the file 6. Other operations: f.tel1() —rotums current file pointer positon [Link](offset) — changes file pointer position F truncate(size) ~ resizes the file Example: ‘writing to a file Terite( ‘Fille handling example’) ‘elose() Reading from a file open(‘[Link]", °F) data = [Link]() print data) fclose() “These operations help inefficiently managing file data 17. With the help of example describe how exploring a package? ‘A package isa collection of madules. We ean explore a package using the dir() function. Example: ‘pore math prine(dir(naeh)) ‘The above code displays all the aitibutes and functions available in te math module. ‘We cam also use help() 10 et deta information: import wath elp(mtnsart) ‘This shows the documentation of he eqr&() Function in the math module. 18. List methods for math and random module. (@ Common methods of math module: smath-sqrt(x) — sue root satn-pow(x,y) — x ralsed w power y smata-Factorial(«) ~ factorial of fmath_cotl(x) — smallest inuger 2 math: Floor(«) — largest Integer x fmath-fabe(x) — absolute value mmarn-sin(x), math. cos(x),_ math-tan(x) fmevnLog(s).— nator logan imath-2og48(0) — base-10 logarithm fmm pi — value of fmathie — value of ¢(2.71828..) @ Common methods of random module: [Link]() ~ random flos in (0.8, 2 [Link](a, ) ~ random ineger Been & and b Fanden-untfore(a, b) — random floa between 2 and [Link](see) ~ random clement from sequence random shuffle(iiat) — shufle the lis [Link](population, t) ~ k random items from the population ‘These modules provide useful inbuilt functions. for ‘mathematical and random operations.

You might also like