{"id":202,"date":"2023-03-22T16:25:09","date_gmt":"2023-03-22T16:25:09","guid":{"rendered":"https:\/\/codeinterview.io\/blog\/?p=202"},"modified":"2024-09-02T05:59:21","modified_gmt":"2024-09-02T05:59:21","slug":"python-coding-interview-questions","status":"publish","type":"post","link":"https:\/\/codeinterview.io\/blog\/python-coding-interview-questions\/","title":{"rendered":"30 Python Coding Interview Questions for Beginner, Mid-Level and Expert Developers"},"content":{"rendered":"\n<p>Python is one of the important programming languages for backend software development. One of the reasons it is so popular is its use in machine learning and artificial intelligence. As Python is ideal for compute-intensive operations, that means it is best suited to all the use cases where computer vision, machine learning or deep learning is utilized. That&#8217;s the reason you will see most of the machine learning libraries and frameworks in Python and a majority of AI engineers write code in Python. Besides AI, Python is also used extensively for backend development, including API and business services development.&nbsp;<\/p>\n\n\n\n<p>Today we will discuss technical coding challenges for Python engineers. We will separately specify coding challenges for beginner, mid-level and expert Python engineers. These coding challenges will not only help technical managers evaluate Python engineers but will also be helpful to candidates who want to test their skills. Let&#8217;s start with coding challenges for beginner-level developers in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-interview-questions-for-beginner-level-python-engineers\"><strong>Interview Questions for Beginner-level Python Engineers<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/codeinterview.io\/signup\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"196\" src=\"https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-2.png\" alt=\"Developer Skill Assessment Tool\" class=\"wp-image-533\" srcset=\"https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-2.png 1024w, https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-2-300x57.png 300w, https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-2-768x147.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n\n\n<p>When preparing interview questions for beginners in the <a href=\"https:\/\/codeinterview.io\/languages\/python-2\">Python language<\/a>, you should focus on basic syntax, language constructs, data structure, libraries, algorithms, OOP, error handling, regular expressions and networking. Here are some of the coding challenges which are suitable for beginner-level Python engineers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-1\">Question 1<\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var1 = 7\nvar2 = 2\nresult = var1 \/\/ var2+ var1%var2\nprint(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-2\">Question 2<\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def concatenate_strings(str1, str2):\n\treturn str1 + \" \" + str2\n \nresult = concatenate_strings(\"Test\", 3)\nprint(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-3\">Question 3<\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def print_uppercase(text):\n\tfor letter in text:\n    \tprint(letter.upper())\n \nprint_uppercase(&#91;\"Test\", \"Python\"])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-4\"><strong>Question 4<\/strong><\/h3>\n\n\n\n<p>Write a method that calculates the simple interest on a loan. The program should take user input for the principal amount, the annual interest rate (as a percentage), and the time to pay in years. The program should calculate and display the total amount (principal + interest) after the specified time.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-5\"><strong>Question 5<\/strong><\/h3>\n\n\n\n<p>What will be the output of the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test(x, y=&#91;]):\n\ty.append(x)\n\treturn y\nprint(test(1))\nprint(test(2))<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-6\"><strong>Question 6<\/strong><\/h3>\n\n\n\n<p>What is wrong in the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>name = input(\"Input your name: \")\nif name == \"John\" or \"Brian\":\n\tprint(\"Welcome, John or Brian!\")\nelse:\n\tprint(\"You're not John or Brian.\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-7\"><strong>Question 7<\/strong><\/h3>\n\n\n\n<p>Create a simple calculator that can perform basic arithmetic operations (addition, subtraction, multiplication and division) on two numbers. The program should take user input for both numbers and the desired operation. The result of the operation will be printed on the screen.&nbsp;&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-8\"><strong>Question 8<\/strong><\/h3>\n\n\n\n<p>What will be the output of the following code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;5, 1, 9, 3, 7]\nsquared_numbers = list(map(lambda x: x**2, numbers))\nsquared_numbers.sort(reverse=True)\nprint(squared_numbers&#91;:3])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-9\"><strong>Question 9<\/strong><\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\nurl = \"https:\/\/jsonplaceholder.typicode.com\/users\"\nresponse = requests.get(url)\ndata = response.json()\n \nemail_addresses = &#91;user&#91;\"email\"] for user in data if user&#91;\"company\"]&#91;\"catchPhrase\"].contains(\"fintech\")]\nprint(email_addresses)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-10\"><strong>Question 10<\/strong><\/h3>\n\n\n\n<p>Find the issue in the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = {1: \"one\", 2: \"two\", 3: \"three\"}\nfor number in numbers:\n\tif numbers&#91;number] == \"two\":\n    \tdel numbers&#91;number]\nprint(numbers)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-interview-questions-for-mid-level-python-engineers\">Interview Questions for Mid-level Python Engineers<\/h2>\n\n\n\n<p>When designing interview questions for mid-level Python developers, you should focus on questions that test the deeper understanding of the language and advanced features. Some of the areas that should be tested include advanced data structures, multithreading, performance optimization, unit testing, advanced OOP and web services. Find below some of the questions that test these concepts:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-1-0\"><strong>Question 1<\/strong><\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def caching_decorator(func):\n\tcache = {}\n \tdef wrapper(*args):\n  \t  if args in cache:\n        \treturn cache&#91;args]\n    \tresult = func(*args)\n    \tcache&#91;args] = result\n    \treturn result\n \treturn wrapper\n @caching_decorator\ndef add(a, b):\n\treturn a + b\n \nadd(3, 5)\nprint(add.cache)\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-2-0\"><strong>Question 2<\/strong><\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_function():\n\ttry:\n    \treturn \"In try\"\n\tfinally:\n    \treturn \"In finally\"\n \nresult = test_function()\nprint(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-3-0\"><strong>Question 3<\/strong><\/h3>\n\n\n\n<p>Develop a task scheduler that runs a specific function after a certain period of time. The scheduler should take user input for the function to run, the time interval (in seconds) between each run, and the total number of runs. Use Python&#8217;s threading or multiprocessing module to develop the scheduler.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-4-0\"><strong>Question 4<\/strong><\/h3>\n\n\n\n<p>Develop a Python-based web scraper that retrieves a specific piece of information from a website. For example, extract all code snippets from a technology blog or get the current price of a product from a shopping website. Use libraries like Beautiful Soup or Scrapy to parse the HTML content and extract the relevant data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-5-0\"><strong>Question 5<\/strong><\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading\n counter = 0\n def increment_counter():\n\tglobal counter\n\tfor _ in range(100000):\n    \tcounter += 1\n \nthreads = &#91;threading.Thread(target=increment_counter) for _ in range(10)]\n&#91;thread.start() for thread in threads]\n&#91;thread.join() for thread in threads]\n \nprint(counter)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-6-0\"><strong>Question 6<\/strong><\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def outer_function():\n\tvalue = \"Say cheese to\"\n \n\tdef inner_function1():\n    \tnonlocal value\n    \tvalue = \"Python\"\n \n\tdef inner_function2():\n    \tglobal value\n    \tvalue = \"Engineers\"\n \n\tinner_function1()\n\tinner_function2()\n\treturn value\n \nvalue = \"Programming\"\nresult = outer_function()\nprint(value, result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-7-0\"><strong>Question 7<\/strong><\/h3>\n\n\n\n<p>What is wrong with below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import requests\ndef fetch_data(api_url):\n\ttry:\n    \tresponse = requests.get(api_url)\n    \tresponse.raise_for_status()\n    \treturn response.json()\n\texcept requests.HTTPError as e:\n    \tprint(\"Error: \", e)\n \napi_url = \"https:\/\/jsonplaceholder.typicode.com\/todos\/1\"\ndata = fetch_data(api_url)\nprint(data&#91;\"title\"])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-8-0\"><strong>Question 8<\/strong><\/h3>\n\n\n\n<p>Develop a Python function that reads a text file and calculates the metadata, including the number of lines, words, and characters in the file. You can ignore whitespaces and punctuation when counting characters. There will be only one input to this program: the text file. After processing, the result will be printed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-9-0\"><strong>Question 9<\/strong><\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = &#91;\n\t{\"id\": 1, \"name\": \"Helen\", \"age\": 28},\n\t{\"id\": 2, \"name\": \"Chris\", \"age\": 49},\n\t{\"id\": 3, \"name\": \"Jennifer\", \"age\": 19},\n]\nresult = {item&#91;\"name\"]: item&#91;\"age\"] for item in data if item&#91;\"age\"] &gt; 20}\nprint(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-10-0\"><strong>Question 10<\/strong><\/h3>\n\n\n\n<p>Implement two versions of a function that generates the first n Fibonacci numbers. The first version of the function should be a regular function that returns a list of Fibonacci numbers, while the other version should be a generator function that produces Fibonacci numbers one at a time. Compare both implementations&#8217; memory usage and runtime performance and share your results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-interview-questions-for-expert-level-python-engineers\"><strong>Interview Questions for Expert-level Python Engineers<\/strong><\/h2>\n\n\n\n<p>When designing coding challenges for expert-level Python developers, you should evaluate the advanced concepts and in-depth knowledge of Python\u2019s features. Some of the areas to test include advanced algorithms, metaprogramming, code optimization, profiling, parallelism, design patterns, security and distributed systems. Here are some coding challenges which are suitable for expert Python developers:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-1-1\"><strong>Question 1<\/strong><\/h3>\n\n\n\n<p>Find the issue in the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MyResource:\n\tdef __init__(self, name):\n    \tself.name = name\n \n\tdef __enter__(self):\n        print(f\"Acquiring {self.name}\")\n    \treturn self\n \n\tdef __exit__(self, exc_type, exc_value, traceback):\n        print(f\"Releasing {self.name}\")\n \ndef use_resource():\n\twith MyResource(\"Resource A\") as res_a, MyResource(\"Resource B\") as res_b:\n    \traise Exception(\"An error occurred\")\n \ntry:\n\tuse_resource()\nexcept Exception as e:\n\tprint(e)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-2-1\"><strong>Question 2<\/strong><\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Meta(type):\n\tdef __new__(cls, name, bases, attrs):\n    \tattrs&#91;\"greeting\"] = \"Hello, Python Engineers!\"\n    \treturn super().__new__(cls, name, bases, attrs)\n \nclass MyClass(metaclass=Meta):\n\tpass\n \nobj = MyClass()\nprint(obj.greeting)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-3-1\"><strong>Question 3<\/strong><\/h3>\n\n\n\n<p>Find the issue in the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import threading\ncounter = 0\ndef increment():\n\tglobal counter\n\tfor _ in range(100000):\n    \tcounter += 1\nthreads = &#91;threading.Thread(target=increment) for _ in range(10)]\n&#91;thread.start() for thread in threads]\n&#91;thread.join() for thread in threads]\nprint(counter)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-4-1\"><strong>Question 4<\/strong><\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class DynamicAttributes:\n\tdef __getattr__(self, name):\n\t    return name.upper()\n\tdef __getattribute__(self, name):\n    \tif name.startswith(\"get_\"):\n        \treturn super().__getattribute__(name&#91;4:])\n    \traise AttributeError\ndyn = DynamicAttributes()\nprint(dyn.get_foo)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-5-1\"><strong>Question 5<\/strong><\/h3>\n\n\n\n<p>Create a distributed task queue using message brokers like RabbitMQ or Apache Kafka. The program should allow users to submit tasks, execute them in parallel on multiple workers and manage the results. Try to implement fault tolerance, retries and prioritization of tasks in your program.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-6-1\"><strong>Question 6<\/strong><\/h3>\n\n\n\n<p>What is wrong with the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># module_a.py\nimport module_b\nclass A:\n\tdef get_b_instance(self):\n    \treturn module_b.B()\n# module_b.py\nimport module_a\nclass B:\n\tdef get_a_instance(self):\n    \treturn module_a.A()\n# main.py\nimport module_a\na = module_a.A()\nb = a.get_b_instance()\nprint(b)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-7-1\"><strong>Question 7<\/strong><\/h3>\n\n\n\n<p>What will be the output of the below code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\nasync def display():\n\tawait asyncio.sleep(1)\n\treturn \"Hello World\"\nasync def main():\n\tresult = await display()\n    print(result)\nasyncio.run(main())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-8-1\"><strong>Question 8<\/strong><\/h3>\n\n\n\n<p>Develop a real-time chat application using WebSockets, asyncio and a suitable web framework like FastAPI or Django. Implement features like user authentication, chat rooms, and message broadcasting. Make sure the application can handle a large number of concurrent requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-9-1\"><strong>Question 9<\/strong><\/h3>\n\n\n\n<p>Optimize the following code snippet that uses Pandas DataFrame to calculate the mean price for each category:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\ndata = {\"category\": &#91;'A', 'B', 'A', 'A', 'B', 'B', 'A', 'B'],\n    \t\"price\": &#91;10, 15, 12, 9, 20, 18, 8, 25]}\ndf = pd.DataFrame(data)\nmean_prices = df.groupby(\"category\")&#91;\"price\"].mean()\nprint(mean_prices)<\/code><\/pre>\n\n\n\n<p>You can optimize data types and use method chaining to optimize the code above. Also, confirm which one of the built-in pandas functions are already being used in the above code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-question-10-1\"><strong>Question 10<\/strong><\/h3>\n\n\n\n<p>There is a function that performs an expensive computation. You need to implement a caching mechanism using decorators or the <em>functools.lru_cache<\/em> function. Analyze the performance improvements and share the trade-offs involved in using caching in this scenario.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we discussed Python coding challenges for evaluating engineering candidates. As the coding challenges depend on the experience level of the developers, we have divided the coding challenges into three sections: beginner, mid-level and expert. These coding challenges evaluate the skillset of Python engineers in different Python areas and test their capabilities to implement a real-world scenario in Python language. Of course, these questions serve just as a guideline and are not for definite evaluation. Evaluating the soft skills of Python engineers is as important as testing their technical skills, so a combination of both is required.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/codeinterview.io\/coding-tests\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"196\" src=\"https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-3-1.png\" alt=\"Test assessment tool\" class=\"wp-image-539\" srcset=\"https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-3-1.png 1024w, https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-3-1-300x57.png 300w, https:\/\/codeinterview.io\/blog\/wp-content\/uploads\/2023\/11\/CodeInterview-3-1-768x147.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n\n\n<p><em>Further reading: <\/em><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/codeinterview.io\/blog\/java-coding-interview-questions\/\">Java Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/reactjs-coding-interview-questions\/\">ReactJS Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/javascript-coding-interview-questions\/\">JavaScript Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/c-sharp-coding-interview-questions\/\">C# Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/c-plus-plus-coding-interview-questions\/\">C++ Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/php-coding-interview-questions\/\">PHP Coding Interview Questions<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeinterview.io\/blog\/advanced-coding-interview-questions\/\">73 Advanced Coding Interview Questions<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python is one of the important programming languages for backend software development. One of the reasons it is so popular is its use in machine learning and artificial intelligence. As Python is ideal for compute-intensive operations, that means it is best suited to all the use cases where computer vision, machine learning or deep learning [&hellip;]<\/p>\n","protected":false},"author":8,"featured_media":203,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[22],"tags":[14],"class_list":["post-202","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-interview-questions"],"_links":{"self":[{"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/posts\/202","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/comments?post=202"}],"version-history":[{"count":0,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/posts\/202\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/media\/203"}],"wp:attachment":[{"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/media?parent=202"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/categories?post=202"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeinterview.io\/blog\/wp-json\/wp\/v2\/tags?post=202"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}