0% found this document useful (0 votes)
18 views

Python 155 Coding Questions With Answers

Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers

Uploaded by

hridyasadanand0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
18 views

Python 155 Coding Questions With Answers

Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers Python 155 Coding Questions With Answers

Uploaded by

hridyasadanand0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
1, Data Types and Variables 1, What are the different data types in Python? python Copy code: # Integer x=5 # Float y = 3.44 # string name = "John" # Last Trults = ["apple", “banana”, “cherry"] # Tuple coords = (1, 2) # Dictionary person = {"name": "Alice", "age": 25) # set Unique_nunbers = (4, 2, 3} 2. How do you create a variable in Python? pytnon Copy code a=10 3. What is a mutable and immutable type in Python? Mutable: List, Dictionary, Set Immutable: Sting, Tuple, Integer 4, How do you convert a string to an integer in Python? python Copy code num_str = "123" pum = int(num_str) 5. What is the difference between is and == python Copy code # "is' checks object identity bea print(a is b) # True # '==! chocks value equality a=[4, 2] b= [4, 2] prant(a ==) # True 6. How do you find the data type of a variable? python Copy code x = 10 print(type(x)) # 7. Explain the concept of None in Python. python Copy code a = None print(type(a)) # 8. What is the difference between a list and a tuple in Python? List: Matable, defined by [] Tuple: Immutable, defined by () python Copy code # List Ast = [1, 2, 3] Ust[9] = 10 # Works # Tupte tup = (1, 2, 3) # tup[0]'= 10 # Throws TypeError 9. Whatis an if statement in Python? python Copy code x= 10 af x > 5: prant("x is greater than 5") 10.How do you write an if -e 1se statement in Python? python Copy code x= at x > 5: prant("x is greater than 5") else: prant("x is less than or equal to 5") 11.What is a for loop and how is it different from a whi le loop? For loop iterates over a sequence. whi Le loop runs as long as a condition is True. python Copy code # For loop Tor 2 in range(5): print(i) # Prints @ to 4 # While loop 128 while 4 <5: print(i) # Prints @ to 4 ited 12.How do you write a whi le loop in Python? python Copy code x=@ while x <5: print(x) kasd 13.Explain the break and continue statements in Python. python Copy code # break for i in range(19); if i==5: break # Exit loop when i is 5 prant(i) # continue for i in range(19): if t= 6: continue # Skip iteration when 4 is 5 prant(i} ‘14. What is a pass statement used for? python Copy code. # pass is a placeholder, used when a statement is required syntactically but you don't want to execute any code. det Tunction(): pass. 15. What is a try-except block in Python? python Copy code try: x= 10/0 except ZeroDivision€rror: prant("Cannot divide by zero") 16.How do you define a function in Python? python Copy code def greet(name: return THeLlo, {name}!" print (greet ("Alice") ) 17.What is the difference between a function and a lambda function? python Copy code # Regular function def Square(x) return x # Lambda function square_lanbaa = lambda x: x * x 18, What are default arguments in Python functions? python Copy code def greet(name="Guest"): return f"Hello, {name}!" print(greet()) # Hello, Guest! print (greot("Alico")) # Hello, Alice! 19.How do you return multiple values from a Python function? python Copy code def get_coordinates(): return 4, 2 x, y = get_coordinates() 20.What is the purpose of the gLoba1 keyword in Python? pytnon Copy code x25 det change_gtovat(): global x x= 19 change_global() print(x) # 10 21. What is the purpose of the nonlocal keyword in Python? python Copy code def outer(): x=5 def inner(): hontocal x x= 10 inner() print(x) # 10 outer() 22.What is a list in Python? python Copy code lst = [1, 2, 3] 23.How do you add elements to a list in Python? python Copy code. ist = [1, 2, 3] ‘st .append(4) print(ist) # [1, 2, 3, 4] 24. What is a dictionary in Python? python Copy code person = {"name": "Alice", "age": 25} 25.How do you remove an item from a dictionary in Python? python Copy code person = {"name": "Alice", "age": 25) person. pop( "age" } print(person) # {'name': ‘Alice'} 26. What is a set in Python and how is it different froma list? + Set: Unordered, no duplicates. python Copy code my set = {1, 2, 3} 27.How do you merge two lists in Python? python Copy code Ist1 = [4, 2] ist2 = [3 4] Ust2 = Ista + 1st2 print(1st3) # [1, 2, 3, 4] 28.How do you access elements in a list, dictionary, and set? python Copy code # List Ast = [1, 2, 3] print(1st[o]) #4 # Dictionary person = {"name": "Alice", "age" print(person["nane"]) # Alice 28) # Set (use iteration or conversion to list) my_set = {1, 2, 3} for item in my set: print(item) 29.What are list comprehensions in Python? python Copy code Ast = [x for x in range(5)] print(ist) # [@, 1, 2, 3, 4] ‘30. What is a nested list in Python? python Copy coae nested st = [[1, 2], [% 4], [5 6]] 31.How do you sorta list in Python? pytnon Copy code. tet = [ae ty 2] Ist sort () prant(ist) # [1, 2, 3] 32.How do you concatenate strings in Python? python Copy code str = "Hello" etr2 = "World" result = stri + " "+ str2 print(result) # Hello World 33.How do you split a string in Python? python Copy code text = "Hello World” words = text.split() print (words) # ['Hello', 'World'] 34.How do you check if a string contains a certain substring in Python? python Copy code text = "Hello World” print(*World" in text) # True 35.How do you convert a string to uppercase or lowercase in Python? python Copy code text = "Hello World” print (text .upper()) # HELLO WORLD print(text.lower()) # hello world 36.How do you remove whitespace from the beginning and end of a string? python Copy code text =" Hello World " print(text.strip()) # Hello World 37. What is string slicing in Python? python Copy code text = "Hello World" print(text[@:5]) # Hello print(text[6:]) # World 38.How do you find the length of a string in Python? python Copy code text = "Hello World” print(ten(text)) #11 39.How do you define a class in Python? python Copy code class Person: def _init_(self, name, age): self.name = name self.age = age person = Person("Alice", 25) print(person.name) # Alice 40.What is a constructor in Python? python Copy code # Constructor is the __init__ method that initializes the object class Person: def init__(self, name, age): self.name = name self.age = age person = Person("Bob", 39) print(person.name) # Bob 41.What is inheritance in Python? python Copy code class Animal: det speak(setr): print ("Animal speaks") class Dog(Animal) det speak(seir): print ("Dog barks") dog = Dog() dog.speak() # Dog varks 42.How do you create an object of a class in Python? python Copy coue class Person: def _init_(setf, name): self.name = name persona = Person("Alice") print(personi.nane) # Alice 43. What is method overriding in Python? python Copy code class Anima’ det sound(setr): print ("Animal sound") class Dog(Animal) : der sound(seir): print ("Bark") dog = Dog() dog.sound() # Bark 44. What is the difference between _str__() and__repr__() in Python? python Copy code class Person: det _init_(self, name): self.name = name def _str_(selr): return f"Person: {self.name}" def _repr_(self): return f"Person({self.name})" person = Person("Alice") print(str(person)) # Person: Alice print(repr(person)) # Person(Alice) 45.How do you create a static method in Python? python Copy code class MyClass: @staticnethod det static_methoa( print ("Static method called") MyClass.static_method() # Static method called 46.How do you create a class method in Python? python Copy code class MyClass: Aclassmethod def class method(cls) : print ("Class method called") MyClass.class_method() # Class method called 47.How do you open a file in Python? python Copy code file = open(“example.txt", "r") 48.How do you read from a file in Python? python Copy code file = open("exanple.txt", "r'") content = file.read() print (content) file.close() 49.How do you write to a file in Python? python Copy code Tile = open("exanple.txt" file.write("Hello, World! file.close() owt) 50.How do you dose a file in Python? python Copy code file = open("example.txt", "r") file.close() 51. What is the difference between read( ) and read Lines( )? python Copy code # read() reads the entire content as a single string file = apen(“exanple.txt", "r") content = file.read() print (content) Tile,close() # readlines() reads the content as a List of Lines file = open("example.txt", "r") lines = Tile.readLines() print (lines) file.close() 52.How do you handle file exceptions in Python? python Copy code try: File = open( "example. txt content = file.read() except FileNotfounderror: print("File not found") finally: File.close() 53.What is an exception in Python? python Copy coae try: x= 19/0 except ZeroDivisionError as e: prant(r"error: {e}") 54.What is the difference between try -except and try- except -FinaLly blocks? python Copy code # try-except try: x= 19/0 except ZeroDivisionerror: prant("Cannot divide by zero") # try-except-finally try: x= 19/0 except ZeroDivisionerror: print("Cannot divide by zero") finally: prant("This will always execute”) 55.How do you raise an exception in Python? python Copy code def divide(x, y): ify == 0: raise ValueError("Cannot divide by zero”) return x / y print(divide(19, 0)) # Raises ValueError 56.What is a custom exception in Python? python Copy code class CustonError (Exception): pass. try: raise CustomError("This is a custom error") except CustomErrar as e: print(e) # This is a custom error 57.What is the purpose of the assert statement in Python? python Copy code x = 10 assert x == 19 # No output, passes assert x == 5 # Raises AssertionError 58.How do you import a module in Python? python Copy code inport math print(math.sqrt(i6)) # 4.0 59.What is the difference between import and from ... import? python Copy code # import inport math print(math.sqrt(16)) # 4.0 # from... import from math import sqrt print(sqrt(16)) # 4.0 60. What is the purpose of the init__.py file in a package? The __indt__. py file is used to mark a directory as a Python package, enabling it to contain submoduies. 61.How do you create a package in Python? Create a directory and add an _init__. py file inside. 62. What is the difference between os and sys modules? 0: Provides functions for interacting with the operating system, syS: Provides access to system-specific parameters and functions. python Copy code inport os print(os.getewd()) # Get current working directory import sys print(sys.version) # Python version 63.How do you install a package using pip? Use the command pip install package_name in the terminal. 64. What is a decorator in Python? python Copy code def my_decorator (func): def wrapper(): print("Before the function call") fune() print ("After the function call") return wrapper @ny_decorator def say_hello( print("Hello!™) say_hello( ) 65.How do you pass arguments to a decorator in Python? python Copy code det my_decorator (func) def wrapper(‘args, **kwargs): print ("Before the function call") fune(*targs, **kwargs) print("After the function catt") return wrapper @ay_decorator det say_hello(nane): print(T*Hello, {name}!") say_hello("Alice") 66. What 1s a generator in Python? python Copy code def my_generator(): yield 1 yield 2 yield 3 gen = ay_generator() for value in gen: print(value) 67. What is the difference between a generator and a normal function? Agenerator uses the y ie Ld statement and reiurns an iterator, whereas a normal function retums a single result using return. 68.How do you create an infinite generator in Python? python Copy coae def infinite_gen(): nun = 0 while True: yield nun Aum += 1. gen = infinite_gen() for _ in range(5): print(next(gen)) # Prints 0, 1, 2, 3, 4 69, What is a lambda function in Python? python Copy code square = lambda x: x * x print(square(5)) # 25 70.How do you use map () in Python? python Copy code numbers = [1, 2, 3, 4] squared = map(lambda x: x * x, numbers) print(1ist(squared)) # [1, 4, 9, 16] 71.How do you use Filter( ) in Python? python Copy coae numbers = [4, 2, 3, 4, 5] even numbers = filter(lambda x: x % 2 == 0, numbers) print(1ist(even_numbers)) # [2, 4] 72.What is reduce( ) in Python? python Copy code from functools import reduce numbers = [4, 2, 3, 4] product = reduce(tambda x, y: x * y, numbers) print (product) # 24 73.What is a list comprehension in Python? python Copy code numbers = [4, 2, 3, 4, 5] squares = [x * x for x in numbers] print(squares) # [1, 4, 9, 16, 25] 74.How do you create a dictionary comprehension in Python? python Copy code numbers = [1, 2, 3, 4, 5] square dict - (x: x * x for x in numbers} print (square dict) # {4: 1, 2: 4, 3: 9, 4: 16, 5: 25} 75.How do you create a set comprehension in Python? python Copy code numbers = [1, 2, 3, 4, 5] square_set = {x'* x Tor X an numbers} print(square sot) # {1, 4, 9, 46, 25} 76.How do you create a generator expression in Python? pytnon Copy code: numbers = [1, 2, 3, 4, 5] square_gen = (x'* x for x in numbers) Tor square in square_gen: prant(square) 77.How do you use regular expressions in Python? python Copy code inport re text = "The price is $109" pattern = r"\de" result = re.findall(pattern, text) print(result) # ['100"] 78.How do you match a string using a regular expression in Python? python Copy code import re text = "The price 4s siea” pattern = r*\S[0-9]+" match = re.search(pattern, text) print (natch.group()) # $100 79.How do you replace a part of a string using regular expressions in Python? python Copy code inport re text = "The price is $100" pattern = r"\$[0-9]+" Rew_text = re.sub(pattern, "S200", text) print(new_text) # The price is $200 80. What is multithreading in Python? python Copy code import threading def print_numbers(): for i in range(5): prant(1) thread = threading. Thread(target=print_nunbers) thread.start() thread.join() # Walt for the thread to rinish 81. What is multiprocessing in Python? python Copy code from multiprocessing impart Pracess def print_numbers(): for 1 in range(5) print (i) process = Process(target=print_numbers) process. start() process. join() # Wait for the process to finish 82.How do you use concurrent . futures for parallelism in Python? python Copy code from concurrent.futures import ThreadPoolExecutor def print_numbers(i): print(i) with ThreadPoolExecutor() as executor: executor.map(print_numbers, range(5)) 83. What is an iterator in Python? python Copy code numbers = [1, 2, 3] iterator = iter (numbers) print(next(iterator)) #1. print(next(iterator)) #2 print(next(iterator)) #3 84. What is a deque in Python? pytnon Copy code. from collections import deque queue = deque({1, 2, 3]) queue. append( 4) queue. appendleft (0) print(queve) # deque([@, 1, 2, 3, 4]) 85.How do you remove an element from a deque? python Copy code Trom collections import deque queue = deque([1, 2, 3]) queue . pop( ) queue. poplett() print (queue) # deque([2]) ‘86.How do you sort a list of dictionaries by a key in Python? python Copy code people {'name!: ‘Charlie’, ‘age': 26}] [{'name': 'Alice', ‘age’: 25}, {'name': 'Bob', ‘age’: 30}, sorted people = sorted(people, key=lambda x: x[*age']) print(sorted_people) # [{'name': "age": 25}, {'nane': "Bod", ‘age’: 30}] 87.How do you perform binary search in Python? python Charlie’, ‘age’: 20}, {'name': ‘Alice’, Copy code import bisect numbers = [1, 2, 3, 4, 5] index = bisect.bisect_left(numbers, 3) print(index) #2 £88.How do you sorta list in descending order in Python? python Copy code numbers = [5, 3, 1, 4, 2] numbers. sort (reverse=True) Print (numbers) # [5, 4, 3, 2 1] £89.How do you create a shallow copy of a list in Python? python Copy code original = [1, 2, 3] copy = original. copy(} 90.Whatis a set in Python, and how do you perform set operations? python Copy code set = {1, 2, 3} set2 = {3, 4, 5} print(set1 4 set2) # Intersection: {3} print(set1 | set2) # Union: {1, 2, 3, 4, 5} print(seti - setz) # DarTerence: {1, 2} 91.How do you get unique elements from alist using a setin Python? python Copy coe numbers = [1, 2, 3, 3, 4, 5, 5] unique_numbers = List(set (numbers)) print(unique_numbers) # [1, 2, 3, 4, 5] 92.How do you merge two dictionaries in Python? python Copy code dict te thts 2} dict2 = {'b': 3, ‘ct: a} merged = {**dicti, **dict2) print(merged) # {'a': 1, " ‘93. What is the Zip( ) function in Python? python Copy code last1 = [1, 2, 3] list2 = ra", "bY, te] zipped = zip(list1, list2) print(1ist(zipped)) # [(4, ‘a'}, (2, 'b'), (3, 'c")] 94.How do you check for membership in a list in Python? python Copy code my lst = [1, 2, 3, 4] print(3 in my list) # True print(5 in my list) # False 95. What is a heap in Python, and how do you use it? python Copy code import heapq heap = [] heapq-heappush(heap, 20) heapg-heappush(heap, 5) heapq-heanpush(heap, 20) print(heap) # [5, 10, 29] print (heang.heappop(heap)) # 5 96.How do you create a priority queue in Python? python Copy code import heapq prioraty_queue = [] heapq.heappush(priority queue, (2, ‘task 2')) heapq-heappush( priority queue, (1, ‘task 1')) heapq.heappush( priority _queue, (3, ‘task 3')) print (heapq.heappop(priority_queue)) # (1, ‘task 1') 97.What is a defaultdict in Python? python Copy code from collections import defaultdict dd = defaultdict (int) dd[‘apple'] += 1 dd[ banana] += 2 print(dd) # defaultdict(, {'apple': 1, ‘banana’: 2}) 98. What is a Counter in Python, and how do you use it? python copy coue from collections import Counter items = ["apple', ‘banana’, ‘apple’, ‘orange’, ‘banana’, ‘banana'] counter = Counter(items) print(counter) # Counter({‘banana’: 3, ‘apple’: 2, ‘orange’: 1}) 99.How do you implement a stack using a list in Python? python Copy code stack = [] stack.append(1) # Push stack.append(2) # Push print (stack.pop()) # Pop: 2 Print(stack) # [1] 100.How do you implement a queue using a deque in Python? “python from collections import deque Copy code queue = deque() perl Copy code queue.append(1) # Enqueue queue.append(2) # Enqueue print(queue.poplert()] # Dequeue: 1 print(queue) # deque([2]) 101.How do you get the current date and time in Python? ~ python from datetime import datetime makefile Copy code now = datetime.now() pert Copy code print(now) # e.g., 2024-12-25 14:39:00.123456 102. How do you format a date in Python? “python from dateuime import datetime perl Copy code now = datetine.now() formatted_date = now.strftine("%V-%m-%d %H:%M:%S" ) print(formatted date) #e.g., 2024-12-25 14:30:00 103. How do you parse a string into a date in Python? *python from datetime import datedme perl Copy code date_str = "2024-12-25" date_obj = datetime.strptime(date_str, "%Y-%m-%d") print(date_obJ) # 2024-12-25 09:00:00 104. How do you calculate the difference between two dates in Python? import datetime ‘python from datetime sess Copy code date1 = datetime(2024, 12, 25) date2 = datetime(2024, 12, 31) gitrerence = aate2 - datel print(difference.days) # 6 105. How do you add or subtract days froma date in Python? * python from datetime import datetime, timedelta Copy code today = datetime.now() tomorrow = today + timedelta(days=1) yesterday = today - tinedelta(days=1) print( tomorrow) print( yesterday) 106.What is the purpose of the asser t keyword in Python? python x = 19 assert x == 10 # Passes assert x == 5 # Raises Assertionerror 107.How do you write a simple unit testin Python? “python import unittest css Copy code det add(a, b): ruby Copy coue return a+b class TestMathOperations(unittest.TestCase) : def test_add(selr) self.assertEqual(add(2, 2), 5) af _nane_ == "_main_": unittest.main{ ) 108. What is the pytest framework in Python? “python # Ina file named test_sample.py def ssert add(2, 3) == 5. test_addition(): perl Copy code # Run the test with the command: pytest test_sanple.py 109. How do you use mock to mock an object in Python testing? “python from unittest import mock ruby Copy code def get_data(): return "real data” def fetch_data(): return get_data() # Mock the get_data function with mock.patch('_main_.get_data', return_value: print (fetch_data()) # mocked data ‘mocked data"): 110.How do you send an HTTP GET request in Python? ~ python import requests esharp Copy code Fesponse = requests.get("nttps: //jsonplaceno der . typicode.com/posts" ) pert Copy code print(response.text) # The content of the response 111. How do you send an HTTPPOST request in Python? “python import requests go Copy cove data = {'name': 'Alice', ‘age’: 25} response = requests post ("https://jsonplaceholder .typicode.com/posts", json=data) print(response.json()) 112. How do you handle exceptions when making HTTP requests? * “python import requests python Copy code try: response = requests.get("https://nonexistenturl.com") response raise_for_status() except requests. exceptions .RequestException as e: print(f"Error: {e}") 113. How do you parse JSON data in Python? ~*python import json sess. Copy code Json_str = ‘{"name": "Alice", "age": 25)* data = json. loads(json_str) print(data) # {'name': ‘Alice’, ‘age’: 25} 114. How do you convert a Python object to JSON? ™ python import json go Copy code data = {'name': ‘Alice’, ‘age’: 25} json_str = json. dumps (data) Print(json_str) # {"name": "Alice", "age": 25} 115.How do you interact with REST APIs in Python? * “python import requests, esharp Copy code response = requests.get( "https: //jsonplaceholder . typicode.com/posts") perl Copy code print(response.json()) # Parse the response to JSON 116. How do you use basic authentication with requests in Python? **pytion from requests.cuth impor HTTPBasicAuth go Copy code response = requests.get("https://example.com", auth=HTTPBasicAuth( ‘username’, ‘passward')) print(response.text) 117. How do you handle timeouts in requests in Python? ~ python import requests python Copy code try: response = requests get("https://example.com", timeout=5) print (response. text) except requests. exceptions. Timeout: print ("The request timed out") 118. How do you handle JSON data from a POST request in Python? python import requests pert Copy code data = {'name': ‘Alice’, ‘age’: 25) response = requests.post "https: //Jsonplaceholder .typicode.com/posts", json=data) print(response.json()) # Parse the response JSON 119.How do you measure the execution time of a Python function? “python import time ruby Copy code dof stow_function(): wa Copy code time. steep(2) start_time = time.time() slow_function() end_time = time. time( ) print(f"Execution time: {end time - start time} seconds") 120. How do you profile a Python program to check its performance? ~ python import cProfile sess. Copy code det stow_function(): time. steep(2) cProfite.run(*slow_function()") 121, How do you use memoization to optimize recursive functions in Python? ~python from functools import Inm_cache python Copy coue @lru_cacho(maxeize=None) def fibonacci(n): if n< return n return Tibonacci(n-1) + fibonacei(n-2) print(fibonacci(100)) # Optimized version of Fibonacci sequence 122. How do you implement caching in Python using Funct 001s. Lru_cache? ™ python from functools import Iru_cache python Copy code @lru_cache(maxsize=100) det expensive_computation(x): return x * x # Simulate an expensive operation print(expensive computation(5)) # Cached result 123.How do you read a file line by line in Python? python with open('sample.txt', 'r') as file: for Line in file: print (Line.strip()) 124.How do you write to a file in Python? python with open('output.txt', 'w') as file: file.write('Hello, World!\n') file.write( 'Python is awesome!) 125.How do you append to a file in Python? python with open( ‘output. txt', 'a') as file: file.write('\nAppending new content.') 126.How do you check if a file exists in Python? * python import os lua Copy code if os.path.exists( ‘sample. txt"): go Copy cose print ("File exists") else: print("File does not exist") 127. How do you handle file exceptions in Python? python try: with open( 'nonexistentfile.txt', 'r') as file: content = file.read() except FileNotFoundError: print("File not found") 128.What is a context manager in Python? python class MyContextManager: def enter (self): print("Entering the context’) retum self def exit(self, exc_type, exc_val, exc_tb): prini(" Exiting the context") esharp Copy code with MyContextManager (): go Copy code print ("Inside the context") 129. How do you use context Lib to create a context manager? "python from contextlib impor contextmanager less Copy code @contextmanager det my_context(): print("Entering the context") yield print ("Exiting the context") with my_context() print ("Inside the context") 130.How do you manually free up memory in Python? “python import ge bash Copy code # To free up memory manually perl Copy code del some_object gc.collect() # Force garbage collection 131, What is the gc module used for in Python? ~python import ge perl Copy code # Nanually trigger garbage collection ge.collect() 132. What is reference counting in Python? - Python uses reference counting to manage memory. When an object’s reference count drops to zero, itis garbage collected. 133.What is the purpose of del in Python? python a = [4, 2, 3] del a # Deletes the reference to the list object 134.How do you load JSON data from a je in Python? python import json python Copy coae with open('data.json', 'r') as file: sess. Copy code data = Json. load(Tite) print (data) 135. How do you write JSON data to a file in Python? “python import json kotlin Copy code data = {"name’: ‘Alice’, ‘age’: 30} with open(‘output.json', 'w!) as file json. dump(data, file) 136. How do you pretty-print JSON in Python? python import json go Copy coue data = ['name': 'Alice', ‘age': 20) print(json.dumps(data, indeni 137. How do you handle JSON decoding errors? python Copy code anvalid_json = ‘{*name try: data = json. loads(invalid json) except json.JSONDecodeError as e print(T"JSON decoding error: {e}") python import json Alice", age: 30}' 136.How do you pass command-line arguments to a Python script? “python import sys bash Copy code # Run as python seript.py argi arg2 sess. Copy code print(sys.argv) # ["script.py", ‘argi’, ‘arg2"] 139. How do you parse command-line arguments with ar gparse? ~ python import argparse python Copy code parser = argparse.ArgunentParser() parser .add_argument(‘name’, type=str, help="Your name" ) args = parser.parse_args() print(f"Hello, {args.name}") 140. How do you set default values for command-line arguments? *"python import argparse go Copy code parser = argparse.ArgumentParser() parser.add_argument('--age', type=ant, default=90, help='Your age’) args = parser.parse_args() print(f"Age: {args.age}") 141. What is the f- string for string formatting in Python 3.6+? python name = ‘Alice’ age = 30 print(f"Name: {name}, Age: {age}") 142.How do you use type annotations in Python 3? “python def greet(name: str, age: int) -> str retum f"Hello {name}, you are {age} years old” bash Copy code print(greet("Alice", 20)) go Copy code 143. What are the main differences between Python 2.x and Python 3.x? - Python 3 uses print () asa function, while Python 2 uses it asa statement. - Python 3 has better Unicode support. - Integer division retums a float in Python 3. 144,How do you create a virtual environmentin Python? bash python -m venv myeny 145.How do you install packages from requirements .txt in Python? bash pip install -r requirements .txt 146.How do you create a setup . py file for a Python package? ~ python from seuptools import setup, find_packages sess. Copy code setup( go Copy code name="my_package", version=".1", packages-f ind’ packages(), instaUl_requires=[ ‘requests’, *numpy* he 147. How do you upload a Python package to PyPI? - Install twine: bash pip install twine -Build the package: bash python setup.py sdist bdist_wheel - Upload the package to PyPI: bash twine upload dist/* 148.How do you create a simple web server with Flask? ~ python from flask import Flask sess Copy code app = Flask(__name__) less Copy code @app.route(*/*) det hello_wortd() return "Hello, World!" if _mane__ == '_main_': app. run (debug=True) 149. How do you handle GET and POST requests with FLask? ™*python from flask import Flask, request python Copy code app = Flask(__name_) @app.route( */submit', methods=['POST"}) def submit() data = request. form['nane'] return f"Hello {data}" af __nane_ app. run (debu ig=True) 150. How do you set up a RESTful API using Flask? ~ python from flask import Flask, jsonify python Copy code app = Flask(__name__) @app.route( '/api/vi/resource', methods=["GET"]) def get_resource(): return jsonity({"message": "Hello, API!"}) af _nane__ == '_main_': app. run(debug=True) 151.How do you ensure your Python code is readable and maintainable? - Follow PEP & (Python's style guide). - Write modular code with functions and classes. - Use descriptive variable and function names. 152.How do you use docstrings to document your code? ~~ python def greet(name: str) -> sir: """ Greet a person by their name, Args: name (str): The name of the person. Retums: str: A greeting message. ""” return f'Hello, {name}! 153. What is the purpose of unit tests in Python? - Unit tests verify that individual components of your code work correctly. - They help catch bugs early and ensure code changes don't break existing functionality. 154,How do you create an asynchronous function in Python using asyneio? ~ python import asyncio esharp Copy cove asyne def hella() sess Copy coue print ("Hello") await asyncio.sleep(1) print ("Wortd") asyncio.run(hetto( )) 155. How do you create and run multiple asynchronous tasks in Python? ™* python import asyncio Copy code async def task1() await asyncio.sleep(1) print ("Task 4") asyne def task2() await asyncio.sleep(2) print ("Task 2") async def main(): await asyncio.gather(task1(), task2()) asyneio.run(nain())

You might also like