TCS Python Developer Interview Questions And Answers For Freshers Are Designed To Assess Knowledge Of Python Programming, Object-Oriented Programming, Data Structures, And Problem-Solving Skills. The Technical Interview May Cover Python Fundamentals Such As Variables, Data Types, Operators, Functions, Loops, Exception Handling, Modules, And File Handling. Candidates May Also Be Asked About Advanced Concepts Including Decorators, Generators, Iterators, Lambda Functions, List Comprehensions, And Memory Management. Database Knowledge, SQL Queries, REST APIs, Testing, Git, And Python Frameworks Such As Django Or Flask May Also Be Discussed Depending On The Job Role. Coding Questions Generally Focus On Strings, Lists, Dictionaries, Searching, Sorting, Recursion, Number Problems, And Logical Programming. Freshers Should Also Be Prepared To Explain Academic Projects, Technical Skills, Problem-Solving Approaches, And Their Understanding Of Python Development Practices. This Collection Of TCS Python Developer Interview Questions And Answers Helps Freshers Strengthen Their Technical Preparation And Build Confidence For Python Developer Interview Rounds.
1. What Is Python?
Ans:
Python Is A High-Level, Interpreted, General-Purpose Programming Language Known For Its Simple Syntax And Readability. It Supports Multiple Programming Paradigms Including Object-Oriented, Procedural, And Functional Programming. Python Provides A Large Standard Library And A Wide Range Of Third-Party Packages For Different Development Requirements. It Is Commonly Used In Web Development, Data Science, Automation, Artificial Intelligence, Testing, And Application Development. Python Uses Dynamic Typing, Which Means Variable Types Are Determined At Runtime. Its Simplicity And Extensive Ecosystem Make Python A Popular Choice For Both Beginners And Professional Developers.
2. What Are The Main Features Of Python?
Ans:
Python Provides Several Features That Make It Suitable For Different Software Development Requirements. It Has Simple And Readable Syntax That Helps Developers Write And Maintain Code Efficiently. Python Is Interpreted, Dynamically Typed, Portable, And Supports Object-Oriented Programming. It Provides Automatic Memory Management And A Large Standard Library For Common Programming Tasks. Python Also Supports Modules, Packages, Exception Handling, Iterators, Generators, And Decorators. These Features Make Python Useful For Web Applications, Automation, Data Processing, Testing, And Backend Development.
3. What Is The Difference Between List And Tuple In Python?
Ans:
A List Is A Mutable Collection That Allows Elements To Be Added, Removed, Or Modified After Creation. A Tuple Is An Immutable Collection Whose Elements Cannot Be Changed After It Has Been Created. Lists Are Defined Using Square Brackets, While Tuples Are Generally Defined Using Parentheses. Tuples Can Be Useful For Representing Fixed Collections Of Values That Should Not Change. Lists Provide More Methods For Modification And Are Suitable For Dynamic Data. The Choice Between Them Depends On Whether The Collection Needs To Be Modified During Program Execution.
4. What Is A Dictionary In Python?
Ans:
- A Dictionary Is A Mutable Data Structure Used To Store Data In Key-Value Pairs. Each Key In A Dictionary Should Be Unique And Is Used To Access Its Corresponding Value.
- Dictionaries Are Written Using Curly Braces With Keys And Values Separated By Colons. They Provide Efficient Lookup, Insertion, And Updating Operations In Typical Cases.
- Dictionaries Are Commonly Used To Represent Structured Information Such As User Details, Configuration Values, And Database Records. Python Provides Methods Such As keys(), values(), items(), get(), And update() For Dictionary Operations.
5. What Is A Set In Python?
Ans:
A Set Is An Unordered Collection Of Unique Elements In Python. Duplicate Values Are Automatically Removed When Data Is Stored In A Set. Sets Support Mathematical Operations Such As Union, Intersection, Difference, And Symmetric Difference. They Are Useful When Fast Membership Checking Or Unique Values Are Required. Sets Are Mutable, Although Their Individual Elements Must Be Hashable. Common Set Methods Include add(), remove(), discard(), union(), And intersection().
6. What Is The Difference Between Mutable And Immutable Objects?
Ans:
Mutable Objects Can Be Changed After They Are Created, While Immutable Objects Cannot Be Modified After Creation. Lists, Dictionaries, And Sets Are Common Examples Of Mutable Objects In Python. Integers, Floats, Strings, And Tuples Are Common Examples Of Immutable Objects. When An Immutable Object Appears To Be Modified, Python Creates A New Object Instead Of Changing The Existing Object. Understanding Mutability Is Important For Avoiding Unexpected Changes When Objects Are Shared Between Variables. It Also Affects Function Arguments, Memory Usage, Hashing, And Dictionary Key Usage.
7. What Are Variables In Python?
Ans:
Variables In Python Are Names Used To Refer To Objects Stored In Memory. Python Does Not Require Explicit Declaration Of A Variable’s Data Type Before Assigning A Value. The Type Of An Object Is Determined Dynamically At Runtime. A Variable Can Refer To Different Types Of Objects At Different Points In A Program. Python Supports Variables Containing Numbers, Strings, Collections, Objects, Functions, And Other Values. Meaningful Variable Names Improve Code Readability And Make Programs Easier To Maintain.
8. What Are Python Data Types?
Ans:
Python Provides Several Built-In Data Types For Representing Different Kinds Of Information. Numeric Types Include Integer, Float, And Complex Numbers, While Boolean Represents True Or False Values. String Is Used For Text, And Collection Types Include List, Tuple, Set, And Dictionary. Python Also Supports Special Values Such As None To Represent The Absence Of A Value. Developers Can Create Custom Data Types Using Classes. Choosing Appropriate Data Types Helps Improve Code Clarity, Correctness, And Efficiency.
9. What Is Type Casting In Python?
Ans:
- Type Casting Is The Process Of Converting A Value From One Data Type Into Another Compatible Data Type. Python Provides Built-In Functions Such As int(), float(), str(), list(), tuple(), And set() For Common Conversions.
- For Example, A Numeric String Can Sometimes Be Converted Into An Integer Using int(). Some Conversions May Cause Data Loss, Such As Converting A Floating-Point Number Into An Integer.
- Invalid Conversions Can Raise Exceptions Such As ValueError. Type Casting Is Commonly Used When Processing User Input, Files, APIs, And Database Data.
10. What Is A Function In Python?
Ans:
A Function Is A Reusable Block Of Code Designed To Perform A Specific Task. Functions Can Accept Input Through Parameters And Can Return Results Using The return Statement. They Help Reduce Code Duplication And Improve Program Organization. Python Allows Functions To Have Default Arguments, Keyword Arguments, Variable-Length Arguments, And Type Annotations. Functions Can Also Be Passed As Arguments To Other Functions Because Python Treats Functions As First-Class Objects. Well-Designed Functions Improve Code Reusability, Testing, Readability, And Maintenance.
11. What Is A Lambda Function?
Ans:
A Lambda Function Is A Small Anonymous Function Created Using The lambda Keyword. It Can Contain A Single Expression And Is Often Used For Short Operations. Lambda Functions Are Frequently Used With Functions Such As map(), filter(), And sorted(). They Can Make Simple Transformations More Concise When A Separate Named Function Is Unnecessary. However, Complex Logic Is Usually Better Written Using A Regular Function For Readability. Lambda Functions Are Commonly Asked In Python Interviews To Test Knowledge Of Functional Programming Concepts.
12. What Are *args And **kwargs?
Ans:
*args Allows A Python Function To Accept A Variable Number Of Positional Arguments. These Arguments Are Collected Inside A Tuple During Function Execution. **kwargs Allows A Function To Accept A Variable Number Of Keyword Arguments. These Arguments Are Collected Inside A Dictionary. Both Features Are Useful When Designing Flexible Functions That Need To Handle Different Numbers Of Inputs. They Are Frequently Used In Frameworks, Utility Functions, Wrappers, And Reusable Python Components.
13. What Is List Comprehension?
Ans:
List Comprehension Is A Concise Way Of Creating A New List From An Existing Iterable. It Can Include An Expression, A Loop, And An Optional Conditional Filter. List Comprehensions Often Make Simple Transformation And Filtering Operations More Readable Than Traditional Loops. For Example, A List Of Squares Can Be Created From A Range Using A Single Expression. They Can Improve Code Conciseness But Should Not Be Used For Very Complex Logic. Python Also Supports Similar Comprehension Syntax For Sets, Dictionaries, And Generators.
14. What Is A Generator In Python?
Ans:
- A Generator Is An Iterator That Produces Values Lazily Instead Of Creating And Storing All Values In Memory At Once. Generators Are Commonly Created Using Functions Containing The yield Statement.
- Each Call To yield Produces A Value And Suspends Execution Until The Next Value Is Requested. This Makes Generators Memory-Efficient For Processing Large Datasets Or Streams Of Data.
- Generators Can Be Iterated Using A for Loop Or The next() Function. They Are Useful For File Processing, Data Pipelines, And Large Sequence Operations.
15. What Is The Difference Between Yield And Return?
Ans:
The return Statement Ends A Function And Sends A Result Back To The Caller. The yield Statement Produces A Value While Pausing The Function’s Execution State. A Function Containing yield Becomes A Generator And Can Continue From The Same Point When The Next Value Is Requested. return Is Suitable When A Function Needs To Produce A Final Result. yield Is Useful When Values Need To Be Produced Incrementally. Generators Using yield Can Reduce Memory Consumption When Processing Large Amounts Of Data.
16. What Is An Iterator In Python?
Ans:
An Iterator Is An Object That Produces Values One At A Time During Iteration. It Implements The __iter__() And __next__() Methods According To Python’s Iterator Protocol. The iter() Function Can Be Used To Obtain An Iterator From An Iterable Object. The next() Function Retrieves The Next Available Value From The Iterator. When No More Values Are Available, The Iterator Raises StopIteration. Iterators Support Memory-Efficient Processing Of Collections, Streams, Files, And Generated Data.
17. What Is A Decorator In Python?
Ans:
A Decorator Is A Function That Extends Or Modifies The Behavior Of Another Function Or Class Without Directly Changing Its Source Code. Decorators Are Commonly Used For Logging, Authentication, Caching, Timing, Validation, And Access Control. The @decorator Syntax Provides A Convenient Way To Apply A Decorator To A Function. Python Treats Functions As First-Class Objects, Which Makes Decorator Implementation Possible. Multiple Decorators Can Be Applied To A Single Function. Understanding Decorators Is Important For Working With Python Frameworks And Advanced Application Design.
18. What Is Object-Oriented Programming In Python?
Ans:
Object-Oriented Programming Is A Programming Approach That Organizes Code Around Objects And Classes. Python Supports Core OOP Concepts Such As Encapsulation, Inheritance, Polymorphism, And Abstraction. A Class Defines The Structure And Behavior Of Objects, While An Object Represents An Instance Of A Class. OOP Helps Organize Large Applications Into Reusable And Maintainable Components. Python Allows Methods, Attributes, Constructors, Inheritance, And Special Methods To Be Defined Within Classes. OOP Is Widely Used In Web Applications, Frameworks, Enterprise Software, And Backend Development.
19. What Is A Class In Python?
Ans:
A Class Is A Blueprint Used To Create Objects With Common Attributes And Behaviors. It Can Contain Variables Called Attributes And Functions Called Methods. The __init__() Method Is Commonly Used To Initialize Object Attributes When An Instance Is Created. Multiple Objects Can Be Created From The Same Class, With Each Object Maintaining Its Own State. Classes Help Organize Related Data And Functionality Into Reusable Components. They Are Fundamental To Object-Oriented Programming In Python.
20. What Is An Object In Python?
Ans:
- An Object Is An Instance Of A Class That Contains Data And Behavior Defined By The Class. Objects Store Their State Through Attributes And Provide Functionality Through Methods.
- Multiple Objects Can Be Created From The Same Class With Different Attribute Values. Python Treats Almost Everything As An Object, Including Numbers, Strings, Functions, And Classes. Objects Communicate By Calling Methods And Accessing Appropriate Attributes.
- Understanding Objects Is Essential For Working With Python’s Object-Oriented Programming Model.
21. What Is Inheritance In Python?
Ans:
Inheritance Allows A Child Class To Acquire Attributes And Methods From A Parent Class. It Promotes Code Reuse And Allows Related Classes To Share Common Functionality. Python Supports Single, Multiple, Multilevel, Hierarchical, And Hybrid Forms Of Inheritance. A Child Class Can Override Parent Methods When Different Behavior Is Required. The super() Function Can Be Used To Access Parent Class Functionality. Inheritance Should Be Used When There Is A Meaningful Relationship Between The Parent And Child Classes.
22. What Is Polymorphism In Python?
Ans:
Polymorphism Means That The Same Interface Or Method Name Can Represent Different Behaviors Depending On The Object Using It. Python Supports Polymorphism Through Method Overriding, Duck Typing, Operator Overloading, And Other Techniques. For Example, Different Classes Can Implement A Method With The Same Name But Provide Different Implementations. This Allows Code To Work With Objects Through Common Interfaces Without Depending On Their Exact Types. Polymorphism Improves Flexibility And Extensibility In Object-Oriented Applications. It Is Particularly Useful When Designing Reusable Components And Frameworks.
23. What Is Encapsulation In Python?
Ans:
Encapsulation Is The Concept Of Combining Data And Methods Within A Class And Controlling How Internal State Is Accessed. Python Uses Naming Conventions And Language Features To Indicate Public, Protected, And Private-Like Members. A Single Leading Underscore Commonly Indicates An Internal Or Protected Member By Convention. Double Leading Underscores Trigger Name Mangling For Certain Class Attributes. Encapsulation Helps Prevent Unintended Direct Modification Of Internal State. It Also Improves Code Organization, Maintainability, And Control Over Object Behavior.
24. What Is Abstraction In Python?
Ans:
- Abstraction Is The Process Of Hiding Unnecessary Implementation Details And Exposing Only The Essential Interface. It Allows Users Of A Class To Focus On What An Object Does Instead Of How It Performs Its Operations.
- Python Supports Abstraction Through Abstract Base Classes And The abc Module. Abstract Methods Define Operations That Subclasses Are Expected To Implement.
- Abstraction Helps Create Clear Interfaces And Reduce Complexity In Large Applications. It Is Useful When Multiple Implementations Need To Follow A Common Design.
25. What Is The Difference Between Is And == In Python?
Ans:
| Aspect | Is | == |
|---|---|---|
| Purpose | Checks Whether Two Variables Refer To The Same Object | Checks Whether Two Objects Have Equal Values |
| Comparison | Compares Object Identity | Compares Object Equality |
| Usage | Commonly Used To Check Against None | Commonly Used To Compare Strings, Numbers, And Other Values |
| Example | a is b Checks If Both Refer To The Same Object | a == b Checks If Both Have The Same Value |
26. What Is Exception Handling In Python?
Ans:
Exception Handling Is A Mechanism Used To Manage Runtime Errors Without Abruptly Terminating A Program. Python Provides try, except, else, And finally Blocks For Handling Exceptions. Code That May Cause An Exception Can Be Placed Inside The try Block. Matching Errors Can Be Handled In The except Block, While finally Can Execute Cleanup Code Regardless Of Whether An Exception Occurs. Proper Exception Handling Improves Application Reliability And User Experience. Specific Exceptions Should Usually Be Handled Instead Of Catching Every Possible Error With A Generic Exception.
27. What Is The Difference Between Syntax Error And Exception?
Ans:
A Syntax Error Occurs When Python Code Does Not Follow The Language’s Required Syntax Rules. Such Errors Are Usually Detected Before The Program Can Execute The Incorrect Statement. An Exception Is A Runtime Error That Occurs While A Syntactically Valid Program Is Executing. Examples Of Exceptions Include ValueError, TypeError, KeyError, IndexError, And ZeroDivisionError. Syntax Errors Must Be Corrected In The Code Structure, While Exceptions Can Often Be Managed Using Exception Handling. Understanding Both Types Helps Developers Diagnose And Fix Python Programs Efficiently.
28. What Is The Finally Block?
The finally Block Is Used In Exception Handling To Execute Code Regardless Of Whether An Exception Occurs. It Is Commonly Used For Cleanup Operations Such As Closing Files, Database Connections, Or Network Resources. A finally Block Can Follow try And except Blocks. Even When An Exception Is Raised And Handled, The finally Block Is Normally Executed. This Makes It Useful For Ensuring That Important Resources Are Released Properly. Context Managers Using The with Statement Are Often Preferred For Resource Management When Available.
29. What Is File Handling In Python?
Ans:
- File Handling Allows Python Programs To Read From And Write Data To Files. The Built-In open() Function Is Used To Open Files With Modes Such As Read, Write, Append, And Binary Modes.
- The with Statement Is Commonly Used To Open Files Because It Automatically Handles Resource Cleanup. Python Provides Methods Such As read(), readline(), readlines(), And write() For File Operations.
- Files Can Contain Text, CSV Data, JSON Data, Logs, Or Other Information. Proper File Handling Requires Appropriate Encoding, Error Handling, And Resource Management.
30. What Is A Module In Python?
Ans:
A Module Is A Python File Containing Code Such As Functions, Classes, Variables, Or Executable Statements. Modules Help Divide Large Programs Into Smaller And Reusable Components. A Module Can Be Imported Using The import Statement Or Specific Objects Can Be Imported From It. Python Provides Many Built-In Modules Such As os, math, datetime, json, And re. Developers Can Also Create Custom Modules For Project-Specific Functionality. Modular Programming Improves Organization, Reusability, Testing, And Maintainability.
31. What Is A Package In Python?
Ans:
A Package Is A Collection Of Related Python Modules Organized Within A Directory Structure. Packages Help Organize Large Applications Into Logical Components. Modern Python Packages Can Use An __init__.py File, Although Namespace Packages Provide Alternative Structures. Packages Can Contain Multiple Modules, Subpackages, And Supporting Resources. They Can Be Imported Using Standard Python Import Statements. Proper Package Organization Makes Large Python Projects Easier To Maintain, Test, And Reuse.
32. What Is PIP In Python?
Ans:
PIP Is The Standard Package Management Tool Commonly Used To Install And Manage Python Packages. It Can Download Packages From The Python Package Index And Other Configured Sources. Commands Such As pip install, pip uninstall, And pip list Help Manage Project Dependencies. A Requirements File Can Be Used To Record Package Versions Needed By A Project. Virtual Environments Are Commonly Combined With PIP To Keep Project Dependencies Isolated. Proper Dependency Management Helps Make Python Applications Reproducible Across Development And Deployment Environments.
33. What Is A Virtual Environment In Python?
Ans:
A Virtual Environment Is An Isolated Python Environment Used To Manage Project-Specific Dependencies. It Allows Different Projects To Use Different Package Versions Without Conflicting With Each Other. Python’s venv Module Can Be Used To Create Virtual Environments. Developers Can Activate The Environment And Install Required Packages Independently Of The Global Python Installation. Virtual Environments Help Improve Reproducibility And Simplify Application Deployment. They Are Commonly Used In Professional Python Development And Software Projects.
34. What Is Garbage Collection In Python?
Ans:
Garbage Collection Is The Process Of Automatically Managing And Reclaiming Memory That Is No Longer Needed By A Python Program. Python Primarily Uses Reference Counting To Track How Many References Point To Objects. When An Object’s Reference Count Reaches Zero, Its Memory Can Usually Be Reclaimed. Python Also Provides A Garbage Collector To Detect Certain Reference Cycles That Reference Counting Alone Cannot Handle. Automatic Memory Management Reduces The Need For Developers To Manually Free Memory. Understanding Garbage Collection Can Help Diagnose Memory Usage Problems In Long-Running Applications.
35. What Is Reference Counting?
Ans:
Reference Counting Is A Memory Management Technique Used By Python To Track References To Objects. Each Object Maintains Information About How Many Active References Point To It. When The Reference Count Becomes Zero, The Object Can Generally Be Deallocated. Reference Counting Allows Many Objects To Be Cleaned Up Quickly Without Waiting For A Separate Garbage Collection Cycle. However, Circular References Can Prevent Reference Counts From Reaching Zero. Python’s Garbage Collector Helps Handle Such Cyclic Reference Cases.
36. What Is Shallow Copy And Deep Copy?
Ans:
- A Shallow Copy Creates A New Outer Object But Keeps References To Nested Objects From The Original Structure.
- A Deep Copy Recursively Creates Copies Of Nested Objects As Well. Python Provides The copy Module With copy() And deepcopy() Functions For These Operations. Shallow Copies Can Be Faster And Are Suitable When Shared Nested Objects Are Intended.
- Deep Copies Are Useful When Completely Independent Nested Data Is Required. Choosing The Correct Copy Method Helps Prevent Unexpected Changes In Mutable Nested Structures.
37. What Is The Difference Between Append And Extend?
Ans:
The append() Method Adds A Single Object As One Element To The End Of A List. The extend() Method Adds Each Element From An Iterable To The Existing List. For Example, Appending A List Adds That Entire List As One Nested Element. Extending With A List Adds Its Individual Elements To The Existing List. Both Methods Modify The Original List Rather Than Creating A New List. Understanding Their Difference Is Important When Working With Dynamic Collections.
38. What Is The Difference Between Remove, Pop, And Del?
Ans:
The remove() Method Deletes The First Matching Value From A List. The pop() Method Removes And Returns An Element At A Specified Index, Or The Last Element When No Index Is Provided. The del Statement Can Delete An Element, A Slice, Or Even An Entire Variable. remove() Works Based On Value, While pop() Primarily Works Based On Position. del Provides Broader Deletion Capabilities Across Python Objects. Selecting The Appropriate Operation Depends On Whether The Value, Index, Or Object Reference Needs To Be Removed.
39. What Is String Slicing In Python?
Ans:
String Slicing Is A Technique Used To Extract A Portion Of A String Using Start, Stop, And Optional Step Values. Python Uses The Syntax string[start:stop:step] For Slicing. The Start Index Is Included, While The Stop Index Is Excluded. Negative Indices Can Be Used To Access Characters From The End Of A String. A Negative Step Can Be Used To Reverse A String Or Traverse It Backward. String Slicing Is Useful For Text Processing, Data Extraction, Validation, And Simple String Transformations..
40. What Is The Difference Between Sort And Sorted?
Ans:
The sort() Method Sorts A Mutable List In Place And Returns None. The sorted() Function Accepts An Iterable And Returns A New Sorted List Without Modifying The Original Iterable. Both Support Options Such As key And reverse For Customized Sorting. sort() Is Appropriate When Modifying An Existing List Is Acceptable. sorted() Is Useful When The Original Collection Needs To Remain Unchanged. Understanding The Difference Helps Prevent Unexpected Data Modification In Python Programs.
41. What Is Recursion In Python?
Ans:
Recursion Is A Programming Technique In Which A Function Calls Itself To Solve A Problem By Breaking It Into Smaller Similar Problems. A Recursive Function Requires A Base Condition To Stop Further Calls. Without A Proper Base Case, The Function Can Continue Calling Itself Until Python Raises A Recursion-Related Error. Recursion Is Commonly Used For Tree Traversal, Graph Algorithms, Searching, And Mathematical Problems. It Can Produce Elegant Solutions But May Consume Significant Stack Space. Iterative Solutions Can Sometimes Be More Efficient For Large Inputs.
42. What Is A Regular Expression In Python?
Ans:
- A Regular Expression Is A Pattern Used To Search, Match, Extract, Or Replace Text Based On Specific Rules. Python Provides The re Module For Regular Expression Operations.
- Common Functions Include search(), match(), findall(), sub(), And split(). Regular Expressions Can Be Used For Email Validation, Log Processing, Text Extraction, And Data Cleaning.
- They Support Patterns For Characters, Digits, Groups, Repetition, And Positions. Complex Regular Expressions Should Be Written Carefully Because They Can Become Difficult To Read And Maintain.
43. What Is JSON Handling In Python?
Ans:
JSON Handling Allows Python Applications To Exchange And Store Data Using The JavaScript Object Notation Format. Python Provides The Built-In json Module For Converting Between JSON And Python Objects. json.loads() Converts A JSON String Into A Python Object, While json.dumps() Converts A Python Object Into A JSON String. JSON Files Can Also Be Read And Written Using json.load() And json.dump(). JSON Is Widely Used In REST APIs, Configuration Files, Web Applications, And Data Exchange. Proper Validation And Error Handling Are Important When Processing External JSON Data.
44. What Is Pickling In Python?
Ans:
Pickling Is A Python Mechanism Used To Serialize Python Objects Into A Byte Stream. The pickle Module Provides Functions Such As dump() And load() For Saving And Restoring Objects. Pickling Can Be Useful For Storing Python-Specific Objects Or Temporary Application State. Unlike JSON, Pickle Is Python-Specific And Can Preserve More Complex Python Object Structures. Pickle Data Should Not Be Loaded From Untrusted Sources Because Deserialization Can Execute Malicious Code. For Interoperable Data Exchange, Formats Such As JSON Are Often More Appropriate.
45. What Is Multithreading In Python?
Ans:
Multithreading Allows Multiple Threads To Execute Within The Same Process And Can Be Useful For I/O-Bound Tasks. Python Provides The threading Module For Creating And Managing Threads. Threads Can Help Improve Responsiveness When Programs Spend Significant Time Waiting For Network, File, Or Other I/O Operations. The Global Interpreter Lock Can Limit CPU-Bound Parallel Execution Of Python Bytecode In Standard CPython. Synchronization Tools Such As Locks And Events May Be Required When Threads Share Mutable Data. Threading Should Be Used Carefully To Avoid Race Conditions And Deadlocks.
46. What Is Multiprocessing In Python?
Ans:
Multiprocessing Uses Multiple Processes To Execute Tasks Independently And Can Provide True Parallelism For CPU-Bound Workloads. Python Provides The multiprocessing Module For Creating And Managing Processes. Each Process Has Its Own Memory Space, Which Helps Avoid Some Shared-State Problems. Multiprocessing Can Be Useful For Computationally Intensive Tasks Such As Large Numerical Calculations And Data Processing. Process Creation And Inter-Process Communication Can Introduce Additional Overhead. The Appropriate Choice Between Threads And Processes Depends On Whether The Workload Is Primarily I/O-Bound Or CPU-Bound.
47. What Is The GIL In Python?
Ans:
The Global Interpreter Lock Is A Mechanism In Standard CPython That Allows Only One Thread At A Time To Execute Python Bytecode Within A Process. The GIL Simplifies Certain Aspects Of Memory Management And CPython’s Object Model. It Can Limit The Benefits Of CPU-Bound Multithreading For Python Code. I/O-Bound Programs Can Still Benefit From Threads Because The Interpreter Can Release The GIL During Many Blocking Operations. CPU-Bound Workloads Can Often Use Multiprocessing Or Native Extensions To Achieve Greater Parallelism. Understanding The GIL Helps Developers Select Appropriate Concurrency Approaches.
48. What Is A Context Manager In Python?
Ans:
- A Context Manager Controls The Setup And Cleanup Of Resources Around A Block Of Code. It Is Commonly Used With The with Statement.
- Files Are A Common Example Because The Context Manager Automatically Closes The File After The Block Finishes. Context Managers Can Also Manage Database Connections, Locks, Transactions, And Other Resources.
- Custom Context Managers Can Be Created Using __enter__() And __exit__() Methods Or The contextlib Module. They Help Make Resource Management Safer, Cleaner, And Less Error-Prone.
49. What Is Unit Testing In Python?
Ans:
Unit Testing Is The Process Of Testing Individual Functions, Methods, Or Small Components Independently. Python Provides The Built-In unittest Framework For Creating And Running Unit Tests. Tests Typically Verify Expected Outputs, Exceptions, Boundary Conditions, And Other Behaviors. Automated Unit Tests Help Detect Regression Problems When Code Changes Are Introduced. Mocking Can Be Used To Isolate External Dependencies Such As APIs, Databases, Or Services. Well-Written Unit Tests Improve Code Reliability, Maintainability, And Development Confidence.
50. What Is Pytest?
Ans:
Pytest Is A Popular Python Testing Framework Used To Create Simple And Scalable Automated Tests. It Supports Plain Python Assertions, Fixtures, Parameterized Tests, Plugins, And Test Discovery. Pytest Usually Requires Less Boilerplate Than The Standard unittest Framework. Fixtures Help Prepare And Clean Up Test Data Or Resources Before And After Tests. Pytest Can Be Integrated Into Continuous Integration And Deployment Pipelines. It Is Commonly Used For Unit Testing, Integration Testing, API Testing, And Regression Testing.
51. What Is PEP 8?
Ans:
PEP 8 Is The Official Python Style Guide That Provides Recommendations For Writing Readable And Consistent Python Code. It Covers Naming Conventions, Indentation, Line Length, Imports, Whitespace, Comments, And Code Organization. Following PEP 8 Helps Different Developers Understand And Maintain The Same Codebase. Tools Such As Linters And Formatters Can Automatically Detect Or Correct Many Style Issues. PEP 8 Does Not Define Program Logic But Establishes Consistent Coding Practices. Professional Python Projects Often Follow PEP 8 Or A Related Team Coding Standard.
52. What Is Python Namespace?
Ans:
A Namespace Is A Mapping Between Names And The Objects To Which Those Names Refer. Python Uses Different Namespaces For Local Variables, Global Variables, Built-In Names, And Modules Or Classes. A Local Namespace Exists Within A Function, While A Global Namespace Belongs To A Module. Python Searches For Names According To The LEGB Rule, Which Represents Local, Enclosing, Global, And Built-In Scopes. Understanding Namespaces Helps Explain Variable Visibility And Name Resolution. Proper Namespace Management Reduces Naming Conflicts And Improves Code Organization.
53. What Is Scope In Python?
Ans:
Scope Defines The Region Of A Python Program Where A Particular Name Can Be Accessed. Python Uses The LEGB Rule To Search For Names In Local, Enclosing, Global, And Built-In Scopes. Variables Created Inside A Function Generally Belong To The Local Scope. The global And nonlocal Keywords Can Be Used In Specific Situations To Modify Names In Outer Scopes. Understanding Scope Helps Prevent Unexpected Variable Behavior And Naming Conflicts. Good Programming Practice Usually Avoids Excessive Reliance On Global Variables.
54. What Is The Difference Between Local And Global Variables?
Ans:
A Local Variable Is Defined Within A Function And Is Generally Accessible Only Within That Function. A Global Variable Is Defined At The Module Level And Can Be Accessed By Functions In That Module Under Appropriate Conditions. The global Keyword Can Be Used When A Function Needs To Rebind A Global Variable. Excessive Use Of Global Variables Can Make Code Harder To Test And Maintain. Local Variables Usually Provide Better Encapsulation And Reduce Unintended Side Effects. Choosing The Appropriate Scope Helps Create Cleaner And More Predictable Programs.
55. What Is The LEGB Rule?
Ans:
- The LEGB Rule Describes The Order Python Uses To Search For A Name During Name Resolution. Python First Searches The Local Scope Of The Current Function.
- It Then Searches Enclosing Function Scopes, Followed By The Global Module Scope. Finally, It Searches The Built-In Namespace For Names Such As len And print.
- Understanding LEGB Helps Developers Diagnose Variable Shadowing And Name Resolution Problems. It Is An Important Concept For Functions, Closures, Nested Functions, And Modules.
56. What Is A Closure In Python?
Ans:
A Closure Is A Function That Remembers And Can Access Variables From An Enclosing Scope Even After The Enclosing Function Has Finished Execution. Closures Are Created When An Inner Function References Variables Defined In Its Outer Function. They Are Useful For Maintaining State Without Using Global Variables. Closures Are Commonly Used In Decorators, Callbacks, And Function Factories. The nonlocal Keyword Can Be Used To Modify Variables In The Enclosing Function Scope. Understanding Closures Helps With Advanced Python Functional Programming Concepts.
57. What Is A Python Package Manager?
Ans:
A Python Package Manager Is A Tool Used To Install, Upgrade, Remove, And Manage External Python Libraries. PIP Is The Most Common Package Manager For Standard Python Projects. Modern Python Projects May Also Use Tools Such As Poetry, Pipenv, Or Other Dependency Management Systems. Package Managers Help Resolve Dependencies And Maintain Reproducible Development Environments. Dependency Version Files Can Record The Required Packages For An Application. Effective Package Management Is Important For Development, Testing, Deployment, And Collaboration.
58. What Is The Difference Between Import And From Import?
Ans:
| Aspect | Import | From Import |
|---|---|---|
| Syntax | import math | from math import sqrt |
| Usage | Access Members Using The Module Name | Access Imported Members Directly |
| Readability | Clearly Shows The Module Source | Can Be More Concise |
| Example | math.sqrt(25) | sqrt(25) |
59. What Is Main Function In Python?
Ans:
Python Does Not Require A Special Main Function For Every Program, But A Common Convention Is To Use A main() Function For Program Entry Logic. The Conditional if __name__ == “__main__”: Ensures That Certain Code Runs Only When The File Is Executed Directly. When The File Is Imported As A Module, That Block Does Not Execute. This Structure Helps Separate Reusable Functions From Script Execution Logic. It Makes Modules Easier To Test And Reuse. The Pattern Is Widely Used In Professional Python Applications And Command-Line Programs.
60. What Is init.py?
Ans:
__init__.py Is A Special Python File Historically Used To Mark A Directory As A Package. It Can Also Contain Package Initialization Code And Define Which Names Are Exposed At The Package Level. Modern Python Supports Namespace Packages Without Requiring This File In Every Package Structure. However, __init__.py Remains Common In Many Python Projects. It Helps Organize Package-Level Imports And Initialization Behavior. Understanding Its Purpose Is Useful When Working With Multi-Module Python Applications.
61. What Is Django?
Ans:
Django Is A High-Level Python Web Framework Used To Build Secure And Maintainable Web Applications. It Follows A Model-Template-View Architecture And Provides Many Built-In Features For Common Web Development Requirements. These Features Include URL Routing, Object-Relational Mapping, Authentication, Forms, Middleware, And Administrative Interfaces. Django Encourages Reusable Components And Convention-Based Development. It Can Be Used For Content Management Systems, Business Applications, APIs, And Large Web Platforms. Django Is Popular For Projects That Require A Feature-Rich Python Backend Framework.
62. What Is Flask?
Ans:
Flask Is A Lightweight Python Web Framework Designed For Building Web Applications And APIs. It Provides Core Web Development Features Such As Routing, Request Handling, Templates, And Development Server Support. Flask Uses A Minimal Core And Allows Developers To Add Extensions Based On Project Requirements. This Makes It Flexible For Small Applications, Microservices, REST APIs, And Prototypes. Compared With Larger Frameworks, Flask Provides Fewer Built-In Components And Gives Developers More Architectural Freedom. Its Simplicity Makes It Commonly Used For Python Backend And API Development.
63. What Is REST API?
Ans:
- A REST API Is An Application Programming Interface Designed Around REST Principles For Communication Between Distributed Systems. REST APIs Commonly Use HTTP Methods Such As GET, POST, PUT, PATCH, And DELETE.
- Resources Are Usually Represented Through URLs, And Data Is Frequently Exchanged Using JSON. REST Services Are Generally Stateless, Meaning Each Request Contains The Information Required To Process It.
- Proper Status Codes Help Communicate Success Or Failure To Clients. REST APIs Are Widely Used To Connect Web Applications, Mobile Applications, Microservices, And External Systems.
64. What Is JSON In REST API?
Ans:
JSON Is A Lightweight Text-Based Data Format Commonly Used To Exchange Information Between REST API Clients And Servers. It Represents Data Using Objects, Arrays, Strings, Numbers, Boolean Values, And Null. Python Provides The json Module For Converting Between JSON And Python Data Structures. JSON Is Human-Readable And Supported By Most Modern Programming Languages. REST APIs Commonly Return JSON Responses And Accept JSON Request Bodies. Proper Validation Is Important Because API Data Can Come From External And Untrusted Source.
65. What Is ORM?
Ans:
ORM Stands For Object-Relational Mapping And Provides A Way To Interact With Relational Databases Using Programming Language Objects. Instead Of Writing Every SQL Query Manually, Developers Can Work With Classes And Objects Representing Database Tables And Records. Django Includes Its Own ORM For Managing Database Models And Queries. ORMs Can Improve Developer Productivity And Reduce Repetitive Database Code. They Also Provide Abstractions For Relationships, Filtering, Transactions, And Query Construction. Developers Should Still Understand SQL Because Complex Queries And Performance Optimization May Require Database-Level Knowledge.
66. What Is SQL Injection?
Ans:
SQL Injection Is A Security Vulnerability That Occurs When Untrusted Input Is Improperly Incorporated Into SQL Statements. An Attacker May Manipulate Input To Change The Intended Meaning Of A Database Query. Parameterized Queries And Proper ORM Usage Can Help Prevent SQL Injection. Input Validation And Least-Privilege Database Access Provide Additional Security Layers. SQL Queries Should Not Be Constructed By Directly Concatenating Untrusted User Input. Secure Coding Practices Are Essential When Developing Python Applications That Interact With Databases.
67. What Is Database Connectivity In Python?
Ans:
Database Connectivity Allows Python Applications To Communicate With Databases For Reading, Inserting, Updating, And Deleting Data. Python Provides Database-Specific Drivers And Libraries For Systems Such As PostgreSQL, MySQL, Oracle, And SQLite. A Typical Workflow Includes Creating A Connection, Executing Queries, Processing Results, Managing Transactions, And Closing Resources. Parameterized Queries Should Be Used To Reduce Security Risks Such As SQL Injection. Connection Pooling Can Improve Performance In Applications With Frequent Database Access. Proper Error Handling And Transaction Management Are Important For Reliable Database Operations.
68. What Is Pandas?
Ans:
Pandas Is A Python Library Commonly Used For Data Manipulation And Analysis. Its Main Data Structures Include Series And DataFrame, Which Provide Convenient Ways To Work With Tabular Data. Pandas Supports Filtering, Grouping, Sorting, Joining, Reshaping, Missing Value Handling, And Aggregation. It Can Read Data From Sources Such As CSV Files, Excel Files, JSON, And SQL Databases. Pandas Is Frequently Used In Data Analysis, Data Cleaning, And Machine Learning Preparation. Its Integration With NumPy And Visualization Libraries Makes It Valuable For Data-Oriented Python Applications.
69. What Is NumPy?
Ans:
NumPy Is A Python Library Designed For Numerical Computing And Efficient Array Operations. Its Core Data Structure Is The Multidimensional NumPy Array, Which Supports Fast Mathematical Calculations. NumPy Provides Functions For Linear Algebra, Statistics, Random Number Generation, And Array Manipulation. It Often Performs Numerical Operations More Efficiently Than Standard Python Loops. Many Python Data Science Libraries Build Their Functionality On Top Of NumPy. NumPy Is Widely Used In Scientific Computing, Machine Learning, Data Processing, And Numerical Analysis.
70. What Is The Difference Between NumPy Array And Python List?
Ans:
- A Python List Can Store Elements Of Different Data Types And Provides Flexible General-Purpose Collection Handling. A NumPy Array Is Designed Primarily For Numerical Computation And Usually Stores Elements In A More Homogeneous Data Type.
- NumPy Arrays Support Vectorized Mathematical Operations Without Explicit Python Loops In Many Cases.
- They Can Provide Better Performance And Memory Efficiency For Large Numerical Datasets. Python Lists Are Often More Suitable For General-Purpose Collections And Heterogeneous Data.
71. What Is Data Serialization?
Ans:
Data Serialization Is The Process Of Converting An Object Or Data Structure Into A Format That Can Be Stored Or Transmitted. Common Python Serialization Formats Include JSON, Pickle, CSV, And Various Binary Formats. Deserialization Converts The Stored Or Transmitted Representation Back Into A Usable Object Or Data Structure. Serialization Is Commonly Used In APIs, File Storage, Caching, Messaging, And Distributed Applications. The Chosen Format Should Consider Security, Interoperability, Performance, And Data Complexity. Untrusted Serialized Data Should Always Be Handled Carefully To Avoid Security Risks.
72. What Is Logging In Python?
Ans:
Logging Is The Process Of Recording Application Events, Errors, Warnings, And Informational Messages During Program Execution. Python Provides The Built-In logging Module For Creating Structured And Configurable Logs. Common Logging Levels Include DEBUG, INFO, WARNING, ERROR, And CRITICAL. Logging Helps Developers Diagnose Problems And Monitor Application Behavior In Development And Production. Logs Can Be Written To Files, Consoles, Or Centralized Logging Systems. Proper Logging Should Provide Useful Context Without Exposing Sensitive Information..
73. What Is Multithreading Vs Multiprocessing?
Ans:
Multithreading Uses Multiple Threads Within The Same Process, While Multiprocessing Uses Multiple Independent Processes. Threads Share Process Memory And Are Often Suitable For I/O-Bound Tasks Such As Network Requests. Processes Have Separate Memory Spaces And Can Provide Better Parallelism For CPU-Bound Workloads In Standard CPython. Threads Generally Have Lower Creation And Communication Overhead Than Processes. Multiprocessing Can Require More Resources Because Each Process Maintains Its Own Runtime And Memory. The Choice Depends On Workload Type, Performance Requirements, Shared-State Needs, And Application Architecture.
74. What Is Asyncio In Python?
Ans:
Asyncio Is A Python Library Used To Write Concurrent Code Using The Async And Await Syntax. It Uses An Event Loop To Manage Multiple Awaitable Tasks, Particularly For I/O-Bound Operations. Async Programming Can Handle Many Network Operations Without Creating A Separate Thread For Every Task. It Is Commonly Used For Network Clients, Web Servers, API Calls, And Other High-Concurrency I/O Workloads. Asyncio Does Not Automatically Make CPU-Bound Tasks Faster. Blocking Operations Should Be Avoided Or Properly Offloaded So That The Event Loop Remains Responsive.
75. What Is A Coroutine In Python?
Ans:
A Coroutine Is A Special Function That Can Pause Its Execution And Resume Later, Typically Using async And await. Coroutines Are Commonly Used With Python’s Asyncio Framework For Concurrent I/O Operations. An async def Function Returns A Coroutine Object When Called. The await Keyword Allows The Event Loop To Suspend One Coroutine While Waiting For Another Awaitable Operation. This Enables Multiple I/O Tasks To Progress Efficiently Within A Single Thread. Coroutines Are Useful For Applications That Need To Handle Many Concurrent Network Or I/O Operations.
76. What Is Caching?
Ans:
- Caching Is The Practice Of Storing Frequently Used Data Or Computation Results So They Can Be Retrieved Faster Later. Python Provides Tools Such As functools.lru_cache For Caching Function Results.
- External Systems Such As Redis Can Also Be Used For Distributed Application Caching. Caching Can Reduce Database Load, Network Requests, And Expensive Computations.
- Cache Design Requires Decisions About Expiration, Invalidation, Size, Consistency, And Memory Usage. Effective Caching Can Significantly Improve Application Performance When Frequently Requested Data Changes Infrequently.
77. What Is Unit Testing Vs Integration Testing?
Ans:
Unit Testing Focuses On Testing Individual Functions, Methods, Or Components In Isolation. Integration Testing Checks Whether Multiple Components Work Correctly Together. Unit Tests Are Usually Faster And Can Use Mocks To Isolate External Dependencies. Integration Tests May Interact With Databases, APIs, Files, Or Other Services. Both Types Are Important For Building Reliable Python Applications. A Good Testing Strategy Combines Unit, Integration, And Higher-Level Tests According To The Application’s Requirements.
78. What Is Mocking In Python?
Ans:
Mocking Is A Testing Technique Used To Replace Real Dependencies With Controlled Objects During Tests. Python’s unittest.mock Module Provides Tools Such As Mock, MagicMock, And patch. Mocks Can Simulate Database Calls, API Responses, File Operations, And Other External Dependencies. This Helps Tests Focus On The Behavior Of The Component Being Tested. Mocking Can Also Make Tests Faster And More Predictable. However, Excessive Mocking May Hide Integration Problems, So It Should Be Used Carefully.
79. What Is Clean Code In Python?
Ans:
Clean Code Is Code That Is Readable, Understandable, Maintainable, And Organized Around Clear Responsibilities. Python Code Should Prefer Simple Solutions, Meaningful Names, Consistent Formatting, And Appropriate Function Sizes. Following PEP 8 And Using Useful Documentation Can Improve Code Quality. Avoiding Unnecessary Complexity And Repeated Logic Makes Applications Easier To Maintain. Automated Testing And Static Analysis Can Further Improve Reliability. Clean Code Helps Teams Collaborate More Effectively And Reduces The Cost Of Future Changes.
80. How Can Python Code Performance Be Improved?
Ans:
Python Performance Can Be Improved By Choosing Appropriate Data Structures And Avoiding Unnecessary Computation. Built-In Functions, List Comprehensions, Vectorized Libraries Such As NumPy, And Efficient Algorithms Can Reduce Execution Time. Profiling Tools Should Be Used To Identify Actual Bottlenecks Before Optimizing Code. Database Queries Should Be Efficient, And Unnecessary Network Or File Operations Should Be Minimized. Caching Can Help When The Same Expensive Computations Are Repeated Frequently. For CPU-Intensive Workloads, Multiprocessing, Native Extensions, Or Specialized Libraries May Provide Additional Performance Improvements.
81. How Does Handle Large Files In Python?
Ans:
Large Files Should Usually Be Processed Incrementally Rather Than Loaded Entirely Into Memory. Python File Objects Can Be Iterated Line By Line To Reduce Memory Consumption. Generators Can Also Produce Processed Records Lazily. For Structured Data, Chunk-Based Processing Can Be Used With Libraries Such As Pandas. Compression, Efficient File Formats, And Streaming Approaches Can Further Improve Storage And Processing Efficiency. The Appropriate Strategy Depends On File Size, Data Format, Processing Requirements, And Available Memory.
82. How Does Debug A Python Program?
Ans:
- Debugging Starts By Reproducing The Problem And Identifying The Exact Input And Conditions That Cause The Error. Error Messages And Tracebacks Should Be Examined Carefully To Locate The Failing Code.
- Python Provides Debugging Tools Such As pdb, IDE Debuggers, Logging, Assertions, And Interactive Inspection.
- Unit Tests Can Help Isolate The Problem To A Specific Function Or Component. Fixes Should Be Validated Against Both The Original Failure And Related Edge Cases.
83. How Does Manage Dependencies In A Python Project?
Ans:
Dependencies Can Be Managed Using A Virtual Environment And A Dependency Management Tool Such As PIP. A Requirements File Can Record Exact Or Compatible Package Versions Needed By The Project. Modern Projects May Also Use Tools Such As Poetry Or Pipenv To Manage Dependencies And Lock Versions. Dependency Updates Should Be Tested Before Being Introduced Into Production Applications. Automated Builds And Continuous Integration Can Verify That Dependencies Install Correctly. Proper Dependency Management Helps Ensure Reproducible Development, Testing, And Deployment Environments.
84. How Does Prepare For A Python Developer Role At TCS?
Ans:
Preparation For A Python Developer Role Should Cover Python Fundamentals, Data Structures, Functions, OOP, Exception Handling, File Handling, Modules, And Advanced Python Concepts. Strong Knowledge Of SQL, APIs, Databases, Git, Testing, And Basic Web Development Can Also Be Valuable For Developer Roles. Coding Practice Should Include Strings, Lists, Dictionaries, Searching, Sorting, Recursion, And Problem-Solving Questions. Practical Knowledge Of Frameworks Such As Django Or Flask Can Help With Backend-Oriented Positions.
85. Write A Python Program To Find The Factorial Of A Number.
Ans:
: The Program Calculates The Factorial Of A Given Number Using A for Loop. The Factorial Is Obtained By Multiplying All Positive Integers From 1 Up To The Given Number
- num = 5
- factorial = 1
- for i in range(1, num + 1):
- factorial *= i
- print(“Factorial:”, factorial)
86. Write A Python Program To Check Whether A Number Is Prime.
Ans:
The Program Checks Whether A Given Number Is Divisible By Any Number Other Than 1 And Itself. Numbers Less Than Or Equal To 1 Are Not Considered Prime Numbers
- num = 17
- is_prime = True
- if num <= 1:
- is_prime = False
- else:
- for i in range(2, int(num ** 0.5) + 1):
- if num % i == 0:
- is_prime = False
- break
- if is_prime:
- print(“Prime Number”)
- else:
- print(“Not A Prime Number”)
87. Write A Python Program To Reverse A Number.
Ans:
The Program Reverses A Number By Extracting Its Last Digit Repeatedly. The Modulus Operator Obtains The Last Digit Of The Number.
- num = 12345
- reverse = 0
- while num > 0:
- digit = num % 10
- reverse = reverse * 10 + digit
- num //= 10
- print(“Reversed Number:”, reverse)
88. Write A Python Program To Find Duplicate Elements In A List.
Ans:
The Program Identifies Elements That Occur More Than Once In A List. The count() Method Determines How Many Times Each Element Appears
- numbers = [10, 20, 30, 20, 40, 10, 50, 30]
- duplicates = []
- for number in numbers:
- if numbers.count(number) > 1 and number not in duplicates:
- duplicates.append(number)
- print(“Duplicate Elements:”, duplicates)
89. Write A Python Program To Generate The Fibonacci Series.
Ans:
The Program Generates The Fibonacci Series Using Two Variables To Store Consecutive Values. The Series Starts With 0 And 1, And Each Following Number Is The Sum Of The Previous Two Numbers.
- n = 10
- a = 0
- b = 1
- for i in range(n):
- print(a, end=” “)
- a, b = b, a + b
90. Write A Python Program To Check Whether Two Strings Are Anagrams.
Ans:
A The Program Checks Whether Two Strings Contain The Same Characters With The Same Frequencies In A Different Or Similar Order
- str1 = “listen”
- str2 = “silent”
- if sorted(str1) == sorted(str2):
- print(“Anagrams”)
- else:
- print(“Not Anagrams”)
LMS

