Introduction Q&A
- What is Python?
- Python is a high-level, interpreted, general-purpose programming language that emphasizes code readability and simplicity. It supports multiple programming paradigms and has extensive libraries.
- Who created Python and when?
- Python was created by Guido van Rossum, a Dutch programmer. He started in December 1989, and the first public release (Python 0.9.0) was in February 1991.
- Why is Python called "Python"?
- The name comes from the British comedy series "Monty Python's Flying Circus," which Guido van Rossum enjoyed watching.
- What are the main features of Python?
- High-level syntax, interpreted execution, dynamic typing, automatic memory management, multi-paradigm support, extensive standard library, cross-platform compatibility, and indentation-based syntax.
- Is Python a compiled or interpreted language?
- Python is interpreted - code is executed line by line. However, it compiles to bytecode (.pyc files) for performance optimization.
- What is the "Zen of Python"?
- A collection of 19 guiding principles for Python programming. Access with
import this. Key principles include "Beautiful is better than ugly" and "Readability counts." - Why should I learn Python?
- Beginner-friendly, versatile for many applications, high job demand, large community, rapid development, and extensive ecosystem of libraries.
- What can I build with Python?
- Web applications, desktop apps, games, data analysis tools, machine learning models, automation scripts, APIs, chatbots, scientific simulations, and more.
- How does Python compare to other languages?
- Easier to learn than C++ or Java, slower execution but faster development. Excellent for productivity and prototyping.
- What is the Python Software Foundation?
- A non-profit organization that holds Python's intellectual property rights, promotes the language, and supports the community.
- How is Python licensed?
- Open-source under the Python Software Foundation License, similar to BSD license. Free to use, modify, and distribute.
- What is PyPI?
- Python Package Index - the official repository for third-party packages. Hosts over 400,000 packages installable with pip.
- What is pip?
- Python's package installer. Allows installation and management of packages from PyPI. Included with Python 3.4+.
- How do I install Python?
- Download from python.org, run the installer, check "Add Python to PATH" on Windows, verify with
python --version. - What is the difference between Python 2 and 3?
- Python 3 has better Unicode support, improved integer division (5/2 = 2.5), print function instead of statement, and removed deprecated features. Python 2 reached end-of-life in January 2020.
- What IDEs are recommended for Python?
- VS Code, PyCharm (Community edition free), IDLE (comes with Python), Sublime Text, Atom, Jupyter Notebook for interactive development.
- How do I run a Python program?
- Save code in .py file, run with
python filename.pyfrom command line. Interactive mode withpythonwithout filename. - What is the Python interpreter?
- A program that reads and executes Python code. Translates code to bytecode and executes it, also provides interactive mode.
- What are Python's strengths and weaknesses?
- Strengths: Easy to learn, readable code, large ecosystem, cross-platform. Weaknesses: Slower than compiled languages, higher memory usage.
Basics Q&A
- How to declare a variable in Python?
- Simply assign a value: x = 5. No type declaration needed - Python determines type automatically.
- What is the difference between / and //?
- / is float division (5/2 = 2.5), // is floor division (5//2 = 2).
- How to define a function?
- def function_name(parameters): followed by indented code block.
- What are the main data types in Python?
- int (integers), float (decimals), str (strings), bool (True/False).
- How do you check a variable's type?
- Use the type() function: type(variable_name).
- What is the difference between = and ==?
- = is assignment operator (x = 5), == is equality comparison (x == 5).
- How does Python handle indentation?
- Indentation defines code blocks. Use 4 spaces or 1 tab consistently.
- What is the purpose of the else clause in loops?
- Else executes when loop completes normally (not via break).
- How do you convert between data types?
- Use int(), float(), str(), bool() functions for type conversion.
- What is the difference between parameters and arguments?
- Parameters are in function definition, arguments are values passed when calling.
- How do you return multiple values from a function?
- Return as tuple: return value1, value2
- What happens if a function has no return statement?
- It returns None implicitly.
- How do you use the range() function?
- range(stop), range(start, stop), or range(start, stop, step).
- What is variable scope?
- Scope determines where a variable can be accessed. Local inside functions, global outside.
- How do logical operators work?
- and: both true, or: at least one true, not: reverses boolean value.
- What are assignment operators?
- Operators like +=, -= that combine assignment with operation (x += 3 means x = x + 3).
- How do you write a multi-line string?
- Use triple quotes: """multi-line string""" or '''multi-line string'''.
- What is the difference between break and continue?
- break exits the loop entirely, continue skips current iteration and continues.
- How do you check if a number is even or odd?
- Use modulo operator: if num % 2 == 0 (even) else (odd).
- What are the rules for variable naming?
- Start with letter/underscore, contain letters/digits/underscores, case-sensitive, no reserved words.
Intermediate Q&A
- What is the difference between list and tuple?
- Lists are mutable (can be changed), tuples are immutable (cannot be changed after creation). Lists use [], tuples use ().
- How to add an item to a list?
- Use append() to add to end, or insert(index, item) to add at specific position.
- How to read a file in Python?
- Use with open('filename', 'r') as f: content = f.read() - the 'with' statement automatically closes the file.
- What is a module?
- A file containing Python code that can be imported and reused in other programs.
- How do you access dictionary values?
- Use square brackets: dict['key'] or the get() method: dict.get('key', default).
- What is the difference between 'w' and 'a' file modes?
- 'w' overwrites the file, 'a' appends to existing content.
- Can tuples be modified?
- No, tuples are immutable. You cannot add, remove, or change elements after creation.
- What are dictionary comprehensions?
- Concise way to create dictionaries: {key_expr: value_expr for item in iterable if condition}.
- How do you handle file errors?
- Use try-except blocks: try: open file except FileNotFoundError: handle error.
- What is the __name__ variable in modules?
- It contains the module's name. When run directly, it's "__main__", when imported, it's the module name.
- How to sort a list in descending order?
- Use list.sort(reverse=True) or sorted(list, reverse=True).
- What is the difference between pop() and remove() for lists?
- pop(index) removes by index and returns the value, remove(value) removes by value.
- How do you check if a key exists in a dictionary?
- Use 'key' in dict or dict.get('key') is not None.
- What are the benefits of using tuples over lists?
- Tuples are immutable (safer), faster for iteration, can be used as dictionary keys, and use less memory.
- How to read a file line by line?
- Use for line in file: or file.readlines() to get all lines as list.
- What is a package in Python?
- A directory containing multiple modules and an __init__.py file.
- How to merge two dictionaries?
- Use dict1.update(dict2) or {**dict1, **dict2} (Python 3.5+).
- What is the purpose of the 'with' statement for files?
- It ensures files are properly closed even if an exception occurs.
- How to get all keys from a dictionary?
- Use dict.keys() which returns a dict_keys view object.
- Can lists contain different data types?
- Yes, lists can contain elements of different types: [1, "hello", True, 3.14].
Advanced Q&A
- What is a class in Python?
- A class is a blueprint for creating objects. It defines attributes and methods that objects of that class will have.
- How to handle exceptions?
- Use try-except blocks. Put potentially error-causing code in try block, and error handling in except block.
- What is NumPy used for?
- NumPy is used for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on them.
- How to create a Pandas DataFrame?
- Use pd.DataFrame(data) where data can be a dictionary, list, or other data structure.
- What is inheritance in OOP?
- Inheritance allows a class (child) to inherit attributes and methods from another class (parent), promoting code reuse.
- What is polymorphism?
- Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling method overriding.
- How do you raise an exception?
- Use the raise keyword: raise ExceptionType("error message").
- What is the difference between __str__ and __repr__?
- __str__ is for user-friendly string representation, __repr__ is for unambiguous representation used by developers.
- What is Big O notation?
- Big O notation describes the upper bound of an algorithm's time or space complexity as input size grows.
- How does NumPy broadcasting work?
- Broadcasting allows operations on arrays of different shapes by automatically expanding smaller arrays to match larger ones.
- What is a Pandas Series?
- A Series is a one-dimensional labeled array in Pandas, similar to a column in a spreadsheet.
- How to handle missing data in Pandas?
- Use methods like dropna() to remove missing values, fillna() to fill them, or isnull() to detect them.
- What is method overriding?
- Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.
- How do you create a custom exception?
- Create a class that inherits from Exception: class MyError(Exception): pass
- What is the time complexity of binary search?
- O(log n) where n is the number of elements in the search space.
- How to merge DataFrames in Pandas?
- Use pd.merge() or DataFrame.merge() with parameters for join type (inner, outer, left, right).
- What is encapsulation in OOP?
- Encapsulation is the bundling of data and methods that operate on that data within a single unit (class), hiding internal details.
- How does garbage collection work in Python?
- Python uses reference counting and cyclic garbage collection to automatically manage memory and clean up unused objects.
- What is a lambda function?
- A lambda function is an anonymous function defined with the lambda keyword: lambda x: x**2
- How to create a NumPy array from a list?
- Use np.array(list_name) to convert a Python list to a NumPy array.
- What is the difference between loc and iloc in Pandas?
- loc uses label-based indexing, iloc uses integer-based (positional) indexing.