DEV Community

Guru prasanna
Guru prasanna

Posted on

Python - Theory Questions and Answers

1. Introduction to Python

  • Python is a high-level, interpreted, dynamically typed, and object-oriented programming language.
  • It is widely used for web development, data science, automation, AI, and more.

Key Features:

  • Simple and easy-to-learn syntax.
  • Interpreted language (no need for compilation).
  • Dynamically typed (no need to declare variable types).
  • Extensive standard library support.
  • Supports multiple programming paradigms (Object-Oriented, Functional, and Procedural).

2. Python Data Types

Basic Data Types:

  • int → Integer values, e.g., x = 10
  • float → Decimal numbers, e.g., y = 3.14
  • str → Sequence of characters, e.g., name = "Python"
  • bool → Boolean values, True or False

Collection Data Types:

  • List → Ordered, mutable collection, e.g., fruits = ["apple", "banana"]
  • Tuple → Ordered, immutable collection, e.g., numbers = (1, 2, 3)
  • Set → Unordered, unique elements, e.g., s = {1, 2, 3}
  • Dictionary → Key-value pairs, e.g., student = {"name": "John", "age": 25}

3. Variables and Operators

Variables:

  • Variables store data and do not require explicit type declaration.
  • Example:
  x = 10  # Integer
  y = "Python"  # String
Enter fullscreen mode Exit fullscreen mode

Operators:

  • Arithmetic: +, -, *, /, %, **, //
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: and, or, not
  • Assignment: =, +=, -=, *=, /=
  • Membership: in, not in
  • Identity: is, is not

4. Control Flow Statements

Conditional Statements:

  • Used for decision-making.
  • Example:
  x = 10
  if x > 0:
      print("Positive")
  elif x == 0:
      print("Zero")
  else:
      print("Negative")
Enter fullscreen mode Exit fullscreen mode

Loops:

  • For Loop: Iterates over a sequence.
  for i in range(5):
      print(i)  # Output: 0 1 2 3 4
Enter fullscreen mode Exit fullscreen mode
  • While Loop: Repeats a block of code while a condition is true.
  x = 0
  while x < 5:
      print(x)
      x += 1
Enter fullscreen mode Exit fullscreen mode

Loop Control Statements:

  • break → Exits the loop early.
  • continue → Skips the current iteration.
  • pass → Placeholder for future code.

5. Functions in Python

  • Functions help reuse code and improve modularity.
  • Example:
  def greet(name):
      return "Hello, " + name

  print(greet("John"))  # Output: Hello, John
Enter fullscreen mode Exit fullscreen mode
  • Lambda (Anonymous) Functions:
  square = lambda x: x * x
  print(square(4))  # Output: 16
Enter fullscreen mode Exit fullscreen mode

6. Object-Oriented Programming (OOP) in Python

Key OOP Concepts:

  • Class & Object:
  class Person:
      def __init__(self, name, age):
          self.name = name
          self.age = age

      def greet(self):
          return f"Hello, my name is {self.name}"

  p1 = Person("Alice", 25)
  print(p1.greet())  # Output: Hello, my name is Alice
Enter fullscreen mode Exit fullscreen mode
  • Encapsulation: Hiding data inside classes.
  • Inheritance: Reusing features of a parent class.
  • Polymorphism: Using a single method name for different types.

7. Exception Handling

  • Used to handle runtime errors.
  • Example:
  try:
      x = 10 / 0
  except ZeroDivisionError:
      print("Cannot divide by zero")
  finally:
      print("Execution complete")
Enter fullscreen mode Exit fullscreen mode

8. File Handling

Opening and Reading a File:

with open("file.txt", "r") as file:
    content = file.read()
    print(content)
Enter fullscreen mode Exit fullscreen mode

Writing to a File:

with open("file.txt", "w") as file:
    file.write("Hello, Python!")
Enter fullscreen mode Exit fullscreen mode

9. Python Modules and Packages

  • Modules are files with Python code (.py).
  import math
  print(math.sqrt(16))  # Output: 4.0
Enter fullscreen mode Exit fullscreen mode
  • Creating a Custom Module:
  # mymodule.py
  def greet(name):
      return f"Hello, {name}"

  # main.py
  import mymodule
  print(mymodule.greet("Alice"))
Enter fullscreen mode Exit fullscreen mode

10. Decorators in Python

  • Used to modify functions without changing their code.
  • Example:
  def decorator_function(original_function):
      def wrapper_function():
          print("Wrapper executed before", original_function.__name__)
          return original_function()
      return wrapper_function

  @decorator_function
  def display():
      print("Display function executed")

  display()
Enter fullscreen mode Exit fullscreen mode

11. Python’s map(), filter(), and reduce() Functions

Using map():

  • Applies a function to all elements of an iterable.
  nums = [1, 2, 3, 4]
  squared = list(map(lambda x: x**2, nums))
  print(squared)  # Output: [1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode

Using filter():

  • Filters elements based on a condition.
  nums = [1, 2, 3, 4, 5]
  even = list(filter(lambda x: x % 2 == 0, nums))
  print(even)  # Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Using reduce():

  • Performs a cumulative operation on elements.
  from functools import reduce
  nums = [1, 2, 3, 4]
  result = reduce(lambda x, y: x + y, nums)
  print(result)  # Output: 10
Enter fullscreen mode Exit fullscreen mode

12. Python Memory Management

  • Python uses automatic garbage collection to manage memory.
  • Objects are deleted when their reference count becomes zero.
  • Example:
  import sys
  x = "Hello"
  print(sys.getrefcount(x))  # Output: Reference count of object
Enter fullscreen mode Exit fullscreen mode

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay