What is GIL in Python, why is it needed, and how can it be bypassed?
Answer:
However, due to the GIL, multithreading in Python does not provide true CPU-level parallelism: even if multiple threads are created, they will run sequentially rather than simultaneously, which limits performance in computationally intensive tasks.
This limitation can be bypassed by using modules like multiprocessing, which run separate processes with their own memory and their own GIL. Heavy logic can also be moved to native C extensions or interpreters without a GIL, such as Jython or experimental versions of PyPy.
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
Python Intermediate Level Certification Exam
Instructions:
This exam consists of 50 multiple-choice and code-output questions.
The suggested time for each question is indicated. Total Time: 60 Minutes.
• Choose the single best answer for each question.
---
Section 1: Core Concepts & Data Structures
• (Time: 60s) What will be the output of the following code?
a) 10
b) 20
c) Error
d) None
• (Time: 75s) What is the output of this code?
a)
b)
c)
d) A
• (Time: 45s) Which of the following is true about the
a)
b)
c) They are completely interchangeable.
d)
• (Time: 60s) What will be the output?
a)
b)
c)
d)
• (Time: 75s) What is the most likely output of this code in CPython?
a) True, True
b) False, False
c) True, False
d) False, True
• (Time: 75s) Which of the following is the primary advantage of a generator expression over a list comprehension?
a) It is always faster.
b) It uses less memory because it evaluates lazily.
c) It can be indexed.
d) It can be used for both reading and writing data.
• (Time: 60s) What is the result of the following set operation?
a)
b)
c)
d) An error occurs.
• (Time: 90s) What will be printed?
a)
b)
c)
d)
Section 2: Functions & Decorators
• (Time: 60s) What do
a) Required positional and keyword arguments.
b) Optional positional arguments and required keyword arguments.
c) Pointers to arguments.
d) A variable number of positional and keyword arguments.
• (Time: 75s) What is the output of this code?
a)
b)
c)
d) An error occurs.
• (Time: 60s) Which statement about lambda functions is true?
a) They can contain multiple expressions.
b) They cannot have default arguments.
c) They are anonymous functions restricted to a single expression.
d) They must be assigned to a variable.
• (Time: 75s) What will be the output?
a)
b)
c)
d) A
Instructions:
This exam consists of 50 multiple-choice and code-output questions.
The suggested time for each question is indicated. Total Time: 60 Minutes.
• Choose the single best answer for each question.
---
Section 1: Core Concepts & Data Structures
• (Time: 60s) What will be the output of the following code?
x = 10
def outer_func():
x = 20
def inner_func():
print(x)
inner_func()
outer_func()
a) 10
b) 20
c) Error
d) None
• (Time: 75s) What is the output of this code?
my_list = [1, 2, [3, 4]]
new_list = my_list.copy()
new_list[2][0] = 99
print(my_list)
a)
[1, 2, [3, 4]]b)
[1, 2, [99, 4]]c)
[99, 2, [3, 4]]d) A
TypeError occurs.• (Time: 45s) Which of the following is true about the
is and == operators?a)
is compares object identity, == compares value.b)
is compares value, == compares object identity.c) They are completely interchangeable.
d)
is is used for strings and == is for numbers.• (Time: 60s) What will be the output?
nums = [1, 2, 3, 4, 5, 6]
print(nums[::-2])
a)
[6, 4, 2]b)
[1, 3, 5]c)
[2, 4, 6]d)
[5, 3, 1]• (Time: 75s) What is the most likely output of this code in CPython?
a = 256
b = 256
print(a is b)
c = 257
d = 257
print(c is d)
a) True, True
b) False, False
c) True, False
d) False, True
• (Time: 75s) Which of the following is the primary advantage of a generator expression over a list comprehension?
a) It is always faster.
b) It uses less memory because it evaluates lazily.
c) It can be indexed.
d) It can be used for both reading and writing data.
• (Time: 60s) What is the result of the following set operation?
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1 ^ s2)a)
{3, 4}b)
{1, 2, 5, 6}c)
{1, 2, 3, 4, 5, 6}d) An error occurs.
• (Time: 90s) What will be printed?
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1))
print(add_item(2))
print(add_item(3, [10, 20]))
a)
[1], [2], [10, 20, 3]b)
[1], [1, 2], [10, 20, 3]c)
[1], [2], [3]d)
[1], [1, 2], [1, 2, 3]Section 2: Functions & Decorators
• (Time: 60s) What do
*args and **kwargs represent in a function definition?a) Required positional and keyword arguments.
b) Optional positional arguments and required keyword arguments.
c) Pointers to arguments.
d) A variable number of positional and keyword arguments.
• (Time: 75s) What is the output of this code?
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
a)
Hello!b)
Before, Hello!, After (each on a new line)c)
Before, After, Hello! (each on a new line)d) An error occurs.
• (Time: 60s) Which statement about lambda functions is true?
a) They can contain multiple expressions.
b) They cannot have default arguments.
c) They are anonymous functions restricted to a single expression.
d) They must be assigned to a variable.
• (Time: 75s) What will be the output?
data = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, data)))
print(result)
a)
[2, 4, 6, 8, 10]b)
[4, 8]c)
[2, 4]d) A
TypeError occurs.• (Time: 90s) What does the
a) It terminates the function immediately.
b) It returns a value and raises an exception.
c) It makes the function a generator, pausing its execution and returning a value.
d) It prints a value to the console without returning it.
• (Time: 60s) What will this code print?
a) 2
b) 5
c) 10
d) An error occurs.
• (Time: 45s) The concept demonstrated in the question above is called a:
a) Decorator
b) Generator
c) Lambda
d) Closure
Section 3: Object-Oriented Programming (OOP)
• (Time: 60s) What is the main purpose of the
a) To destroy an instance of a class.
b) To be the first method run when a script is executed.
c) To initialize the state of a new object when it is created.
d) To define a static method.
• (Time: 75s) What is the difference between a class variable and an instance variable?
a) They are the same.
b) Class variables are shared by all instances; instance variables are unique to each instance.
c) Instance variables are shared by all instances; class variables are unique to each instance.
d) Class variables cannot be modified.
• (Time: 90s) What will be the output of this code?
a)
b)
c)
d)
• (Time: 60s) What is the purpose of the
a) To call a method from a parent class.
b) To create a superclass.
c) To check if a class is a superclass of another.
d) To delete a parent class.
• (Time: 90s) What does the
a) It creates a method that automatically receives the class as the first argument.
b) It converts a method into a function that belongs to the class but doesn't receive any implicit first argument (
c) It makes a method private.
d) It allows a method to be called on an instance only.
• (Time: 75s) What is the correct way to define a property that makes an attribute read-only?
a)
b)
c)
d)
• (Time: 60s) The principle of a subclass providing a specific implementation of a method that is already provided by its parent class is called:
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Abstraction
• (Time: 90s) What will
a) An error,
b) 0
c) 3
d) The memory address of the object.
Section 4: Modules & Standard Library
• (Time: 60s) What is the primary use of the
a) To create a dictionary with a default sorting order.
b) To provide a default value for a key that does not exist, avoiding a
c) To create a thread-safe dictionary.
d) To create a dictionary that remembers insertion order (like a standard
yield keyword do in a function?a) It terminates the function immediately.
b) It returns a value and raises an exception.
c) It makes the function a generator, pausing its execution and returning a value.
d) It prints a value to the console without returning it.
• (Time: 60s) What will this code print?
def get_multiplier(n):
def multiplier(x):
return x * n
return multiplier
double = get_multiplier(2)
print(double(5))
a) 2
b) 5
c) 10
d) An error occurs.
• (Time: 45s) The concept demonstrated in the question above is called a:
a) Decorator
b) Generator
c) Lambda
d) Closure
Section 3: Object-Oriented Programming (OOP)
• (Time: 60s) What is the main purpose of the
__init__ method in a Python class?a) To destroy an instance of a class.
b) To be the first method run when a script is executed.
c) To initialize the state of a new object when it is created.
d) To define a static method.
• (Time: 75s) What is the difference between a class variable and an instance variable?
a) They are the same.
b) Class variables are shared by all instances; instance variables are unique to each instance.
c) Instance variables are shared by all instances; class variables are unique to each instance.
d) Class variables cannot be modified.
• (Time: 90s) What will be the output of this code?
class Parent:
def speak(self):
print("Parent speaking")
class Child(Parent):
def speak(self):
print("Child speaking")
super().speak()
c = Child()
c.speak()
a)
Parent speakingb)
Child speakingc)
Child speaking, Parent speaking (on new lines)d)
Parent speaking, Child speaking (on new lines)• (Time: 60s) What is the purpose of the
super() function in OOP?a) To call a method from a parent class.
b) To create a superclass.
c) To check if a class is a superclass of another.
d) To delete a parent class.
• (Time: 90s) What does the
@staticmethod decorator do?a) It creates a method that automatically receives the class as the first argument.
b) It converts a method into a function that belongs to the class but doesn't receive any implicit first argument (
self or cls).c) It makes a method private.
d) It allows a method to be called on an instance only.
• (Time: 75s) What is the correct way to define a property that makes an attribute read-only?
a)
def get_my_attr(self): ...b)
__my_attr = valuec)
@property def my_attr(self): ...d)
static my_attr = value• (Time: 60s) The principle of a subclass providing a specific implementation of a method that is already provided by its parent class is called:
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Abstraction
• (Time: 90s) What will
len(p) return after running this code?class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs)
p = Playlist(['Song A', 'Song B', 'Song C'])
a) An error,
len() is not supported.b) 0
c) 3
d) The memory address of the object.
Section 4: Modules & Standard Library
• (Time: 60s) What is the primary use of the
collections.defaultdict?a) To create a dictionary with a default sorting order.
b) To provide a default value for a key that does not exist, avoiding a
KeyError.c) To create a thread-safe dictionary.
d) To create a dictionary that remembers insertion order (like a standard
dict in Python 3.7+).• (Time: 75s) What will this code print?
a) 1
b) 2
c) 3
d)
• (Time: 60s) Which module is used for working with dates and times?
a)
b)
c)
d)
• (Time: 75s) How do you serialize a Python dictionary
a)
b)
c)
d)
• (Time: 90s) What is the output?
a)
b)
c)
d)
• (Time: 60s) To check if a file named
a)
b)
c)
d)
Section 5: Error Handling & File I/O
• (Time: 45s) What is the primary purpose of a
a) To speed up code execution.
b) To handle exceptions and prevent the program from crashing.
c) To define a new type of error.
d) To test code for syntax errors.
• (Time: 90s) In a
a)
b)
c)
d)
• (Time: 75s) Why is using the
a) It automatically reads the entire file into memory.
b) It provides better performance than a standard
c) It automatically closes the file, even if exceptions occur.
d) It automatically creates the file if it doesn't exist.
• (Time: 60s) Which is the best practice for catching exceptions?
a)
b)
c)
d)
• (Time: 75s) What will happen when this code runs?
a)
b)
c)
d) The program will crash.
Section 6: Advanced & Miscellaneous
• (Time: 75s) What does a list comprehension like
a) Creates a list of booleans.
b) Creates a list of even numbers from 0 to 9.
c) Creates a list of odd numbers from 0 to 9.
d) Returns a generator object.
• (Time: 90s) What is the output?
a)
b) 1
c)
d) A
from collections import Counter
my_list = ['a', 'b', 'c', 'a', 'b', 'a']
counts = Counter(my_list)
print(counts['a'])
a) 1
b) 2
c) 3
d)
['a', 'a', 'a']• (Time: 60s) Which module is used for working with dates and times?
a)
timeb)
datec)
datetimed)
calendar• (Time: 75s) How do you serialize a Python dictionary
d into a JSON formatted string?a)
json.load(d)b)
json.dumps(d)c)
pickle.dumps(d)d)
d.to_json()• (Time: 90s) What is the output?
import itertools
data = ['A', 'B']
result = list(itertools.permutations(data, 2))
print(result)
a)
[('A', 'B')]b)
[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]c)
[('A', 'B'), ('B', 'A')]d)
[('A',), ('B',)]• (Time: 60s) To check if a file named
data.txt exists in the current directory, you would use:a)
os.path.exists('data.txt')b)
os.file.exists('data.txt')c)
sys.path.exists('data.txt')d)
open('data.txt').exists()Section 5: Error Handling & File I/O
• (Time: 45s) What is the primary purpose of a
try...except block?a) To speed up code execution.
b) To handle exceptions and prevent the program from crashing.
c) To define a new type of error.
d) To test code for syntax errors.
• (Time: 90s) In a
try...except...else...finally block, which block is always executed regardless of whether an exception occurred or not?a)
tryb)
exceptc)
elsed)
finally• (Time: 75s) Why is using the
with statement (with open(...) as f:) preferred for file handling?a) It automatically reads the entire file into memory.
b) It provides better performance than a standard
try...finally.c) It automatically closes the file, even if exceptions occur.
d) It automatically creates the file if it doesn't exist.
• (Time: 60s) Which is the best practice for catching exceptions?
a)
except:b)
except Exception:c)
except ValueError: (or another specific exception)d)
except Error:• (Time: 75s) What will happen when this code runs?
try:
print("Start")
result = 10 / 0
print("Middle")
except ZeroDivisionError:
print("Caught error")
else:
print("No error")
finally:
print("Finish")
a)
Start, Middle, No error, Finishb)
Start, Caught error, Finishc)
Start, Caught error, No error, Finishd) The program will crash.
Section 6: Advanced & Miscellaneous
• (Time: 75s) What does a list comprehension like
[x for x in range(10) if x % 2 == 0] do?a) Creates a list of booleans.
b) Creates a list of even numbers from 0 to 9.
c) Creates a list of odd numbers from 0 to 9.
d) Returns a generator object.
• (Time: 90s) What is the output?
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k:v for v, k in my_dict.items()}
print(new_dict[1])a)
ab) 1
c)
bd) A
KeyError.• (Time: 75s) What is the Global Interpreter Lock (GIL) in CPython?
a) A security feature that locks global variables.
b) A mechanism that allows only one thread to execute Python bytecode at a time.
c) A tool for debugging multi-threaded applications.
d) A memory management utility.
• (Time: 60s) What is the result of
a)
b)
c) It raises a
d)
• (Time: 90s) To implement a context manager, a class must have which methods?
a)
b)
c)
d)
• (Time: 60s) What will the
a)
b)
c)
d)
• (Time: 75s) Which of the following correctly finds all numbers greater than 10 in a list called
a)
b)
c)
d)
• (Time: 60s) A module that is imported is executed:
a) Every time it is imported.
b) Only the first time it is imported in a program's execution.
c) Never, its functions are just made available.
d) Every time a function from it is called.
• (Time: 90s) What is the purpose of the
a) It defines the main function of the script.
b) It is required for all Python scripts to run.
c) It allows code to be run only when the file is executed directly as a script, not when imported.
d) It is a comment and has no effect on execution.
• (Time: 60s) Which data type is mutable?
a)
b)
c)
d)
• (Time: 75s) What is printed?
a)
b)
c)
d) The code does not print anything.
• (Time: 45s) What is a "virtual environment" in Python used for?
a) To run Python code on a virtual machine.
b) To create an isolated environment for a project with its own dependencies.
c) To test code performance in different environments.
d) A built-in Python IDE.
• (Time: 75s) What is the output?
a) A
b) 20
c) 30
d) 10
• (Time: 60s) How would you remove the key
a)
b)
c)
d)
• (Time: 90s) Consider the Walrus Operator
a) 0
b) 2
c) 7
d) 9
a) A security feature that locks global variables.
b) A mechanism that allows only one thread to execute Python bytecode at a time.
c) A tool for debugging multi-threaded applications.
d) A memory management utility.
• (Time: 60s) What is the result of
*a, b = [1, 2, 3, 4, 5]?a)
a is [1, 2, 3, 4] and b is 5.b)
a is 1 and b is [2, 3, 4, 5].c) It raises a
SyntaxError.d)
a is (1, 2, 3, 4) and b is 5.• (Time: 90s) To implement a context manager, a class must have which methods?
a)
__init__ and __del__b)
__enter__ and __exit__c)
__open__ and __close__d)
__start__ and __stop__• (Time: 60s) What will the
sorted() function do with this input? sorted(['c', 'B', 'a'])a)
['a', 'B', 'c'] (case-insensitive sort)b)
['a', 'c', 'B']c)
['B', 'a', 'c'] (ASCII order)d)
['c', 'B', 'a'] (no change)• (Time: 75s) Which of the following correctly finds all numbers greater than 10 in a list called
nums in a functional style?a)
filter(lambda x: x > 10, nums)b)
[x for x in nums if x > 10]c)
map(lambda x: x > 10, nums)d)
reduce(lambda x, y: x > 10, nums)• (Time: 60s) A module that is imported is executed:
a) Every time it is imported.
b) Only the first time it is imported in a program's execution.
c) Never, its functions are just made available.
d) Every time a function from it is called.
• (Time: 90s) What is the purpose of the
if __name__ == "__main__": block?a) It defines the main function of the script.
b) It is required for all Python scripts to run.
c) It allows code to be run only when the file is executed directly as a script, not when imported.
d) It is a comment and has no effect on execution.
• (Time: 60s) Which data type is mutable?
a)
tupleb)
strc)
intd)
dict• (Time: 75s) What is printed?
t = (1, 2, [3, 4])
try:
t[1] = 5
except TypeError:
print("Error 1")
try:
t[2][0] = 9
except TypeError:
print("Error 2")
print(t)
a)
Error 1, (1, 2, [9, 4])b)
Error 1, Error 2, (1, 2, [3, 4])c)
Error 1, (1, 2, [3, 4])d) The code does not print anything.
• (Time: 45s) What is a "virtual environment" in Python used for?
a) To run Python code on a virtual machine.
b) To create an isolated environment for a project with its own dependencies.
c) To test code performance in different environments.
d) A built-in Python IDE.
• (Time: 75s) What is the output?
from collections import namedtuple
Point = namedtuple('Point', 'x y')
p = Point(10, 20)
print(p.x + p[1])
a) A
TypeError.b) 20
c) 30
d) 10
• (Time: 60s) How would you remove the key
'b' from the dictionary d = {'a': 1, 'b': 2}?a)
d.remove('b')b)
d.pop('b')c)
d.delete('b')d)
d.slice('b')• (Time: 90s) Consider the Walrus Operator
:=. What will be the value of count after this loop?data = [1, 2, 3, 4]
count = 0
while (n := len(data)) > 2:
data.pop()
count += n
a) 0
b) 2
c) 7
d) 9
• (Time: 60s) What does the
a) It terminates the program.
b) It skips the current iteration of a loop.
c) It is a null operation; nothing happens when it executes.
d) It raises a
#Python #Certification #Exam #Programming #CodingTest #Intermediate
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
pass statement do?a) It terminates the program.
b) It skips the current iteration of a loop.
c) It is a null operation; nothing happens when it executes.
d) It raises a
NotImplementedError.#Python #Certification #Exam #Programming #CodingTest #Intermediate
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❤2
What is the difference between asynchrony, multithreading, and multiprocessing?
Answer:
Multithreading uses multiple threads within one process that share memory and can run in parallel with coordination among them.
Multiprocessing launches several isolated processes, each with its own address space and resources, allowing true parallelism at the CPU level.
Simply put, asynchrony is efficient for I/O tasks, threads are used for tasks with shared data, and processes are for resource-intensive computations where load distribution across cores is important.
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
🏆 Mastering 150 JavaScript Core Instructions
📢 Dive into JavaScript! Our comprehensive guide covers 150 core instructions, definitions, and use cases with practical examples. Master web development essentials!
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Dive into JavaScript! Our comprehensive guide covers 150 core instructions, definitions, and use cases with practical examples. Master web development essentials!
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
Mastering 150 JavaScript Core Instructions
A Comprehensive Guide to 150 Core JavaScript Instructions What is JavaScript? JavaScript (JS) is a high-level, often just-in-time compiled, and multi-paradigm programming language. It is one of the core technologies of the World Wide Web, alongside HTML and…
❤1
🏆 150 Design Patterns: A Complete Guide
📢 Dive into 150 essential Software Design Patterns! Learn practical solutions with code examples to build robust, efficient, and scalable applications.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Dive into 150 essential Software Design Patterns! Learn practical solutions with code examples to build robust, efficient, and scalable applications.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
150 Design Patterns: A Complete Guide
A Comprehensive Guide to 150 Concepts in Software Design Patterns What are Design Patterns? In software engineering, a design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished…
❤2
A generator in Python is a function that returns not a single value, but an iterator object.
Generators differ from regular functions in that they use yield instead of return.
The next value from the iterator is obtained by calling next(generator).
Example:
👉 @DataScience4
Generators differ from regular functions in that they use yield instead of return.
The next value from the iterator is obtained by calling next(generator).
Example:
def multiple_generator(x, n):
for i in range(1, n + 1):
yield x * i
multiples_of_5 = multiple_generator(5, 3)
print(next(multiples_of_5)) # 5
print(next(multiples_of_5)) # 10
print(next(multiples_of_5)) # 15
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
🏆 Unlock 150 SQL Clean Code Principles
📢 Unlock cleaner, more maintainable SQL! Explore 150 essential clean code principles to write readable, consistent queries that reduce bugs and simplify collaboration.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Unlock cleaner, more maintainable SQL! Explore 150 essential clean code principles to write readable, consistent queries that reduce bugs and simplify collaboration.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
Unlock 150 SQL Clean Code Principles
A Comprehensive Guide to 150 SQL Clean Code Principles What is SQL Clean Code? SQL Clean Code refers to the practice of writing SQL queries, scripts, and database schemas in a way that is highly readable, consistent, and maintainable. It's not about making…
The Walrus Operator
Introduced in Python 3.8, the "walrus operator"
It solves the common problem where you need to compute a value, check it, and then use it again.
---
#### The Old Way: Repetitive Code
Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".
Notice how
---
#### The Pythonic Way: Using the Walrus Operator
The walrus operator lets you capture the value and test it in a single, elegant line.
Here,
• Calls
• The entire expression evaluates to that same value, which is then compared to
This eliminates redundant code, making your logic cleaner and more direct.
#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
:= (Assignment Expressions)Introduced in Python 3.8, the "walrus operator"
:= allows you to assign a value to a variable as part of a larger expression. It's a powerful tool for writing more concise and readable code, especially in while loops and comprehensions.It solves the common problem where you need to compute a value, check it, and then use it again.
---
#### The Old Way: Repetitive Code
Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".
# We have to get the input once before the loop,
# and then again inside the loop.
command = input("Enter command: ")
while command != "quit":
print(f"Executing: {command}")
command = input("Enter command: ")
print("Exiting program.")
Notice how
input("Enter command: ") is written twice.---
#### The Pythonic Way: Using the Walrus Operator
:=The walrus operator lets you capture the value and test it in a single, elegant line.
while (command := input("Enter command: ")) != "quit":
print(f"Executing: {command}")
print("Exiting program.")Here,
(command := input(...)) does two things:• Calls
input() and assigns its value to the command variable.• The entire expression evaluates to that same value, which is then compared to
"quit".This eliminates redundant code, making your logic cleaner and more direct.
#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❤2
How to view an object's methods?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
❤2🔥1
❔ Interview Question
What is the GIL (Global Interpreter Lock) in Python, and how does it impact the execution of multi-threaded programs?
Answer: The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. This means that in a CPython process, only one thread can be executing Python bytecode at any given moment, even on a multi-core processor.
This has a significant impact on performance:
• For CPU-bound tasks: Multi-threaded Python programs see no performance gain from multiple CPU cores. If you have a task that performs heavy calculations (e.g., image processing, complex math), creating multiple threads will not make it run faster. The threads will execute sequentially, not in parallel, because they have to take turns acquiring the GIL.
• For I/O-bound tasks: The GIL is less of a problem. When a thread is waiting for Input/Output (I/O) operations (like waiting for a network response, reading from a file, or querying a database), it releases the GIL. This allows another thread to run. Therefore, the
How to achieve true parallelism?
To bypass the GIL and leverage multiple CPU cores for CPU-bound tasks, you must use the
tags: #Python #Interview #CodingInterview #GIL #Concurrency #Threading #Multiprocessing #SoftwareEngineering
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
What is the GIL (Global Interpreter Lock) in Python, and how does it impact the execution of multi-threaded programs?
Answer: The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. This means that in a CPython process, only one thread can be executing Python bytecode at any given moment, even on a multi-core processor.
This has a significant impact on performance:
• For CPU-bound tasks: Multi-threaded Python programs see no performance gain from multiple CPU cores. If you have a task that performs heavy calculations (e.g., image processing, complex math), creating multiple threads will not make it run faster. The threads will execute sequentially, not in parallel, because they have to take turns acquiring the GIL.
• For I/O-bound tasks: The GIL is less of a problem. When a thread is waiting for Input/Output (I/O) operations (like waiting for a network response, reading from a file, or querying a database), it releases the GIL. This allows another thread to run. Therefore, the
threading module is still highly effective for tasks that spend most of their time waiting, as it allows for concurrency.How to achieve true parallelism?
To bypass the GIL and leverage multiple CPU cores for CPU-bound tasks, you must use the
multiprocessing module. It creates separate processes, each with its own Python interpreter and memory space, so the GIL of one process does not affect the others.tags: #Python #Interview #CodingInterview #GIL #Concurrency #Threading #Multiprocessing #SoftwareEngineering
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❤1
What objects can be put into a set?
Answer:
Objects like list, dict, set, and other mutable structures cannot be put in: they do not have a hash function (hash) and will cause a TypeError.
ta
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
Python tip:
Use the Path class from the pathlib module to work with file paths cross-platform.
👉 @DataScienceQ
Use the Path class from the pathlib module to work with file paths cross-platform.
from pathlib import Path
p = Path('/usr/local/bin')
Please open Telegram to view this post
VIEW IN TELEGRAM
❤3
🏆 NumPy Python Tips
📢 Boost your Python skills with NumPy! Learn quick tips for efficient array creation and manipulation to level up your data handling.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Boost your Python skills with NumPy! Learn quick tips for efficient array creation and manipulation to level up your data handling.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
NumPy Python Tips
Python tip:Create an uninitialized array (contents are arbitrary) for performance.import numpy as npempty_array = np.empty((2, 3))
❤1
Tired of missing perfect GOLD entries?
Last week alone: 1,740 pips profit, 10/12 trades won—all shared live in our channel.
Ready to catch the next move? Stay ahead with premium signals & real-time updates—don’t just watch, start profiting!
Join GOLD PIPS SIGNALS before the next trade drops!
#ad InsideAds
Last week alone: 1,740 pips profit, 10/12 trades won—all shared live in our channel.
Ready to catch the next move? Stay ahead with premium signals & real-time updates—don’t just watch, start profiting!
Join GOLD PIPS SIGNALS before the next trade drops!
#ad InsideAds
❤1
🌍 Remote Work — India Only 🇮🇳
💰 Earn $800–$2000/month
📆 Weekly payments — card or crypto
🕒 Work 3–4 hours/day
🏠 Fully remote — no office, no experience needed
🎓 Training provided
👉 Indian citizens aged 25+ only
📩 Message our HR manager to apply today!
#ad InsideAds
💰 Earn $800–$2000/month
📆 Weekly payments — card or crypto
🕒 Work 3–4 hours/day
🏠 Fully remote — no office, no experience needed
🎓 Training provided
👉 Indian citizens aged 25+ only
📩 Message our HR manager to apply today!
#ad InsideAds
❤2
What can be a key in a dictionary?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
❤3