problem solving questions python

Practice Python

follow us in feedly

Beginner Python exercises

  • Why Practice Python?
  • Why Chilis?
  • Resources for learners

All Exercises

problem solving questions python

All Solutions

  • 1: Character Input Solutions
  • 2: Odd Or Even Solutions
  • 3: List Less Than Ten Solutions
  • 4: Divisors Solutions
  • 5: List Overlap Solutions
  • 6: String Lists Solutions
  • 7: List Comprehensions Solutions
  • 8: Rock Paper Scissors Solutions
  • 9: Guessing Game One Solutions
  • 10: List Overlap Comprehensions Solutions
  • 11: Check Primality Functions Solutions
  • 12: List Ends Solutions
  • 13: Fibonacci Solutions
  • 14: List Remove Duplicates Solutions
  • 15: Reverse Word Order Solutions
  • 16: Password Generator Solutions
  • 17: Decode A Web Page Solutions
  • 18: Cows And Bulls Solutions
  • 19: Decode A Web Page Two Solutions
  • 20: Element Search Solutions
  • 21: Write To A File Solutions
  • 22: Read From File Solutions
  • 23: File Overlap Solutions
  • 24: Draw A Game Board Solutions
  • 25: Guessing Game Two Solutions
  • 26: Check Tic Tac Toe Solutions
  • 27: Tic Tac Toe Draw Solutions
  • 28: Max Of Three Solutions
  • 29: Tic Tac Toe Game Solutions
  • 30: Pick Word Solutions
  • 31: Guess Letters Solutions
  • 32: Hangman Solutions
  • 33: Birthday Dictionaries Solutions
  • 34: Birthday Json Solutions
  • 35: Birthday Months Solutions
  • 36: Birthday Plots Solutions
  • 37: Functions Refactor Solution
  • 38: f Strings Solution
  • 39: Character Input Datetime Solution
  • 40: Error Checking Solution

Top online courses in Programming Languages

10 Python Practice Exercises for Beginners with Solutions

Author's photo

  • python basics
  • get started with python
  • online practice

A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.

Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.

If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. Read about the course in the March 2023 episode of our series Python Course of the Month .

Take the course Python Practice: Word Games , and you gain experience working with string functions and text files through its 27 interactive exercises.  Its release announcement gives you more information and a feel for how it works.

Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work.

To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise.

Let’s get started!

Exercise 1: User Input and Conditional Statements

Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers.

Here, we start by using the built-in function input() , which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times.

Exercise 2: Lowercase and Uppercase Characters

Below is a string, text . It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result:

We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format.

Exercise 3: Building Triangles

Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10.

The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything.

Python Practice Exercises for Beginners

Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy!

Exercise 4: Call a Function From Another Function

Create two functions: print_five_times() and speak() . The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False ). If the repeat parameter is set to False , the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function.

This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program.

If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True .

Exercise 5: Looping and Conditional Statements

Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example:

Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list.

Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold . You may include this if you like.

Exercise 6: Nested Loops and Conditional Statements

Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you:

This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list . Then, we loop through every character in the current word and check if the current character is in the special_chars list.

This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word.

Exercise 7: Lists and Tuples

Create a function find_short_long_word(words_list) . The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list:

the function should return

Assume the input list is non-empty.

The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list.

We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple.

Exercise 8: Dictionaries

As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points.

Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple.

The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable.

Exercise 9: More Dictionaries

Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format:

For example, for input:

the output should be:

Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items.

We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format.

Exercise 10: String Encryption

Implement the Caesar cipher . This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet.

For example, consider the string 'word' . If we shift every letter down one position in the alphabet, we have 'xpse' . Shifting by 2 positions gives the string 'yqtf' . Start by defining a string with every letter in the alphabet:

Name your function cipher(word, shift) , which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter.

This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string.

This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError . When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge.

Do You Want More Python Practice Exercises?

We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games . These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these.

We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “ The 5 Best Python Books for Beginners .” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “ What’s the Best Way to Practice Python? ” If you keep up with your practice exercises, you’ll become a Python master in no time!

You may also like

problem solving questions python

How Do You Write a SELECT Statement in SQL?

problem solving questions python

What Is a Foreign Key in SQL?

problem solving questions python

Enumerate and Explain All the Basic Elements of an SQL Query

Top 50 Python Interview Questions With Example Answers

problem solving questions python

Guido van Rossum’s Python , initially released in 1991, has become one of the most popular programming languages, cherished by developers worldwide. In fact, Stack Overflow's 2022 Developer Survey stated that Python is the fourth most popular programming language, with respondents claiming they use it almost 50 percent of the time in their development work.

The language’s popularity largely stems from its requiring fewer lines of code compared to others like Java or C++ . Further, its readability and reliance on a syntax comparable to English make it among the easiest programming languages to learn. 

It’s also an open-source programming language, meaning anyone can download the source code for free, make changes, and distribute their own version. This works perfectly in tandem with Python’s development community, which connects developers and provides support for them when needed. 

This situation hasn’t escaped the notice of some of the biggest companies in the world (Intel, NASA, Facebook, etc.), who are all looking for Python developers . With that in mind, let’s dive into how you can prepare for Python interview questions and what those questions might look like.

More Interview Prep Top 20 Technical Interview Questions with Example Answers

How to Prepare for a Python Interview

Upon receiving an invitation for a Python developer job interview, refresh your programming knowledge and review your accomplishments in the field. The interview structure will generally involve a series of questions followed by live coding challenges to assess both technical prowess and soft skills like communication and teamwork .

If you’re a hiring manager or HR professional, you might want to think about approaching the 50 questions below from a few different angles. Perhaps you want the candidate to focus on explaining current projects they’re working on, what testing frameworks they prefer, or their ability to mentor others on the subject of Python.

Before we go through 50 example questions, here are some helpful tips for a developer to remember:

Python Interview Tips

  • Emphasize logical problem-solving when answering technical questions.
  • Answer questions with past case studies or examples you were involved in.
  • Highlight achievements or specific metrics you can point to.
  • In these examples, don’t be afraid to highlight what the challenges were and how you overcame them.

Brush Up Your Python Skills Python Attributes: Class vs. Instance Explained

50 Python Interview Questions

Here are 50 of the most likely Python interview questions, along with some viable responses and relevant code snippets. Do note that, depending on your experience and the company involved, the questions and answers can differ.

1. What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It boasts dynamic typing and automatic garbage collection, accommodating various programming paradigms such as structured, object-oriented, and functional approaches.

2. Explain the difference between Python 2 and Python 3.

Python 3 is the latest version and is not backward-compatible with Python 2. Instead, Python 3 focuses on code clarity, simplicity, and removing inconsistencies.

3. How do you install third-party packages in Python?

You can use the PIP package manager. For example, to install the R equests library, run  ‘pip install requests’ .

4. What are Python namespaces and scopes?

A namespace is a container that holds various identifiers (variables, functions, etc.). In contrast, scopes determine the visibility of these identifiers in different parts of your code.

5. Explain the Global Interpreter Lock (GIL).

The GIL is a mutual exclusion (mutex) that allows only one thread to execute in the interpreter at a time, limiting true parallelism in Python threads. In Python, performance remains consistent between single-threaded and multithreaded processes.

6. What is PEP 8?

PEP 8 is the Python Enhancement Proposal, written by Guido van Rossum, Barry Warsaw, and Nick Coghlan, that provides coding style guidelines for writing readable and consistent Python code.

7. How can you make comments in Python?

You can create single-line comments using the hash symbol: # . For multi-line comments, you can enclose the text in triple quotes like this: “ ” ”text” “ ” .

8. What are mutable and immutable data types?

Mutable data types can be changed after creation (e.g., lists ). In other words, the memory location of the object remains the same, but its internal state can change. By contrast, immutable data types cannot (e.g., strings, tuples ). Instead, you must create a new object with the desired changes. This immutability ensures that the original object maintains its integrity. 

9. How do you differentiate between a tuple and a list?

Lists are mutable data types that consume more memory and are suitable for operations like insertion and deletion, though iterations are time-consuming. Contrarily, tuples are immutable, consume less memory, and are efficient for element access with faster iterations.

10. What is the purpose of the ‘ if __name__ == “ __main__ ” : ’ statement?

This statement allows you to run certain code on the premise that the script is executed directly, not when it ’ s imported as a module.

11.  Explain the concept of a generator in Python.

Generators in Python define iterator implementation by yielding expressions in a function. They don’t implement ‘iter’ and ‘next()’ methods, thereby reducing various overheads.

12. How do you swap the values of two variables without using a temporary variable?

You can use tuple unpacking: `a, b = b, a` .

13. Explain the difference between ‘ == ’ and ‘ is ’ .

‘==’ checks if the values are equal; ‘is’ checks if the objects are the same.

14. How do you create an empty dictionary?

You can create an empty dictionary using the curly braces: ‘my_dict = {}’ .

15. How do you add an element to a list?

You can use the ‘append()’ method to add an element to the end of a list.

16. What is the difference between 'extend()' and 'append()' methods for lists?

‘extend()’ adds elements of an iterable to the end of the list, whereas  ‘append()’ adds a single element to the end.

17. What is the difference between a Dynamically Typed language and a Static Typed Language?

Typed languages are those where data are either known by the machine at compile-time or runtime. Dynamically typed languages don ’ t require predefined data for variables and determine types at runtime based on values.

18. Is indentation required in Python?

Indentation is absolutely essential in Python. It not only enhances code readability but also defines code blocks. Proper indentation is crucial for correct code execution; otherwise, you are left with a code that is not indented and difficult to read.

19. What is docstring in Python?

A docstring is used to associate documentation with Python modules, functions, classes, and methods. It provides a way to describe how to use these components.

20. What are the different built-in data types in Python?

Python offers various built-in data types, including numeric types (int, float, complex), sequence types (string, list, tuple, range), mapping types (dictionary), and set types.

21. How do you floor a number in Python?

Python ’ s math module provides the floor () function, which returns the largest integer not greater than the input. ceil() returns the smallest integer greater than or equal to the input.

22. What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new instance with copied values and is faster, whereas a deep copy stores values that are already copied and takes longer but is more comprehensive. 

23.  What is a ‘break, continue, and pass’ in Python?

A ‘break’ terminates the current loop or statement, ‘continue’ moves to the next iteration of the loop, and ‘pass’ is a placeholder for no operation within a statement block.

24. What are Decorators?

Decorators are the syntax constructs that modify functions in Python. They are often used to add functionality to existing functions without modifying their code directly.

25.  What are Iterators in Python?

Iterators are objects that allow iteration over elements, usually in collections like lists. They implement the ‘__iter__()’ and ‘next()’ methods for iteration.

26. Is Tuple Comprehension possible? If yes, how, and if not why?

Tuple comprehension is not possible in Python, unlike list comprehensions. It would result in a generator, not a tuple.

27.  What are *args and **kwargs?

‘*args’ and ‘**kwargs’ allow passing a variable number of arguments to functions. They help create flexible functions that can handle varying numbers of input parameters.

28.  What is Scope in Python?

Scope refers to where a variable can be accessed and modified. It includes local, global, module-level, and outermost scopes.

29. What is PIP?

PIP stands for Python Installer Package. It ’ s a command-line tool that is used to install Python packages from online repositories.

30. What is Polymorphism in Python?

Polymorphism is a concept that refers to the ability of objects to take on multiple forms. In Python, it allows objects of different classes to be treated as if they belong to a common superclass.

31. How do you debug a Python program?

The built-in ‘pdb’ module enables you to debug in Python. You can initiate debugging using this command: 

32. What is the difference between ‘xrange’ and ‘range’ functions?

‘Range()’ and ‘xrange()’ are both used for looping, but ‘xrange()’ was available in Python 2 and behaves similarly to ‘range()’ in Python 3. ‘Xrange()’ is generated only when required, leading to its designation as “ lazy evaluation. ”

33. What is Dictionary Comprehension?

Dictionary comprehension is a concise way to create dictionaries from iterable sources. It allows the creation of key-value pairs based on conditions and expressions.

34. What are Function Annotations in Python?

Function annotations add metadata to function parameters and return value. They are used to provide information about expected types or behavior.

35. What are Access Specifiers in Python?

Access specifiers (public, protected, and private) determine the visibility of class members. Public members are accessible everywhere, protected members are set within derived classes, and private members are only within the class.

36.  What are unit tests in Python?

Unit tests are performed on the smallest testable parts of software to ensure they function as intended. They validate the functionality of individual components.

37. Does Python support multiple inheritance?

Python supports multiple inheritances , allowing a class to inherit attributes and methods from multiple parent classes.

38. How do you handle exceptions in Python?

You can attempt to use except blocks to handle exceptions in Python. The code inside the try block is executed, and if an exception occurs, the code inside the except block is also executed.

39. What is the purpose of the ‘ finally ’ block?

The ‘finally’ block defines a block of code that will be executed regardless of whether an exception is raised or not.

40. What is the use of ‘ self ’ in Python class methods?

‘Self’ is used as the first parameter in class methods to refer to the class instance. It allows you to access the instance ’ s attributes and methods within the method.

41. What are Pickling and Unpickling Conceptually?

Pickling refers to converting Python objects into a byte stream, while unpickling is the opposite, reconstructing objects from that stream. These techniques are used for storing objects in files or databases .

42. Is Dictionary Lookup Faster than List Lookup? Why?

Dictionary lookup time is generally faster, with a complexity of O(1), due to their hash table implementation. In contrast, list lookup time is O(n), where the entire list may need to be iterated to find a value.

43. What Constitutes a Python Library?

A Python library is a collection of modules or packages that offer pre-implemented functions and classes. These libraries provide developers with ready-made solutions for common tasks.

44. Can you swap variables without using a third variable? How?

Yes, you can swap variables without a third variable by using tuple unpacking. The syntax is: a, b = b, a .

45. Explain the ‘enumerate()’ function in Python.

The ‘enumerate()’ function couples an iterable with its index. It simplifies loops where you need to access both elements and their corresponding positions.

46. What is the ‘ternary operator’ in Python?

A: The ternary operator, also known as the conditional operator, provides a way to write concise if-else statements in a single line. It takes the form ‘x’ if ‘condition else y’ , where x is the value if the condition is true, and y is the value if the condition is false. Although it can enhance code readability, it ’ s important to use the ternary operator carefully and prioritize code clarity over brevity.

47.  Can you clarify the distinctions between the ‘pop()’, ‘remove()’, and ‘del’ operations when working with Python lists?

A: The ‘pop()’ method removes an element at a specific index from the list. You can achieve this by providing the index as an argument. For example, ‘nums.pop(1)’ will remove the element at ‘index 1’ from the nums list.

remove() Function : The ‘remove()’ method is used to eliminate the first occurrence of a specific value in the list. By passing the value as an argument, the method will search for it and remove the first occurrence. For instance, if nums = [1, 1, 2, 2, 3, 3], then nums.remove(2) will remove the first two encountered in the list.

del Statement : The del statement allows you to delete an item at a particular index from the list. You can accomplish this by specifying the index using del keyword. For example, ‘del nums[0]’ will remove the item at index zero from the nums list.

48. What is the ‘join()’ method in Python Strings? How does it function?

A: The ‘join()’ method is a built-in string method designed to concatenate elements of an iterable, like a list, using a specified separator string. For example, suppose we have a list of characters `chars = ["H", "e", "l", "l", "o"]` . Using `"".join(chars)` connects these characters with an empty string separator, resulting in the string `"Hello"` .

49. How do you sort a list in reverse order using Python?

You can achieve this using the `sorted()` function with the `reverse` parameter set to `True` . Here ’ s an example:

The output will display the sorted list in descending order: [9, 7, 5, 3, 1]

In this example, the `sorted()` function returns a new sorted list, while the original list remains unchanged.

50. What Does Negative Indexing Mean?

Negative indexing means indexing starts from the other end of a sequence. In a list, the last element is at the -1 index, the second-to-last at -2, and so on. Negative indexing allows you to conveniently access elements from the end of a list without calculating the exact index.

Ace Your Next Interview How to Answer ‘Why Do You Want to Work Here?’

Prepare for Your Python Interview

So there you have it: A comprehensive list of possible Python questions you could be asked at an interview. Remember, this by no means covers everything, and there will be many questions similar to these where you need to demonstrate extensive coding examples. Still, this is a good starting point!

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Great Companies Need Great People. That's Where We Come In.

Pythonista Planet Logo

35 Python Programming Exercises and Solutions

To understand a programming language deeply, you need to practice what you’ve learned. If you’ve completed learning the syntax of Python programming language, it is the right time to do some practice programs.

In this article, I’ll list down some problems that I’ve done and the answer code for each exercise. Analyze each problem and try to solve it by yourself. If you have any doubts, you can check the code that I’ve provided below. I’ve also attached the corresponding outputs.

1. Python program to check whether the given number is even or not.

2. python program to convert the temperature in degree centigrade to fahrenheit, 3. python program to find the area of a triangle whose sides are given, 4. python program to find out the average of a set of integers, 5. python program to find the product of a set of real numbers, 6. python program to find the circumference and area of a circle with a given radius, 7. python program to check whether the given integer is a multiple of 5, 8. python program to check whether the given integer is a multiple of both 5 and 7, 9. python program to find the average of 10 numbers using while loop, 10. python program to display the given integer in a reverse manner, 11. python program to find the geometric mean of n numbers, 12. python program to find the sum of the digits of an integer using a while loop, 13. python program to display all the multiples of 3 within the range 10 to 50, 14. python program to display all integers within the range 100-200 whose sum of digits is an even number, 15. python program to check whether the given integer is a prime number or not, 16. python program to generate the prime numbers from 1 to n, 17. python program to find the roots of a quadratic equation, 18. python program to print the numbers from a given number n till 0 using recursion, 19. python program to find the factorial of a number using recursion, 20. python program to display the sum of n numbers using a list, 21. python program to implement linear search, 22. python program to implement binary search, 23. python program to find the odd numbers in an array, 24. python program to find the largest number in a list without using built-in functions, 25. python program to insert a number to any position in a list, 26. python program to delete an element from a list by index, 27. python program to check whether a string is palindrome or not, 28. python program to implement matrix addition, 29. python program to implement matrix multiplication, 30. python program to check leap year, 31. python program to find the nth term in a fibonacci series using recursion, 32. python program to print fibonacci series using iteration, 33. python program to print all the items in a dictionary, 34. python program to implement a calculator to do basic operations, 35. python program to draw a circle of squares using turtle.

problem solving questions python

For practicing more such exercises, I suggest you go to  hackerrank.com  and sign up. You’ll be able to practice Python there very effectively.

Once you become comfortable solving coding challenges, it’s time to move on and build something cool with your skills. If you know Python but haven’t built an app before, I suggest you check out my  Create Desktop Apps Using Python & Tkinter  course. This interactive course will walk you through from scratch to building clickable apps and games using Python.

I hope these exercises were helpful to you. If you have any doubts, feel free to let me know in the comments.

Happy coding.

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

11 thoughts on “ 35 Python Programming Exercises and Solutions ”

I don’t mean to nitpick and I don’t want this published but you might want to check code for #16. 4 is not a prime number.

Thanks man for pointing out the mistake. I’ve updated the code.

# 8. Python program to check whether the given integer is a multiple of both 5 and 7:

You can only check if integer is a multiple of 35. It always works the same – just multiply all the numbers you need to check for multiplicity.

For reverse the given integer n=int(input(“enter the no:”)) n=str(n) n=int(n[::-1]) print(n)

very good, tnks

Please who can help me with this question asap

A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs $0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill (including the 911 charge) is subject to 5 percent sales tax.

We are so to run the code in phyton

this is best app

Hello Ashwin, Thanks for sharing a Python practice

May be in a better way for reverse.

#”’ Reverse of a string

v_str = str ( input(‘ Enter a valid string or number :- ‘) ) v_rev_str=” for v_d in v_str: v_rev_str = v_d + v_rev_str

print( ‘reverse of th input string / number :- ‘, v_str ,’is :- ‘, v_rev_str.capitalize() )

#Reverse of a string ”’

Problem 15. When searching for prime numbers, the maximum search range only needs to be sqrt(n). You needlessly continue the search up to //n. Additionally, you check all even numbers. As long as you declare 2 to be prime, the rest of the search can start at 3 and check every other number. Another big efficiency improvement.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name and email in this browser for the next time I comment.

Recent Posts

Introduction to Modular Programming with Flask

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules. In this tutorial, let's understand what modular...

Introduction to ORM with Flask-SQLAlchemy

While Flask provides the essentials to get a web application up and running, it doesn't force anything upon the developer. This means that many features aren't included in the core framework....

problem solving questions python

Python Wife Logo

  • Computer Vision
  • Problem Solving in Python
  • Intro to DS and Algo
  • Analysis of Algorithm
  • Dictionaries
  • Linked Lists
  • Doubly Linked Lists
  • Circular Singly Linked List
  • Circular Doubly Linked List
  • Tree/Binary Tree
  • Binary Search Tree
  • Binary Heap
  • Sorting Algorithms
  • Searching Algorithms
  • Single-Source Shortest Path
  • Topological Sort
  • Dijkstra’s
  • Bellman-Ford’s
  • All Pair Shortest Path
  • Minimum Spanning Tree
  • Kruskal & Prim’s

Problem-solving is the process of identifying a problem, creating an algorithm to solve the given problem, and finally implementing the algorithm to develop a computer program .

An algorithm is a process or set of rules to be followed while performing calculations or other problem-solving operations. It is simply a set of steps to accomplish a certain task.

In this article, we will discuss 5 major steps for efficient problem-solving. These steps are:

  • Understanding the Problem
  • Exploring Examples
  • Breaking the Problem Down
  • Solving or Simplification
  • Looking back and Refactoring

While understanding the problem, we first need to closely examine the language of the question and then proceed further. The following questions can be helpful while understanding the given problem at hand.

  • Can the problem be restated in our own words?
  • What are the inputs that are needed for the problem?
  • What are the outputs that come from the problem?
  • Can the outputs be determined from the inputs? In other words, do we have enough information to solve the given problem?
  • What should the important pieces of data be labeled?

Example : Write a function that takes two numbers and returns their sum.

  • Implement addition
  • Integer, Float, etc.

Once we have understood the given problem, we can look up various examples related to it. The examples should cover all situations that can be encountered while the implementation.

  • Start with simple examples.
  • Progress to more complex examples.
  • Explore examples with empty inputs.
  • Explore examples with invalid inputs.

Example : Write a function that takes a string as input and returns the count of each character

After exploring examples related to the problem, we need to break down the given problem. Before implementation, we write out the steps that need to be taken to solve the question.

Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead.

The steps to simplify a problem are as follows:

  • Find the core difficulty
  • Temporarily ignore the difficulty
  • Write a simplified solution
  • Then incorporate that difficulty

Since we have completed the implementation of the problem, we now look back at the code and refactor it if required. It is an important step to refactor the code so as to improve efficiency.

The following questions can be helpful while looking back at the code and refactoring:

  • Can we check the result?
  • Can we derive the result differently?
  • Can we understand it at a glance?
  • Can we use the result or mehtod for some other problem?
  • Can you improve the performance of the solution?
  • How do other people solve the problem?

Trending Posts You Might Like

  • File Upload / Download with Streamlit
  • Dijkstra’s Algorithm in Python
  • Seaborn with STREAMLIT
  • Greedy Algorithms in Python

Author : Bhavya

Download Interview guide PDF

  • Python Interview Questions

Download PDF

Introduction to python:.

Python was developed by Guido van Rossum and was released first on February 20, 1991. It is one of the most widely used and loved programming languages and is interpreted in nature thereby providing flexibility in incorporating dynamic semantics. It is also a free and open-source language with very simple and clean syntax. This makes it easy for developers to learn Python . Python also supports object-oriented programming and is most commonly used to perform general-purpose programming. 

Due to its simplistic nature and the ability to achieve multiple functionalities in fewer lines of code, python’s popularity is growing tremendously. Python is also used in Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and various other domains due to its ability to support powerful computations using powerful libraries. Due to this, there is a huge demand for Python developers in India and across the world. Companies are willing to offer amazing perks and benefits to these developers. 

In this article, we will see the most commonly asked Python interview questions and answers which will help you excel and bag amazing job offers.

We have classified them into the following sections:

Python Interview Questions for Freshers

Python interview questions for experienced, python oops interview questions, python pandas interview questions, numpy interview questions, python libraries interview questions, python programming examples, 1. what is python what are the benefits of using python.

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

Benefits of using Python:

  • Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse.
  • Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

2. What is a dynamically typed language?

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.

Type-checking can be done at two stages -

  • Static - Data Types are checked before execution.
  • Dynamic - Data Types are checked during execution.

Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

problem solving questions python

3. What is an Interpreted language?

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

4. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal . A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

5. What is Scope in Python?

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

  • A local scope refers to the local objects available in the current function.
  • A global scope refers to the objects available throughout the code execution since their inception.
  • A module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Note: Local scope objects can be synced with global scope objects using keywords such as global .

  • Software Dev
  • Data Science

6. What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both s equence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types . Lists are represented with square brackets ['sara', 6, 0.19] , while tuples are represented with parantheses ('ansh', 5, 0.97) . But what is the real difference between the two? The key difference between the two is that while lists are mutable , tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:

7. What are the common built-in data types in Python?

There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories-

  • None Type: None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.
  • Numeric Types: There are three distinct numeric types - integers, floating-point numbers , and complex numbers . Additionally, booleans are a sub-type of integers.

Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.

  • Sequence Types: According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.

Note: The standard library also includes additional types for processing: 1. Binary data such as bytearray bytes memoryview , and 2. Text strings such as str .

  • Mapping Types:

A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary .

  • Set Types: Currently, Python has two built-in set types - set and frozenset . set type is mutable and supports methods like add() and remove() . frozenset type is immutable and can't be modified after creation.

Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set.

  • Modules: Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access : mymod.myobj , where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__ , but direct assignment to this module is neither possible nor recommended.
  • Callable Types: Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions , and some other built-in functions, methods and classes . Refer to the documentation at docs.python.org for a detailed view of the callable types .

8. What is pass in Python?

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

9. What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -

  • Simplicity : Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.
  • Maintainability : Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.
  • Reusability : Functions defined in a module can be easily reused by other parts of the application.
  • Scoping : Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules , in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar .

Packages allow for hierarchial structuring of the module namespace using dot notation . As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.

10. What are global, protected and private attributes in Python?

  • Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
  • Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.
  • Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

11. What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

12. What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

13. What is break, continue and pass in Python?

14. what are unit tests in python.

  • Unit test is a unit testing framework of Python.
  • Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.
  • This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

15. What is docstring in Python?

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.

16. What is slicing in Python?

  • As the name suggests, ‘slicing’ is taking parts of.
  • Syntax for slicing is [start : stop : step]
  • start is the starting index from where to slice a list or tuple
  • stop is the ending index or where to sop.
  • step is the number of steps to jump.
  • Default value for start is 0, stop is number of items, step is 1.
  • Slicing can be done on strings, arrays, lists , and tuples .

17. Explain how can you make a Python Script executable on Unix?

  • Script file must begin with #!/usr/bin/env python

18. What is the difference between Python Arrays and lists?

  • Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
  • Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

1. How is memory managed in Python?

  • Memory management in Python is handled by the Python Memory Manager . The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space.
  • Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

problem solving questions python

2. What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that are being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace.

problem solving questions python

3. What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are:

  • Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10() , acos() , exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp() .
  • Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities.

This behavior can be overridden using the global keyword inside the function, as shown in the following example:

4. What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example:

The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function , i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

5. What are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists , dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial:

  • Performing mathematical operations on the entire list
  • Performing conditional filtering operations on the entire list
  • Combining multiple lists into one

Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one. 

  • Flattening a multi-dimensional list

A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements. 

Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python.

6. What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

  • Assigning lambda functions to a variable:
  • Wrapping lambda functions inside another function:

7. How do you copy an object in Python?

In Python, the assignment statement ( = operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module -

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied. Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

8. What is the difference between xrange and range in Python?

xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list , whereas, xrange() returns an xrange object .

So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object-type generator and has been termed as " yielding ".

Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).

Note : xrange has been deprecated as of Python 3.x . Now range does exactly the same as what xrange used to do in Python 2.x , since it was way better to use xrange() than the original range() function in Python 2.x.

9. What is pickling and unpickling?

Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here, the pickle module comes into play.

  • Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions.
  • The function used for the above process is pickle.dump() .

Unpickling:

  • Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory.
  • The function used for the above process is pickle.load() .

Note: Python has another, more primitive, serialization module called marshall , which exists primarily to support .pyc files in Python and differs significantly from the pickle .

problem solving questions python

10. What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object. Let's try and build a generator for fibonacci numbers -

11. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

12. What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console. dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

  • For Modules/Library objects, it returns a list of all attributes, contained in that module.
  • For Class Objects, it returns a list of all valid attributes and base attributes.
  • With no arguments passed, it returns a list of attributes in the current scope.

13. What is the difference between .py and .pyc files?

  • .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.
  • Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.
  • Having .pyc file saves you the compilation time.

14. How Python is interpreted?

  • Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
  • Source code is a file with .py extension.
  • Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”.
  • .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.

15. How are arguments passed by value or by reference in python?

  • Pass by value : Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference : Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.

In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

16. What are iterators in Python?

  • An iterator is an object.
  • It remembers its state i.e., where it is during iteration (see code below to see how)
  • __iter__() method initializes an iterator.
  • It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.
  • It is also self-iterable.
  • Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

17. Explain how to delete a file in Python?

Use command os.remove(file_name)

18. Explain split() and join() functions in Python?

  • You can use split() function to split a string based on a delimiter to a list of strings.
  • You can use join() function to join a list of strings based on a delimiter to give a single string.

19. What does *args and **kwargs mean?

  • *args is a special syntax used in the function definition to pass variable-length arguments.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
  • **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable that has a name when passed to a function.
  • It is actually a dictionary of the variable names and its value.

20. What are negative indexes and why are they used?

  • Negative indexes are the indexes from the end of the list or tuple or string.
  • Arr[-1] means the last element of array Arr[]

1. How do you create a class in Python?

To create a class in python, we use the keyword “class” as shown in the example below:

To instantiate or create an object from the class created above, we do the following:

To access the name attribute, we just call the attribute using the dot operator as shown below:

To create methods inside the class, we include the methods under the scope of the class as shown below:

The self parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below:

The overall program would look like this:

2. How does inheritance work in python? Explain it with an example.

Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code reusability and helps the developer to maintain applications without redundant code. The class inheriting from another class is a child class or also called a derived class. The class from which a child class derives the members are called parent class or superclass.

Python supports different kinds of inheritance, they are:

  • Single Inheritance : Child class derives members of one parent class.

problem solving questions python

  • Multi-level Inheritance: The members of the parent class, A, are inherited by child class which is then inherited by another child class, B. The features of the base class and the derived class are further inherited into the new derived class, C. Here, A is the grandfather class of class C.

problem solving questions python

  • Multiple Inheritance: This is achieved when one child class derives members from more than one parent class. All features of parent classes are inherited in the child class.

problem solving questions python

  • Hierarchical Inheritance: When a parent class is derived by more than one child class, it is called hierarchical inheritance.

problem solving questions python

3. How do you access parent members in the child class?

Following are the ways using which you can access parent class members within a child class:

  • By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below:
  • By using super(): The parent class members can be accessed in child class using the super keyword.

4. Are access specifiers used in python?

Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.

5. Is it possible to call parent class without its instance creation?

Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.

6. How is an empty class created in python?

An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside the class. For example-

Output: Name created = Interviewbit

7. Differentiate between new and override modifiers.

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

8. Why is finalize used?

Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.

9. What is init method in python?

The init method works similarly to the constructors in Java. The method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation. For example:

10. How will you check if a class is a child of another class?

This is done by using a method called issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly. For example:

  • We can check if an object is an instance of a class by making use of isinstance() method:

1. What do you know about pandas?

  • Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis.
  • Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.

2. Define pandas dataframe.

A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns. The syntax for creating dataframe:

  • data - Represents various forms like series, map, ndarray, lists, dict etc.
  • index - Optional argument that represents an index to row labels.
  • columns - Optional argument for column labels.
  • Dtype - the data type of each column. Again optional.

3. How will you combine different pandas dataframes?

The dataframes can be combines using the below approaches:

  • append() method : This is used to stack the dataframes horizontally. Syntax:
  • concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the same columns and similar fields. Syntax:
  • join() method: This is used for extracting data from various dataframes having one or more common columns.

4. Can you create a series from the dictionary object in pandas?

One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below:

If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary.

5. How will you identify and deal with missing values in a dataframe?

We can identify if a dataframe has missing values by using the isnull() and isna() methods.

We can handle missing values by either replacing the values in the column with 0 as follows:

Or by replacing it with the mean value of the column

6. What do you understand by reindexing in pandas?

Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.

7. How to add new column to pandas dataframe?

A new column can be added to a pandas dataframe as follows:

8. How will you delete indices, rows and columns from a dataframe?

To delete an Index:

  • Execute del df.index.name for removing the index by name.
  • Alternatively, the df.index.name can be assigned to None.
  • For example, if you have the below dataframe:
  • To drop the index name “Names”:

To delete row/column from dataframe:

  • drop() method is used to delete row/column from dataframe.
  • The axis argument is passed to the drop method where if the value is 0, it indicates to drop/delete a row and if 1 it has to drop the column.
  • Additionally, we can try to delete the rows/columns in place by setting the value of inplace to True. This makes sure that the job is done without the need for reassignment.
  • The duplicate values from the row/column can be deleted by using the drop_duplicates() method.

problem solving questions python

9. Can you get items of series A that are not available in another series B?

This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below.

10. How will you get the items that are not common to both the given series A and B?

We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection.

problem solving questions python

The following code demonstrates this:

11. While importing data from different sources, can the pandas library recognize dates?

Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data from the sources. Consider an example where we read data from a CSV file, we may encounter different date-time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below:

1. What do you understand by NumPy?

NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its flexibility to perform various operations like trigonometric operations, algebraic and statistical computations, it is most commonly used in performing scientific computations and various broadcasting functions. The following image shows the applications of NumPy:

problem solving questions python

2. How are NumPy arrays advantageous over python lists?

  • The list data structure of python is very highly efficient and is capable of performing various functions. But, they have severe limitations when it comes to the computation of vectorized operations which deals with element-wise multiplication and addition. The python lists also require the information regarding the type of every element which results in overhead as type dispatching code gets executes every time any operation is performed on any element. This is where the NumPy arrays come into the picture as all the limitations of python lists are handled in NumPy arrays.
  • Additionally, as the size of the NumPy arrays increases, NumPy becomes around 30x times faster than the Python List. This is because the Numpy arrays are densely packed in the memory due to their homogenous nature. This ensures the memory free up is also faster.

3. What are the steps to create 1D, 2D and 3D arrays?

  • 1D array creation:
  • 2D array creation:
  • 3D array creation:
  • ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the creation of a 6D array:

4. You are given a numpy array and a new column as inputs. How will you delete the second column and replace the column with a new column value?

Example: Given array:

New Column values:

5. How will you efficiently load data from a text file?

We can use the method numpy.loadtxt() which can automatically read the file’s header and footer lines and the comments if any.

This method is highly efficient and even if this method feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used.

Following are the file formats that are supported:

  • Text files: These files are generally very slow, huge but portable and are human-readable.
  • Raw binary: This file does not have any metadata and is not portable. But they are fast.
  • Pickle: These are borderline slow and portable but depends on the NumPy versions.
  • HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables and h5py format.
  • .npy: This is NumPy's native binary data format which is extremely simple, efficient and portable.

6. How will you read CSV data into an array in NumPy?

This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.

7. How will you sort the array based on the Nth column?

For example, consider an array arr.

Let us try to sort the rows by the 2nd column so that we get:

We can do this by using the sort() method in numpy as:

We can also perform sorting and that too inplace sorting by doing:

8. How will you find the nearest value in a given numpy array?

We can use the argmin() method of numpy as shown below:

9. How will you reverse the numpy array using one line of code?

This can be done as shown in the following:

where arr = original given array, reverse_array is the resultant after reversing all elements in the input.

10. How will you find the shape of any given NumPy array?

We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms of row count and column count of the array.

1. Differentiate between a package and a module in python.

The module is a single python file. A module can import other modules (other python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside.

A python module is created by saving a file with the extension of .py . This file will have classes and functions that are reusable in the code as well as across modules.

A python package is created by following the below steps:

  • Create a directory and give a valid name that represents its operation.
  • Place modules of one kind in this directory.
  • Create __init__.py file in this directory. This lets python know the directory we created is a package. The contents of this package can be imported across different modules in other packages to reuse the functionality.

2. What are some of the most commonly used built-in modules in Python?

Python modules are the files having python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are:

3. What are lambda functions?

Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as:

4. How can you generate random numbers?

Python provides a module called random using which we can generate random numbers.

  • The random() method generates float values lying between 0 and 1 randomly.
  • To generate customised random numbers between specified ranges, we can use the randrange() method Syntax: randrange(beginning, end, step) For example:

5. Can you easily check if all characters in the given string is alphanumeric?

This can be easily done by making use of the isalnum() method that returns true in case the string has only alphanumeric characters.

For Example -

Another way is to use match() method from the re (regex) module as shown:

6. What are the differences between pickling and unpickling?

Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary form data to python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as python objects upon which processing can be done in python.

Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.

problem solving questions python

7. Define GIL.

GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). The following diagram represents how GIL works.

problem solving questions python

Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the second thread. The process repeats and the GIL are used by different threads alternatively until the threads have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes execution only when it acquires the lock.

8. Define PYTHONPATH.

It is an environment variable used for incorporating additional directories during the import of a module or a package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded.

9. Define PIP.

PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is:

10. Are there any tools for identifying bugs and performing static analysis in python?

Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module’s coding standards and supports different plugins to enable custom features to meet this requirement.

11. Differentiate between deep and shallow copies.

  • Shallow copy does the task of creating new objects storing references of original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects.
  • Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively.

12. What is main function in python? How do you invoke it?

In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function and by using the __name__ property of python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below:

1. Write python function which takes a variable number of arguments.

A function that takes variable arguments is called a function prototype. Syntax:

For example:

The * in the function argument represents variable arguments in the function.

2. WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.

You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True.

3. Write a program for counting the number of every character of a given text file.

The idea is to use collections and pprint module as shown below:

4. Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N.

This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair.

5. Write a Program to add two integers >0 without using the plus operator.

We can use bitwise operators to achieve this.

6. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:

By solving the equation, we get:

7. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.

We can use the re module of python to perform regex pattern comparison here.

8. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.

We can again use the re module to convert the date string as shown below:

You can also use the datetime module as shown below:

9. Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionary

We can use the Counter method from the collections module

10. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive?

We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source.

Conclusion:

In this article, we have seen commonly asked interview questions for a python developer. These questions along with regular problem practice sessions will help you crack any python based interviews. Over the years, python has gained a lot of popularity amongst the developer’s community due to its simplicity and ability to support powerful computations. Due to this, the demand for good python developers is ever-growing. Nevertheless, to mention, the perks of being a python developer are really good. Along with theoretical knowledge in python, there is an emphasis on the ability to write good-quality code as well. So, keep learning and keep practising problems and without a doubt, you can crack any interviews.

Looking to get certified in Python? Check out Scaler Topic's Free Python course with certification. 

Important Resources:

  • Python Interview Questions for Data Science
  • Python Basic Programs
  • Python Commands
  • Python Developer Resume
  • Python Projects
  • Difference Between Python 2 and 3
  • Python Frameworks
  • Python Documentation
  • Numpy Tutorial
  • Python Vs R
  • Python Vs Javascript
  • Difference Between C and Python
  • Python Vs Java
  • Features of Python
  • Golang vs Python
  • Python Developer Skills
  • Online Python Compiler

Coding Problems

Suppose list1 = [3,4,5,2,1,0], what is list1 after list1.pop(1)?

What is the output of the following statement "Hello World"[::-1] ?

What is the difference between lists and tuples?

Let func = lambda a, b : (a ** b) , what is the output of func(float(10),20) ?

Which statement is false for __init__?

Which of the following is the function responsible for pickling?

Which of the following is a protected attribute?

Which of the following is untrue for Python namespaces?

Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'] , what is the output of ["".join([i, j]) for i, j in zip(list1, list2)] ?

time.time() in Python returns?

What is the output of the following program?

What is the output of the below program?

Which among the below options will correct the below error obtained while reading “sample_file.csv” in pandas?

Which among the following options helps us to check whether a pandas dataframe is empty?

How will you find the location of numbers which are multiples of 5 in a series?

What is the output of the below code?

Which among the below options picks out negative numbers from the given list.

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

  • Trending Now
  • Data Structures
  • System Design
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • Data Science Using Python
  • Web Development
  • Web Browser
  • Design Patterns
  • Software Development
  • Product Management
  • Programming

Improve your Coding Skills with Practice

 alt=

IMAGES

  1. Problem Solving using Python

    problem solving questions python

  2. Solving an Optimization Problem with Python

    problem solving questions python

  3. algorithmic problem solving in python

    problem solving questions python

  4. GitHub

    problem solving questions python

  5. #6 Python Problem Solving

    problem solving questions python

  6. Python Practice Questions

    problem solving questions python

VIDEO

  1. GE3151 Problem Solving and Python Programming Important 2 Marks Questions for Semester April 2023

  2. Problem solving with recursion in python

  3. Solving mathematical problems using Python

  4. Python Problem Solving Class 2 (List)

  5. Problem Solving On List Python

  6. Python Problem solving Question #technologies #leetcode #hackerrank #python3 #problemsolving

COMMENTS

  1. Python Exercises, Practice, Challenges

    Each exercise has 10-20 Questions. The solution is provided for every question. Practice each Exercise in Online Code Editor. These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

  2. Python Practice Problems: Get Ready for Your Next Interview

    Python Practice Problem 2: Caesar Cipher. The next question is a two-parter. You'll code up a function to compute a Caesar cipher on text input. ... Your final Python practice problem is to solve a sudoku puzzle! Finding a fast and memory-efficient solution to this problem can be quite a challenge. The solution you'll examine has been ...

  3. Python Practice for Beginners: 15 Hands-On Problems

    Python Practice Problem 1: Average Expenses for Each Semester. John has a list of his monthly expenses from last year: He wants to know his average expenses for each semester. Using a for loop, calculate John's average expenses for the first semester (January to June) and the second semester (July to December).

  4. Python Exercise with Practice Questions and Solutions

    Python exercises, practice questions, and solutions. A detailed guide with 50 plus Python practice exercises for Python developer. ... Python Program for N Queen Problem >> More Programs on Python DSA. ... In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and programming logic ...

  5. Solve Python

    Easy Python (Basic) Max Score: 10 Success Rate: 89.71%. Solve Challenge. Arithmetic Operators. Easy Python (Basic) Max Score: 10 Success Rate: 97.41%. Solve Challenge. ... Problem Solving (Basic) Python (Basic) Problem Solving (Advanced) Python (Intermediate) Difficulty. Easy. Medium. Hard. Subdomains. Introduction. Basic Data Types. Strings ...

  6. Exercises and Solutions

    Beginner Python exercises. Home; Why Practice Python? Why Chilis? Resources for learners; All Exercises. 1: Character Input 2: Odd Or Even 3: List Less Than Ten 4: Divisors 5: List Overlap 6: String Lists 7: List Comprehensions 8: Rock Paper Scissors 9: Guessing Game One 10: List Overlap Comprehensions 11: Check Primality Functions 12: List Ends 13: Fibonacci 14: List Remove Duplicates

  7. 2,500+ Python Practice Challenges // Edabit

    There is a single operator in Python, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples remainder(1, 3) 1 remainder(3, 4) 3 remainder(5, 5) 0 remainde …

  8. 10 Python Practice Exercises for Beginners with Solutions

    Exercise 1: User Input and Conditional Statements. Write a program that asks the user for a number then prints the following sentence that number of times: 'I am back to check on my skills!'. If the number is greater than 10, print this sentence instead: 'Python conditions and loops are a piece of cake.'.

  9. Python Online Practice: 93 Unique Coding Exercises

    Research shows that hands-on practice is the most effective way to learn, * and luckily there are so many different ways to practice that you're bound to find one that works best for you. In this post, we'll share 93 ways to practice Python online by writing actual code, broken down into different practice methods.

  10. Python Basic Exercise for Beginners with Solutions

    What questions are included in this Python fundamental exercise? The exercise contains 15 programs to solve. The hint and solution is provided for each question. I have added tips and required learning resources for each question, which will help you solve the exercise. When you complete each question, you get more familiar with the basics of ...

  11. The 23 Top Python Interview Questions & Answers

    This question is a simple math problem. Find the sum of all elements in the list. ... cheat sheets, and mock questions, and solve coding challenges to pass the interview stage. You need to prepare for general Python questions on native functionality, job-specific questions (data engineer, data scientist, backend developer), and timed code-based ...

  12. Python Functions Exercise with Solution [10 Programs]

    Exercise 1: Create a function in Python. Exercise 2: Create a function with variable length of arguments. Exercise 3: Return multiple values from a function. Exercise 4: Create a function with a default argument. Exercise 5: Create an inner function to calculate the addition in the following way. Exercise 6: Create a recursive function.

  13. Python Exercises, Practice, Solution

    Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. Python supports multiple programming paradigms, including object-oriented ...

  14. Top 50 Python Interview Questions With Example Answers

    Emphasize logical problem-solving when answering technical questions. Answer questions with past case studies or examples you were involved in. ... Here are 50 of the most likely Python interview questions, along with some viable responses and relevant code snippets. Do note that, depending on your experience and the company involved, the ...

  15. PDF Python Practice Book

    Problem 2: Create a python script to print hello, world!four times. Problem 3: Create a python script with the following text and see the output. ... more of it as we get into solving more serious problems. Built-in Functions Python provides some useful built-in functions. >>> min(2,3) 2 >>> max(3,4) 4 The built-in function lencomputes length ...

  16. 35 Python Programming Exercises and Solutions

    In this article, I'll list down some problems that I've done and the answer code for each exercise. Analyze each problem and try to solve it by yourself. If you have any doubts, you can check the code that I've provided below. I've also attached the corresponding outputs. 1. Python program to check whether the given number is even or not.

  17. Python Basics: Problem Solving with Code

    Module 3 • 4 hours to complete. Everything you've learned in this course about Python is just basic building blocks that programmers use to build bigger building blocks of their own. In this module, we'll do precisely that, turning Python into a little language for drawing pictures, a DIY MS Paint. What's included.

  18. Cracking Coding Interviews: Python Solutions for Common Problems

    To solve this problem using backtracking, you can place queens one by one in different columns and check for clashes at each step. If a queen can be safely placed in the current row and column ...

  19. Problem Solving in Python

    Step 4 - Solving or Simplification. Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead. The steps to simplify a problem are as follows: Find the core difficulty.

  20. Python Practice Questions for Coding Interviews

    When you solve questions, it develops problem-solving skills. If you are learning Python and have completed the fundamentals of Python, your next step should be to solve some Python practice questions as a beginner. So, in this article, I will take you through some Python practice questions for coding interviews every beginner should try. ...

  21. Python for loop and if else Exercises [10 Exercise Programs]

    This Python loop exercise include the following: -. It contains 18 programs to solve using if-else statements and looping techniques.; Solutions are provided for all questions and tested on Python 3. This exercise is nothing but an assignment to solve, where you can solve and practice different loop programs and challenges.

  22. Top Python Interview Questions and Answers (2024)

    Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants: 7. ... we will see the most commonly asked Python interview questions and answers which will help you excel and bag amazing job offers. ... These questions along with regular problem practice sessions will help you crack any python based interviews. Over the ...

  23. GeeksforGeeks

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

  24. python

    I am trying to solve a problem with an unbalanced data set. I have two classes, one is for patients with risk 1, the other for patients without risk 0. I have a much larger number of patients without risk. For analysis, I used methods such as RandomOverSampler, SMOTE, ADASYN, Borderline-SMOTE, RandomUnderSampler, TomekLinks, NearMiss, SMOTEENN ...