Thursday, October 15, 2026

Python Quiz: `and` vs `or` — Operand Return Behavior

 ### Python Quiz: `and` vs `or` — Operand Return Behavior

Test your Python knowledge with these 10 quiz questions, covering truthy/falsy values, short-circuit evaluation, and code output.

Key rule to remember:

* `x and y` → returns `x` if `x` is falsy; otherwise returns `y`.

* `x or y` → returns `x` if `x` is truthy; otherwise returns `y`.

Python and/or Operator Quiz


1. What is the output? print(0 or 15)

   A. 0

   B. False

   C. True

   D. 15


2. What is the output? print("Python" and "Quiz")

   A. Python

   B. False

   C. Quiz

   D. True


3. What is the output? print([] or "Empty")

   A. Empty

   B. True

   C. []

   D. False


4. What is the output? print(5 and 0 and 8)

   A. True

   B. 0

   C. 5

   D. 8


5. What is the output? print(None or False or "Done")

   A. True

   B. None

   C. False

   D. Done


6. Select every expression that evaluates to the integer 0. # Evaluate each expression independently

   A. 9 or 0

   B. 9 and 0

   C. 0 and 7

   D. 0 or 7


7. In Python, the expression "Hi" or "Bye" evaluates to the string "Hi".

   True

   False


8. In Python, [] and 10 evaluates to the integer 10 because and always returns its last operand.

   True

   False


9. What is printed? def check(): print("called") return 99 print(1 or check())

   A. called, then 1

   B. called, then 99

   C. 99 only

   D. 1 only


10. What is the output? value = "" result = value and 100 print(repr(result))

   A. None

   B. ''

   C. 100

   D. False

Quick revision tip: `and` stops at the first falsy operand; `or` stops at the first truthy operand. Both return the actual operand, 

not necessarily `True` or `False`.

Thursday, October 8, 2026

Python Requests Package quiz


Python Requests Package — Complete Quiz with Answers


Basic + Intermediate


Q1. Which Python package is commonly used to send HTTP requests easily?

A) urllib

B) requests

C) httpclient

D) httplib

Answer: B) requests


Q2. Which attribute returns the HTTP status code of a response object r?

A) r.status

B) r.code

C) r.status_code

D) r.http_code

Answer: C) r.status_code


Q3. response.json() converts a JSON response into a Python dictionary or list.

A) True

B) False

Answer: A) True


Q4. The requests package is included in Python's standard library and does not require installation.

A) True

B) False

Answer: B) False


Q5. Which methods are valid HTTP methods supported directly by Requests?

A) delete()

B) get()

C) post()

D) put()

Answer: B, C, D

Note: delete() is also supported by Requests; this question's original answer set was incomplete.


Q6. Which parameter is used to send query-string values in requests.get()?

A) data

B) params

C) query

D) args

Answer: B) params



---


Intermediate Code Quiz


Q7. What is printed?


import requests

r = requests.get('https://example.com')

print(r.status_code)


A) 404

B) 200

C) 500

D) 301

Answer: B) 200


Q8. What does this send to the server?


requests.get(

    'https://api.example.com/users',

    params={'page': 2, 'limit': 10}

)


A) JSON body

B) Form data

C) URL query parameters

D) HTTP headers

Answer: C) URL query parameters


Q9. What Python object is most likely returned?


response = requests.get(url)

data = response.json()


If the API returns a JSON object: A) tuple

B) list

C) dict

D) bytes

Answer: C) dict


Q10. response.text returns the response body decoded as text.

A) True

B) False

Answer: A) True


Q11. What is the purpose of response.raise_for_status()?

A) Converts response to JSON

B) Raises an exception for unsuccessful HTTP status codes

C) Retries the request

D) Closes the connection

Answer: B


Q12. What does this request do?


requests.post(

    url,

    json={'name': 'John'},

    headers={'Authorization': 'Bearer TOKEN'}

)


A) Sends data as URL parameters

B) Sends JSON data in the request body

C) Sends a POST request

D) Sends an Authorization header

Answer: B, C, D


Q13. What does timeout=5 do?


requests.get(url, timeout=5)


A) Retries 5 times

B) Sets a 5-second timeout

C) Sends 5 requests

D) Waits 5 minutes

Answer: B) Sets a 5-second timeout


Q14. Which exception can be caught for timeout or other Requests-related network errors?


try:

    requests.get(url, timeout=3)

except ______ as e:

    print(e)


A) ValueError

B) KeyError

C) requests.exceptions.RequestException

D) IndexError

Answer: C


Q15. What does this return?


r.headers.get('Content-Type')


A) HTTP status code

B) Content-Type header value

C) Request body

D) URL

Answer: B) Content-Type header value


Q16. What does this send?


requests.post(url, data={'name': 'John'})


A) JSON data

B) Form data

C) Query parameters

D) Cookies

Answer: B) Form data


Fresh Intermediate Code Quiz


Q17. What does r.ok indicate?


r = requests.get(url)

print(r.ok)


A) True only for status 200

B) True only for status 201

C) True only for status 300

D) True when status is below 400

Answer: D


Q18. What does r.content provide?


r = requests.get(url)

content = r.content


A) JSON dictionary

B) Raw response bytes

C) HTTP status

D) Headers

Answer: B) Raw response bytes


Q19. What happens for HTTP 404?

r = requests.get(url)

r.raise_for_status()

print("Done")

A) Prints Done

B) Returns 200

C) Retries automatically

D) Raises HTTPError

Answer: D


Q20. Which arguments can be supplied to requests.get()?

A) cookies

B) headers

C) verify

D) All of the above

Answer: D


Q21. A requests.Session can persist settings such as cookies across multiple requests.

A) True

B) False

Answer: A) True


Q22. What is the purpose of this code?

session = requests.Session()

session.headers.update({'User-Agent': 'MyApp'})

A) Sends one request

B) Sets a default header for session requests

C) Deletes headers

D) Disables cookies

Answer: B


Q23. What does this do?

requests.get(url, allow_redirects=False)

A) Prevents automatic redirects

B) Forces a redirect

C) Disables HTTPS

D) Retries redirects

Answer: A


Q24. What does this do?


requests.get(

    url,

    cookies={'session_id': 'abc123'}

)


A) Sends cookies with the request

B) Creates a new session

C) Deletes cookies

D) Reads response headers

Answer: A


Q25. Which code correctly saves an image response?

r = requests.get(url)

A)open('image.jpg', 'w').write(r.text)

B)open('image.jpg', 'r').write(r.content)

C) open('image.jpg', 'wb').write(r.content)

D) open('image.jpg', 'a').write(r.json())

Answer: C


Q26. What is the purpose of requests.head(url)?

A) Downloads the complete response body

B) Sends a POST request

C) Deletes a resource

D) Fetches headers without normally downloading the response body

Answer: D


Quick Revision


requests.get() → GET request

requests.post() → POST request

requests.put() → PUT request

requests.delete() → DELETE request


params={} → URL query parameters

data={} → Form/request data

json={} → JSON request body

headers={} → HTTP headers

cookies={} → Cookies


r.status_code → HTTP status code

r.ok → True for status < 400

r.text → Response as text

r.content → Response as bytes

r.json() → Parse JSON response

r.headers → Response headers


raise_for_status() → Raise HTTP error

timeout=5 → Request timeout

Session() → Persist settings/cookies

allow_redirects=False→ Don't follow redirects

head() → Fetch headers

Tuesday, October 6, 2026

Python try-except Quiz

 Python try-except Quiz


1. What is the output? try: print(10 / 0) except ZeroDivisionError: print("Error")

   A. Error

   B. 10

   C. No output

   D. 0


2. What happens if an exception occurs inside try and there is no matching except block?

   A. The finally block is skipped automatically

   B. The exception becomes None

   C. The program raises the exception

   D. Python ignores the exception


3. A finally block normally executes whether or not an exception occurs in the associated try block.

   True

   False


4. What is the output? try: x = int("abc") except ValueError: print("Invalid") else: print("Valid")

   A. No output

   B. Valid

   C. Invalid

   D. abc


5. Which of the following can be used to explicitly raise an exception in Python? Select all that apply.

   A. throw ValueError("Invalid")

   B. raise RuntimeError("Failed")

   C. raise ValueError("Invalid")

   D. raise Exception("Problem")


6. The except block must always specify an exception type.

   True

   False


7. What is the output? try: print(5 / 1) except ZeroDivisionError: print("Error") else: print("Success")

   A. Success only

   B. 5 then Error

   C. 5.0 then Success

   D. Error


8. Which exception is most appropriate when accessing a dictionary key that does not exist?

   A. TypeError

   B. NameError

   C. IndexError

   D. KeyError


9. What does the else block in try-except-else execute when the try block completes successfully?

   A. It executes only when an exception occurs

   B. It executes after the try block

   C. It always executes before try

   D. It replaces finally


10. What is the output? try: numbers = [1, 2, 3] print(numbers[5]) except IndexError: print("Index problem") finally: print("Done")

   A. Index problem then Done

   B. 5 then Done

   C. Index problem only

   D. Done only

Tuesday, September 29, 2026

Python file-handling

 ### Top 20 Python `open()` Function Quiz 🐍


Test your Python file-handling knowledge with 20 multiple-choice questions covering file modes, reading, writing, appending, `with` statements, and file pointers.


### Part 1: Basic `open()` Quiz

Q1. What is the default mode of open()?

A. 'w'

B. 'r'

C. 'a'

D. 'x'

Correct answer: B

The default mode is 'r', which opens a file for reading.


Q2. What happens if you open a non-existing file using open('test.txt', 'r')?

A. Creates the file

B. Returns None

C. Raises FileNotFoundError

D. Creates an empty file

Correct answer: C

Read mode requires the file to exist.


Q3. Which mode opens a file for writing and truncates existing content?

A. 'a'

B. 'r'

C. 'w'

D. 'x'

Correct answer: C

'w' creates a file if needed and clears existing content.


Q4. Which mode adds content to the end of a file?

A. 'r'

B. 'a'

C. 'w'

D. 'x'

Correct answer: B

Append mode writes at the end without removing existing content.


Q5. What does mode 'x' do?

A. Reads a file

B. Appends content

C. Creates a new file exclusively

D. Deletes a file

Correct answer: C

'x' raises FileExistsError if the file already exists.


Q6. What does file.read() return?

A. A list of lines

B. A string containing file content

C. A file object

D. An integer

Correct answer: B

read() returns the file contents as a string in text mode.


Q7. What does readline() return?

A. All lines

B. One line, including newline if present

C. A list

D. The last line only

Correct answer: B

readline() reads one line at a time.


Q8. What does readlines() return?

A. A string

B. A tuple

C. A list of lines

D. A dictionary

Correct answer: C

readlines() returns a list where each element is a line.


Q9. Which method writes a string to a file?

A. read()

B. write()

C. readline()

D. append()

Correct answer: B

write() writes a string and does not automatically add a newline.


Q10. What is the purpose of the with statement when opening files?

A. Makes file read-only

B. Automatically closes the file

C. Deletes the file

D. Opens only binary files

Correct answer: B

The context manager closes the file automatically, even if an exception occurs.


### Part 2: Output-Based Quiz

Q11. What is printed if file.txt contains Hello World?

f = open('file.txt', 'r') print(f.read(5))

A. Hello

B. Hello World

C. World

D. Error

Correct answer: A

read(5) reads the first five characters.


Q12. What is printed if file.txt contains Python?

f = open('file.txt', 'r') print(f.read()) print(f.read())

A. Python twice

B. Python followed by a blank line

C. Error

D. None twice

Correct answer: B

The first read consumes the content. The second read returns an empty string.


Q13. What is the content after execution if file.txt initially contains ABC?

f = open('file.txt', 'w') f.write('XYZ') f.close()

A. ABCXYZ

B. ABC

C. XYZ

D. XYZABC

Correct answer: C

Write mode truncates the original file before writing XYZ.


Q14. If file.txt contains Hi, what is its content after this?

f = open('file.txt', 'a') f.write('!') f.close()

A. !

B. Hi!

C. Hi

D. !Hi

Correct answer: B

Append mode adds ! at the end.


Q15. What does this print?

with open('file.txt', 'w') as f: f.write('Python') print(f.closed)

A. False

B. True

C. Python

D. Error

Correct answer: B

The with block closes the file when execution exits the block.


Q16. What is printed?

f = open('file.txt', 'w') print(f.write('Hello')) f.close()

A. Hello

B. 5

C. None

D. True

Correct answer: B


write() returns the number of characters written. Hello has five characters.


Q17. What is printed?

f = open('file.txt', 'w') f.write('ABC\\nDEF') f.close() f = open('file.txt', 'r') print(f.readline().strip())

A. ABC

B. DEF

C. ABC DEF

D. ABC\\nDEF

Correct answer: A

readline() reads the first line; strip() removes the newline.


Q18. What does seek(0) do?

f.seek(0)

A. Closes the file

B. Moves the file pointer to the beginning

C. Deletes the first character

D. Moves to the end

Correct answer: B

seek(0) moves the file pointer to byte/character position zero in ordinary text-file usage.


Q19. What is printed?

f = open('file.txt', 'w+') f.write('ABC') f.seek(0) print(f.read()) f.close()

A. ABC

B. Empty string

C. 3

D. Error

Correct answer: A

w+ permits reading and writing. seek(0) moves the pointer back to the beginning.


Q20. What happens when opening an existing file with mode 'x'?

f = open('existing.txt', 'x')

A. File is overwritten

B. File is appended

C. FileExistsError is raised

D. File is read

Correct answer: C

Exclusive creation fails if the file already exists.


### Quick revision: Python file modes


| Mode | Purpose |

| ---- | ---------------------------------------- |

| r | Read; file must exist |

| w | Write; truncates existing content |

| a | Append; creates file if missing |

| x | Create exclusively; fails i

f file exists |

| r+ | Read and write; file must exist |

| w+ | Read and write; truncates existing file |

| a+ | Read and append; creates if missing |


Remember: Use `with open("file.txt", "r") as f:` for automatic file closing.

Classes, Objects, Inheritance, Method Overriding & More

 ### Top 20 Python OOP Quiz 🐍


### Classes, Objects, Inheritance, Method Overriding & More


Test your Python knowledge with these 20 output-based MCQs covering classes, constructors, inheritance, method overriding, `super()`, polymorphism, encapsulation, and abstraction.


### Section 1: Classes and Objects

Q1. What is the output?

```python

class Student:

    def __init__(self, name):

        self.name = name


s = Student("Ravi")

print(s.name)

```

A. Student

B. Ravi

C. name

D. Error

Answer: B — Ravi. `self.name` stores the instance attribute.


Q2. What is the output?

```python

class Demo:

    x = 10


a = Demo()

b = Demo()

a.x = 20


print(b.x)

```


A. 10

B. 20

C. None

D. Error

Answer: A — 10. Assigning `a.x` creates an instance attribute; `b.x` still resolves to the class attribute.


Q3. What does `__init__()` do?

A. Destroys an object

B. Initializes an instance after it is created

C. Inherits a class

D. Defines a static method

Answer: B — It initializes the newly created instance.


Q4. What is the output?

```python

class A:

    def show(self):

        print("A")


obj = A()

obj.show()

```

A. A

B. show

C. None

D. Error

Answer: A — A.


Q5. What is the output?

```python

class Counter:

    count = 0


    def __init__(self):

        Counter.count += 1


a = Counter()

b = Counter()

print(Counter.count)

```

A. 0

B. 1

C. 2

D. Error

Answer: C — 2. The class variable is incremented for each instance.


### Section 2: Inheritance and Method Overriding

Q6. What is the output?

```python

class Parent:

    def show(self):

        print("Parent")


class Child(Parent):

    pass


Child().show()

```

A. Child

B. Parent

C. None

D. Error

Answer: B — Parent. Child inherits the method.


Q7. What is the output?

```python

class Parent:

    def show(self):

        print("Parent")


class Child(Parent):

    def show(self):

        print("Child")


Child().show()

```

A. Parent

B. Child

C. Parent Child

D. Error

Answer: B — Child. The child overrides the parent method.


Q8. What is the output?

```python

class A:

    def show(self):

        print("A")


class B(A):

    def show(self):

        super().show()

        print("B")


B().show()

```

A. B then A

B. A then B

C. B only

D. Error

Answer: B — A, then B. `super()` calls the next implementation in the method resolution order.


Q9. What is the output?

```python

class A:

    def __init__(self):

        print("A")


class B(A):

    def __init__(self):

        print("B")


B()

```

A. A then B

B. B then A

C. B only

D. A only

Answer: C — B only. The child constructor does not call the parent constructor.


Q10. What is the output?

```python

class A:

    def __init__(self):

        self.x = 10


class B(A):

    def __init__(self):

        super().__init__()

        self.y = 20


obj = B()

print(obj.x + obj.y)

```

A. 10

B. 20

C. 30

D. Error

Answer: C — 30. `super().__init__()` initializes `x`; the child initializes `y`.


Q11. Which inheritance type allows a class to inherit from two parent classes?

A. Single inheritance

B. Multiple inheritance

C. Multilevel inheritance

D. Hierarchical inheritance

Answer: B — Multiple inheritance.


Q12. What is the output?

```python

class A:

    def show(self):

        print("A")


class B:

    def show(self):

        print("B")


class C(A, B):

    pass


C().show()

```

A. A

B. B

C. A B

D. Error

Answer: A — A. Python searches base classes according to the MRO; A comes first.


### Section 3: Polymorphism, Encapsulation & Abstraction

Q13. What is the output?

```python

class Animal:

    def sound(self):

        print("Animal")


class Dog(Animal):

    def sound(self):

        print("Bark")


def make_sound(obj):

    obj.sound()


make_sound(Dog())

```

A. Animal

B. Bark

C. Both

D. Error

Answer: B — Bark. This demonstrates runtime polymorphism.


Q14. What is the output?

```python

class A:

    def show(self):

        return "Hello"


obj = A()

print(obj.show())

```

A. None

B. Hello

C. show

D. Error

Answer: B — Hello. The method returns a string.


Q15. What is the output?

```python

class Employee:

    def __init__(self):

        self.__salary = 50000


e = Employee()

print(e.__salary)

```

A. 50000

B. None

C. AttributeError

D. SyntaxError

Answer: C — AttributeError. Double-underscore attributes undergo name mangling.


Q16. What is the output?

```python

class A:

    def __init__(self):

        self.__x = 10


obj = A()

print(obj._A__x)

```

A. 10

B. None

C. AttributeError

D. SyntaxError

Answer: A — 10. Name mangling changes `__x` to `_A__x`; it is not strict privacy.


Q17. Which module provides support for abstract base classes?

A. os

B. abc

C. sys

D. math

Answer: B — `abc` (Abstract Base Classes).


Q18. What happens when you run this code?

```python

from abc import ABC, abstractmethod


class Shape(ABC):

    @abstractmethod

    def area(self):

        pass


s = Shape()

```

A. Object created successfully

B. Returns None

C. TypeError

D. SyntaxError

Answer: C — TypeError. A class with unimplemented abstract methods cannot be instantiated.


Q19. What is the output?

```python

class A:

    def greet(self):

        print("Hello")


class B(A):

    pass


class C(B):

    pass


C().greet()

```

A. Hello

B. A

C. None

D. Error

Answer: A — Hello. This is multilevel inheritance: A → B → C.


Q20. What is the output?

```python

class A:

    def show(self):

        print("A")


class B(A):

    def show(self):

        print("B")

        super().show()


class C(B):

    def show(self):

        print("C")

        super().show()


C().show()

```

A. A B C

B. C B A

C. C A B

D. C only

Answer: B — C, B, A. Each `super()` call invokes the next method in the MRO.


### Quick Revision – Python OOP


| Concept | Key point |

| ------------- | ---------------------------------------------------------------------- |

| Class | Blueprint for creating objects |

| Object | Instance of a class |

| Inheritance | Reuse parent class functionality |

| Overriding | Child provides its own implementation of an inherited method |

| super() | Accesses the next implementation in the MRO |

| Polymorphism | Same interface, different behavior |

| Encapsulation | Bundling data and methods; name mangling helps avoid accidental access |

| Abstraction | Define required interfaces using abstract classes and methods |

Tuesday, September 22, 2026

Linux df and du commands to manage and check disk space


1. df (Disk Free) — Check Filesystem Space

The df command shows the amount of disk space available on the entire file system.

  • Basic usage (Human-readable format):

    Bash
    df -h
    
    (The -h flag converts bytes into KB, MB, or GB for readability).

  • Show filesystem types along with space:

    Bash
    df -Th
    
    (Displays formats like ext4, tmpfs, xfs, etc.)

  • Check Inode usage (file count limits):

    Bash
    df -i
    
    (Useful if your disk says it has space, but you get "No space left on device" errors due to running out of inodes).

2. du (Disk Usage) — Check File & Directory Sizes

The du command estimates file and directory space usage, helping you find which specific folders are consuming your storage.

  • Check the size of a specific directory (human-readable):

    Bash
    du -sh /path/to/directory
    
    (The -s flag gives a summary total instead of listing every individual sub-file).

  • List sizes of all files and subfolders in the current directory:

    Bash
    du -h --max-depth=1
    
    (Helps you quickly see which sub-folder is taking up the most space).

  • Sort directories by size (largest first):

    Bash
    du -h --max-depth=1 | sort -hr
    
  • Show total size of everything in the current directory including a grand total:
    Bash
    du -ch
    


💡 Quick Summary Comparison

CommandFocusBest Used ForCommon Flag
dfFilesystem levelChecking overall hard drive / partition capacitydf -h
duDirectory levelFinding which specific folders or files are hogging spacedu -sh *