• How it works
  • Homework answers

Physics help

Python Answers

Questions: 5 831

Answers by our Experts: 5 728

Ask Your question

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Search & Filtering

Create a method named check_angles. The sum of a triangle's three angles should return True if the sum is equal to 180, and False otherwise. The method should print whether the angles belong to a triangle or not.

11.1  Write methods to verify if the triangle is an acute triangle or obtuse triangle.

11.2  Create an instance of the triangle class and call all the defined methods.

11.3  Create three child classes of triangle class - isosceles_triangle, right_triangle and equilateral_triangle.

11.4  Define methods which check for their properties.

Create an empty dictionary called Car_0 . Then fill the dictionary with Keys : color , speed , X_position and Y_position.

car_0 = {'x_position': 10, 'y_position': 72, 'speed': 'medium'} .

a) If the speed is slow the coordinates of the X_pos get incremented by 2.

b) If the speed is Medium the coordinates of the X_pos gets incremented by 9

c) Now if the speed is Fast the coordinates of the X_pos gets incremented by 22.

Print the modified dictionary.

Create a simple Card game in which there are 8 cards which are randomly chosen from a deck. The first card is shown face up. The game asks the player to predict whether the next card in the selection will have a higher or lower value than the currently showing card.

For example, say the card that’s shown is a 3. The player chooses “higher,” and the next card is shown. If that card has a higher value, the player is correct. In this example, if the player had chosen “lower,” they would have been incorrect. If the player guesses correctly, they get 20 points. If they choose incorrectly, they lose 15 points. If the next card to be turned over has the same value as the previous card, the player is incorrect.

Consider an ongoing test cricket series. Following are the names of the players and their scores in the test1 and 2.

Test Match 1 :

Dhoni : 56 , Balaji : 94

Test Match 2 :

Balaji : 80 , Dravid : 105

Calculate the highest number of runs scored by an individual cricketer in both of the matches. Create a python function Max_Score (M) that reads a dictionary M that recognizes the player with the highest total score. This function will return ( Top player , Total Score ) . You can consider the Top player as String who is the highest scorer and Top score as Integer .

Input : Max_Score({‘test1’:{‘Dhoni’:56, ‘Balaji : 85}, ‘test2’:{‘Dhoni’ 87, ‘Balaji’’:200}}) Output : (‘Balaji ‘ , 200)

Write a Python program to demonstrate Polymorphism.

1. Class  Vehicle  with a parameterized function  Fare,  that takes input value as fare and

returns it to calling Objects.

2. Create five separate variables  Bus, Car, Train, Truck and Ship  that call the  Fare

3. Use a third variable  TotalFare  to store the sum of fare for each Vehicle Type. 4. Print the  TotalFare.

Write a Python program to demonstrate multiple inheritance.

1.  Employee  class has 3 data members  EmployeeID ,  Gender  (String) , Salary  and

PerformanceRating ( Out of 5 )  of type int. It has a get() function to get these details from

2.  JoiningDetail  class has a data member  DateOfJoining  of type  Date  and a function

getDoJ  to get the Date of joining of employees.

3.  Information  Class uses the marks from  Employee  class and the  DateOfJoining  date

from the  JoiningDetail  class to calculate the top 3 Employees based on their Ratings and then Display, using  readData , all the details on these employees in Ascending order of their Date Of Joining.

You are given an array of numbers as input: [10,20,10,40,50,45,30,70,5,20,45] and a target value: 50. You are required to find pairs of elements (indices of two numbers) from the given array whose sum equals a specific target number. Your solution should not use the same element twice, thus it must be a single solution for each input

1.1 Write a Python class that defines a function to find pairs which takes 2 parameters (input array and target value) and returns a list of pairs whose sum is equal to target given above. You are required to print the list of pairs and state how many pairs if found. Your solution should call the function to find pairs, then return a list of pairs.

1.2 Given the input array nums in 1.1 above. Write a second program to find a set of good pairs from that input array nums. Here a pair (i,j) is said to be a good pair if nums[i] is the same as nums[j] and i < j. You are required to display an array of good pairs indices and the number of good pairs.

How to find largest number inn list in python

Given a list of integers, write a program to print the sum of all prime numbers in the list of integers.

Note: one is neither prime nor composite number

Using the pass statement

how to get a input here ! example ! 2 4 5 6 7 8 2 4 5 2 3 8 how to get it?

  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

Python Practice for Beginners: 15 Hands-On Problems

Author's photo

  • online practice

Want to put your Python skills to the test? Challenge yourself with these 15 Python practice exercises taken directly from our Python courses!

There’s no denying that solving Python exercises is one of the best ways to practice and improve your Python skills . Hands-on engagement with the language is essential for effective learning. This is exactly what this article will help you with: we've curated a diverse set of Python practice exercises tailored specifically for beginners seeking to test their programming skills.

These Python practice exercises cover a spectrum of fundamental concepts, all of which are covered in our Python Data Structures in Practice and Built-in Algorithms in Python courses. Together, both courses add up to 39 hours of content. They contain over 180 exercises for you to hone your Python skills. In fact, the exercises in this article were taken directly from these courses!

In these Python practice exercises, we will use a variety of data structures, including lists, dictionaries, and sets. We’ll also practice basic programming features like functions, loops, and conditionals. Every exercise is followed by a solution and explanation. The proposed solution is not necessarily the only possible answer, so try to find your own alternative solutions. Let’s get right into it!

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).

Explanation

We initialize two variables, first_semester_total and second_semester_total , to store the total expenses for each semester. Then, we iterate through the monthly_spending list using enumerate() , which provides both the index and the corresponding value in each iteration. If you have never heard of enumerate() before – or if you are unsure about how for loops in Python work – take a look at our article How to Write a for Loop in Python .

Within the loop, we check if the index is less than 6 (January to June); if so, we add the expense to first_semester_total . If the index is greater than 6, we add the expense to second_semester_total .

After iterating through all the months, we calculate the average expenses for each semester by dividing the total expenses by 6 (the number of months in each semester). Finally, we print out the average expenses for each semester.

Python Practice Problem 2: Who Spent More?

John has a friend, Sam, who also kept a list of his expenses from last year:

They want to find out how many months John spent more money than Sam. Use a for loop to compare their expenses for each month. Keep track of the number of months where John spent more money.

We initialize the variable months_john_spent_more with the value zero. Then we use a for loop with range(len()) to iterate over the indices of the john_monthly_spending list.

Within the loop, we compare John's expenses with Sam's expenses for the corresponding month using the index i . If John's expenses are greater than Sam's for a particular month, we increment the months_john_spent_more variable. Finally, we print out the total number of months where John spent more money than Sam.

Python Practice Problem 3: All of Our Friends

Paul and Tina each have a list of their respective friends:

Combine both lists into a single list that contains all of their friends. Don’t include duplicate entries in the resulting list.

There are a few different ways to solve this problem. One option is to use the + operator to concatenate Paul and Tina's friend lists ( paul_friends and tina_friends ). Afterwards, we convert the combined list to a set using set() , and then convert it back to a list using list() . Since sets cannot have duplicate entries, this process guarantees that the resulting list does not hold any duplicates. Finally, we print the resulting combined list of friends.

If you need a refresher on Python sets, check out our in-depth guide to working with sets in Python or find out the difference between Python sets, lists, and tuples .

Python Practice Problem 4: Find the Common Friends

Now, let’s try a different operation. We will start from the same lists of Paul’s and Tina’s friends:

In this exercise, we’ll use a for loop to get a list of their common friends.

For this problem, we use a for loop to iterate through each friend in Paul's list ( paul_friends ). Inside the loop, we check if the current friend is also present in Tina's list ( tina_friends ). If it is, it is added to the common_friends list. This approach guarantees that we test each one of Paul’s friends against each one of Tina’s friends. Finally, we print the resulting list of friends that are common to both Paul and Tina.

Python Practice Problem 5: Find the Basketball Players

You work at a sports club. The following sets contain the names of players registered to play different sports:

How can you obtain a set that includes the players that are only registered to play basketball (i.e. not registered for football or volleyball)?

This type of scenario is exactly where set operations shine. Don’t worry if you never heard about them: we have an article on Python set operations with examples to help get you up to speed.

First, we use the | (union) operator to combine the sets of football and volleyball players into a single set. In the same line, we use the - (difference) operator to subtract this combined set from the set of basketball players. The result is a set containing only the players registered for basketball and not for football or volleyball.

If you prefer, you can also reach the same answer using set methods instead of the operators:

It’s essentially the same operation, so use whichever you think is more readable.

Python Practice Problem 6: Count the Votes

Let’s try counting the number of occurrences in a list. The list below represent the results of a poll where students were asked for their favorite programming language:

Use a dictionary to tally up the votes in the poll.

In this exercise, we utilize a dictionary ( vote_tally ) to count the occurrences of each programming language in the poll results. We iterate through the poll_results list using a for loop; for each language, we check if it already is in the dictionary. If it is, we increment the count; otherwise, we add the language to the dictionary with a starting count of 1. This approach effectively tallies up the votes for each programming language.

If you want to learn more about other ways to work with dictionaries in Python, check out our article on 13 dictionary examples for beginners .

Python Practice Problem 7: Sum the Scores

Three friends are playing a game, where each player has three rounds to score. At the end, the player whose total score (i.e. the sum of each round) is the highest wins. Consider the scores below (formatted as a list of tuples):

Create a dictionary where each player is represented by the dictionary key and the corresponding total score is the dictionary value.

This solution is similar to the previous one. We use a dictionary ( total_scores ) to store the total scores for each player in the game. We iterate through the list of scores using a for loop, extracting the player's name and score from each tuple. For each player, we check if they already exist as a key in the dictionary. If they do, we add the current score to the existing total; otherwise, we create a new key in the dictionary with the initial score. At the end of the for loop, the total score of each player will be stored in the total_scores dictionary, which we at last print.

Python Practice Problem 8: Calculate the Statistics

Given any list of numbers in Python, such as …

 … write a function that returns a tuple containing the list’s maximum value, sum of values, and mean value.

We create a function called calculate_statistics to calculate the required statistics from a list of numbers. This function utilizes a combination of max() , sum() , and len() to obtain these statistics. The results are then returned as a tuple containing the maximum value, the sum of values, and the mean value.

The function is called with the provided list and the results are printed individually.

Python Practice Problem 9: Longest and Shortest Words

Given the list of words below ..

… find the longest and the shortest word in the list.

To find the longest and shortest word in the list, we initialize the variables longest_word and shortest_word as the first word in the list. Then we use a for loop to iterate through the word list. Within the loop, we compare the length of each word with the length of the current longest and shortest words. If a word is longer than the current longest word, it becomes the new longest word; on the other hand, if it's shorter than the current shortest word, it becomes the new shortest word. After iterating through the entire list, the variables longest_word and shortest_word will hold the corresponding words.

There’s a catch, though: what happens if two or more words are the shortest? In that case, since the logic used is to overwrite the shortest_word only if the current word is shorter – but not of equal length – then shortest_word is set to whichever shortest word appears first. The same logic applies to longest_word , too. If you want to set these variables to the shortest/longest word that appears last in the list, you only need to change the comparisons to <= (less or equal than) and >= (greater or equal than), respectively.

If you want to learn more about Python strings and what you can do with them, be sure to check out this overview on Python string methods .

Python Practice Problem 10: Filter a List by Frequency

Given a list of numbers …

… create a new list containing only the numbers that occur at least three times in the list.

Here, we use a for loop to iterate through the number_list . In the loop, we use the count() method to check if the current number occurs at least three times in the number_list . If the condition is met, the number is appended to the filtered_list .

After the loop, the filtered_list contains only numbers that appear three or more times in the original list.

Python Practice Problem 11: The Second-Best Score

You’re given a list of students’ scores in no particular order:

Find the second-highest score in the list.

This one is a breeze if we know about the sort() method for Python lists – we use it here to sort the list of exam results in ascending order. This way, the highest scores come last. Then we only need to access the second to last element in the list (using the index -2 ) to get the second-highest score.

Python Practice Problem 12: Check If a List Is Symmetrical

Given the lists of numbers below …

… create a function that returns whether a list is symmetrical. In this case, a symmetrical list is a list that remains the same after it is reversed – i.e. it’s the same backwards and forwards.

Reversing a list can be achieved by using the reverse() method. In this solution, this is done inside the is_symmetrical function.

To avoid modifying the original list, a copy is created using the copy() method before using reverse() . The reversed list is then compared with the original list to determine if it’s symmetrical.

The remaining code is responsible for passing each list to the is_symmetrical function and printing out the result.

Python Practice Problem 13: Sort By Number of Vowels

Given this list of strings …

… sort the list by the number of vowels in each word. Words with fewer vowels should come first.

Whenever we need to sort values in a custom order, the easiest approach is to create a helper function. In this approach, we pass the helper function to Python’s sorted() function using the key parameter. The sorting logic is defined in the helper function.

In the solution above, the custom function count_vowels uses a for loop to iterate through each character in the word, checking if it is a vowel in a case-insensitive manner. The loop increments the count variable for each vowel found and then returns it. We then simply pass the list of fruits to sorted() , along with the key=count_vowels argument.

Python Practice Problem 14: Sorting a Mixed List

Imagine you have a list with mixed data types: strings, integers, and floats:

Typically, you wouldn’t be able to sort this list, since Python cannot compare strings to numbers. However, writing a custom sorting function can help you sort this list.

Create a function that sorts the mixed list above using the following logic:

  • If the element is a string, the length of the string is used for sorting.
  • If the element is a number, the number itself is used.

As proposed in the exercise, a custom sorting function named custom_sort is defined to handle the sorting logic. The function checks whether each element is a string or a number using the isinstance() function. If the element is a string, it returns the length of the string for sorting; if it's a number (integer or float), it returns the number itself.

The sorted() function is then used to sort the mixed_list using the logic defined in the custom sorting function.

If you’re having a hard time wrapping your head around custom sort functions, check out this article that details how to write a custom sort function in Python .

Python Practice Problem 15: Filter and Reorder

Given another list of strings, such as the one below ..

.. create a function that does two things: filters out any words with three or fewer characters and sorts the resulting list alphabetically.

Here, we define filter_and_sort , a function that does both proposed tasks.

First, it uses a for loop to filter out words with three or fewer characters, creating a filtered_list . Then, it sorts the filtered list alphabetically using the sorted() function, producing the final sorted_list .

The function returns this sorted list, which we print out.

Want Even More Python Practice Problems?

We hope these exercises have given you a bit of a coding workout. If you’re after more Python practice content, head straight for our courses on Python Data Structures in Practice and Built-in Algorithms in Python , where you can work on exciting practice exercises similar to the ones in this article.

Additionally, you can check out our articles on Python loop practice exercises , Python list exercises , and Python dictionary exercises . Much like this article, they are all targeted towards beginners, so you should feel right at home!

You may also like

python assignment expert questions

How Do You Write a SELECT Statement in SQL?

python assignment expert questions

What Is a Foreign Key in SQL?

python assignment expert questions

Enumerate and Explain All the Basic Elements of an SQL Query

theme logo

Logical Python

Effective Python Tutorials

Python Practice Exercises and Challenges with Solutions

Practice exercise.

Welcome to our Python Exercise collection, these exercises are designed for all levels of learners. Whether you are a Beginner, an intermittent developer, or an expert. We have everything for you.

These are the curated set of exercises, each customized to reinforce essential concepts such as loops, functions, and conditionals. These bite-sized challenges are perfect for quick practice sessions, making learning Python a breeze.

Simply choose an exercise, read the instructions, and start coding! Solutions are available to keep you on the right track.

Here are the exercises:

  • Python Basics Exercise with Solutions
  • Python Input/Output Exercise with Solutions
  • Python String Exercise with Solutions
  • Python Loop Exercise with Solutions
  • Python List Exercise with Solutions
  • Python Tuple Exercise with Solutions
  • Python Set Exercise with Solutions
  • Python Dictionary Exercise with Solutions
  • Python Functions Exercise with Solutions
  • Python OOPS Exercise with Solutions

Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.24%

Python if-else easy python (basic) max score: 10 success rate: 89.70%, arithmetic operators easy python (basic) max score: 10 success rate: 97.41%, python: division easy python (basic) max score: 10 success rate: 98.68%, loops easy python (basic) max score: 10 success rate: 98.10%, write a function medium python (basic) max score: 10 success rate: 90.31%, print function easy python (basic) max score: 20 success rate: 97.27%, list comprehensions easy python (basic) max score: 10 success rate: 97.68%, find the runner-up score easy python (basic) max score: 10 success rate: 94.17%, nested lists easy python (basic) max score: 10 success rate: 91.70%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

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.

python assignment expert questions

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....

python assignment expert questions

Top 72 Swift Interview Questions

41 Advanced Python Interview Questions You Must Know

The entry-level Python developer salary in the US is $78,176 a year on average, The average junior Python developer salary is $89,776, The mid-level Python developer salary reaches $$111,896, While the senior Python developer earns $122,093 on average.

Q1 :   What are virtualenvs ?

  • A virtualenv is what Python developers call an isolated environment for development, running, debugging Python code.
  • It is used to isolate a Python interpreter together with a set of libraries and settings.
  • Together with pip, it allows develop, deploy and run multiple applications on a single host, each with its own version of the Python interpreter, and a separate set of libraries.

Q2 :   What are the Wheels and Eggs ? What is the difference?

Wheel and Egg are both packaging formats that aim to support the use case of needing an install artifact that doesn’t require building or compilation, which can be costly in testing and production workflows.

The Egg format was introduced by setuptools in 2004, whereas the Wheel format was introduced by PEP 427 in 2012.

Wheel is currently considered the standard for built and binary packaging for Python.

Here’s a breakdown of the important differences between Wheel and Egg.

  • Wheel has an official PEP. Egg did not.
  • Wheel is a distribution format, i.e a packaging format. 1 Egg was both a distribution format and a runtime installation format (if left zipped), and was designed to be importable.
  • Wheel archives do not include .pyc files. Therefore, when the distribution only contains Python files (i.e. no compiled extensions), and is compatible with Python 2 and 3, it’s possible for a wheel to be “universal”, similar to an sdist.
  • Wheel uses PEP376-compliant .dist-info directories. Egg used .egg-info.
  • Wheel has a richer file naming convention. A single wheel archive can indicate its compatibility with a number of Python language versions and implementations, ABIs, and system architectures.
  • Wheel is versioned. Every wheel file contains the version of the wheel specification and the implementation that packaged it.
  • Wheel is internally organized by sysconfig path type, therefore making it easier to convert to other formats.

Q3 :   What does an x = y or z assignment do in Python?

If bool(a) returns False , then x is assigned the value of b .

Q4 :   What does the Python nonlocal statement do (in Python 3.0 and later)?

  • In short, it lets you assign values to a variable in an outer (but non-global) scope .
  • The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

For example, the counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.

Q5 :   What is the function of self ?

Self is a variable that represents the instance of the object to itself . In most object-oriented programming languages, this is passed to the methods as a hidden parameter that is defined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to a separate instance of the variable for individual objects.

Let's say you have a class ClassA which contains a method methodA defined as:

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

The self variable refers to the object itself.

Q6 :   What is the python with statement designed for?

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers .

For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow.

As a result you could do something like:

OR (Python 3.1)

Q7 :   Can you explain Closures (as they relate to Python)?

Objects are data with methods attached, closures are functions with data attached. The method of binding data to a function without actually passing them as parameters is called closure .

Q8 :   Create function that similar to os.walk

Q9 :   how do i write a function with output parameters (call by reference).

In Python arguments are passed by assignment . When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object.

If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method (like b = b + 1 ), the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.

So to achieve the desired effect your best choice is to return a tuple containing the multiple results:

Q10 :   How is set() implemented internally?

I've seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have?

  • Indeed, CPython's sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values.
  • So basically a set uses a hashtable as its underlying data structure. This explains the O(1) membership checking, since looking up an item in a hashtable is an O(1) operation, on average.
  • Also, it worth to mention when people say sets have O(1) membership-checking, they are talking about the average case. In the worst case (when all hashed values collide) membership-checking is O(n) .

Q11 :   How to make a chain of function decorators ?

How can I make two decorators in Python that would do the following?

which should return:

Q12 :   Is it a good idea to use multi-thread to speed your Python code?

Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it.

Python has a construct called the Global Interpreter Lock ( GIL ). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution.

Q13 :   Show me three different ways of fetching every third item in the list

Q14 :   what are metaclasses in python.

  • A class defines how an instance of the class (i.e. an object) behaves while
  • A metaclass defines how a class behaves .
  • A class is an instance of a metaclass.

You can call it a 'class factory'.

Q15 :   What are the advantages of NumPy over regular Python lists ?

NumPy's arrays are more compact than Python lists - a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access to reading and writing items is also faster with NumPy.

The difference is mostly due to "indirectness" - a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value - and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers take 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists.

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allows one to avoid unnecessary work. And they are also efficiently implemented.

Q16 :   What is Cython ?

  • Cython is a programming language that aims to be a superset of the Python programming language, designed to give C-like performance with code that is written mostly in Python with optional additional C-inspired syntax.
  • Cython is a compiled language that is typically used to generate CPython extension modules.

Q17 :   What is GIL ?

Python has a construct called the Global Interpreter Lock (GIL).

The GIL makes sure that only one of your threads can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution.

Q18 :   What is MRO in Python? How does it work?

Method Resolution Order (MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.

In Python, method resolution order defines the order in which the base classes are searched when executing a method . First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO (Method Resolution Order). While inheriting from another class, the interpreter needs a way to resolve the methods that are being called via an instance. Thus we need the method resolution order.

Python resolves method and attribute lookups using the C3 linearisation of the class and its parents. The C3 linearisation is neither depth-first nor breadth-first in complex multiple inheritance hierarchies.

Q19 :   What is Monkey Patching ? How to use it in Python?

A MonkeyPatch is a piece of Python code that extends or modifies other code at runtime (typically at startup).

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.

Q20 :   What is an alternative to GIL ?

The Python interpreter is not fully thread-safe . In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice.

If the purpose of the GIL is to protect state from corruption, then one obvious alternative is lock at a much finer grain (fine-grained locking) ; perhaps at a per object level. The problem with this is that although it has been demonstrated to increase the performance of multi-threaded programs, it has more overhead and single-threaded programs suffer as a result.

Q21 :   What is the difference between old style and new style classes in Python?

What is the difference between old style and new style classes in Python? When should I use one or the other?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

Old-style classes don't.

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

Also, MRO (Method Resolution Order) changed:

  • Classic classes do a depth first search from left to right. Stop on first match. They do not have the mro attribute.
  • New-style classes MRO is more complicated to synthesize in a single English sentence. One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the mro attribute which shows the search order.

Some other notes:

  • New style class objects cannot be raised unless derived from Exception .
  • Old style classes are still marginally faster for attribute lookup.

Q22 :   What is the difference between @staticmethod and @classmethod ?

A staticmethod is a method that knows nothing about the class or the instance it was called on. It just gets the arguments that were passed, no implicit first argument. Its definition is immutable via inheritance.

A classmethod , on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. Its definition follows Sub class, not Parent class, via inheritance.

If your method accesses other variables/methods in your class then use @classmethod .

Q23 :   What is the purpose of the single underscore _ variable in Python?

_ has 4 main conventional uses in Python:

  • To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
  • For translation lookup in i18n (see the gettext documentation for example), as in code like: raise forms.ValidationError(_("Please enter a correct username"))
  • As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: label, has_label, _ = text.partition(':') .
  • As part of a function definition (using either def or lambda ), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like: callback = lambda _: True

Q24 :   What will be returned by this code?

It will return:

This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4, so all the functions now return 4**2, i.e. 16.

Q25 :   What will be the output of the code below?

The above code will output [] , and will not result in an IndexError .

As one would expect, attempting to access a member of a list using an index that exceeds the number of members (e.g., attempting to access list[10] in the list above) results in an IndexError . However, attempting to access a slice of a list at a starting index that exceeds the number of members in the list will not result in an IndexError and will simply return an empty list.

What makes this a particularly nasty gotcha is that it can lead to bugs that are really hard to track down since no error is raised at runtime.

Q26 :   What's the difference between a Python module and a Python package ?

Any Python file is a module , its name being the file's base name without the .py extension.

A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional init .py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own init .py file.

Packages are modules too. They are just packaged up differently; they are formed by the combination of a directory plus init .py file. They are modules that can contain other modules.

Q27 :   Whenever you exit Python, is all memory de-allocated ?

The answer here is no .

  • The modules with circular references to other objects , or to objects referenced from global namespaces, aren’t always freed on exiting Python.
  • Plus, it is impossible to de-allocate portions of memory reserved by the C library .

Q28 :   Why Python (CPython and others) uses the GIL ?

In CPython, the global interpreter lock, or GIL , is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe .

Python has a GIL as opposed to fine-grained locking for several reasons:

  • It is faster in the single-threaded case.
  • It is faster in the multi-threaded case for i/o bound programs.
  • It is faster in the multi-threaded case for cpu-bound programs that do their compute-intensive work in C libraries.
  • It makes C extensions easier to write: there will be no switch of Python threads except where you allow it to happen (i.e. between the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros).
  • It makes wrapping C libraries easier. You don't have to worry about thread safety. If the library is not thread-safe, you simply keep the GIL locked while you call it.

Q29 :   Will the code below work? Why or why not?

Given the following subclass of dictionary:

Will the code below work? Why or why not?

Actually, the code shown will work with the standard dictionary object in python 2 or 3—that is normal behavior. Subclassing dict is unnecessary. However, the subclass still won’t work with the code shown because __missing__ returns a value but does not change the dict itself:

So it will “work,” in the sense that it won’t produce any error, but doesn’t do what it seems to be intended to do.

Here is a __missing__ -based method that will update the dictionary, as well as return a value:

But since version 2.5, a defaultdict object has been available in the collections module (in the standard library.)

Q30 :   Describe Python's Garbage Collection mechanism in brief

A lot can be said here. There are a few main points that you should mention:

  • Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else
  • occasionally things called "reference cycles" happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1 . If o1 and o2 are not referenced by anything else then they shouldn't be live. But each of them has a reference count of 1.
  • Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.

This explanation is CPython specific.

Q31 :   How do I access a module written in Python from C ?

You can get a pointer to the module object by calling PyImport_ImportModule :

You can then access the module’s attributes (i.e. any name defined in the module) as follows:

Calling PyObject_SetAttrString to assign to variables in the module also works.

Q32 :   How should one access nonlocal variables in closures in python 2.x?

Inner functions can read nonlocal variables in 2.x, just not rebind them. This is annoying, but you can work around it. Just create a dictionary, and store your data as elements therein. Inner functions are not prohibited from mutating the objects that nonlocal variables refer to.

Or using nonlocal class :

It works because you can modify nonlocal variables. But you cannot do assignment to nonlocal variables.

Q33 :   How to read a 8GB file in Python?

All you need to do is use the file object as an iterator .

Even better is using context manager in recent Python versions.

This will automatically close the file as well.

Q34 :   Is there a simple, elegant way to define singletons ?

Use a metaclass :

In general, it makes sense to use a metaclass to implement a singleton. A singleton is special because is created only once, and a metaclass is the way you customize the creation of a class. Using a metaclass gives you more control in case you need to customize the singleton class definitions in other ways.

Another approach is to use Modules :

Modules are imported only once, everything else is overthinking. Don't use singletons and try not to use globals.

Q35 :   Is there any downside to the -O flag apart from missing on the built-in debugging information?

Many python modules that assume docstrings are available, and would break if that optimization level is used, for instance at the company where I work, raw sql is placed in docstrings , and executed by way of function decorators (not even kidding).

Somewhat less frequently, assert is used to perform logic functions, rather than merely declare the invariant expectations of a point in code, and so any code like that would also break.

Q36 :   What does Python optimisation ( -O or PYTHONOPTIMIZE ) do?

In Python 2.7, -O has the following effect:

  • the byte code extension changes to .pyo
  • sys.flags.optimize gets set to
  • __debug__ is False
  • asserts don't get executed

In addition -OO has the following effect:

  • sys.flags.optimize gets set to 2
  • doc strings are not available

Q37 :   What is a global interpreter lock ( GIL ) and why is it an issue?

A lot of noise has been made around removing the GIL from Python, and I'd like to understand why that is so important.

There are several implementations of Python, for example, CPython, IronPython, RPython, etc.

In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe.

The GIL is controversial because it prevents multithreaded CPython programs from taking full advantage of multiprocessor systems in certain situations. Note that potentially blocking or long-running operations, such as I/O, image processing, and NumPy number crunching, happen outside the GIL. Therefore it is only in multithreaded programs that spend a lot of time inside the GIL, interpreting CPython bytecode, that the GIL becomes a bottleneck.

The GIL is a problem if , and only if, you are doing CPU-intensive work in pure Python. Here you can get cleaner design using processes and message-passing (e.g. mpi4py).

Q38 :   What will this code return ?

What will this code return? Explain.

Here ('A', 'B') is a tuple. We could access values in tuple, use the square brackets [] . The a == False is an expression that could be evaluated as boolean. In Python 3.x True and False are keywords and will always be equal to 1 and 0. So the result will be A :

Q39 :   Why isn't all memory freed when Python exits ?

Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.

If you want to force Python to delete certain things on deallocation, you can use the atexit module to register one or more exit functions to handle those deletions.

Q40 :   Why use else in try/except construct in Python?

Why have the code that must be executed if the try clause does not raise an exception within the try construct? Why not simply have it follow the try/except at the same indentation level?

The else block is only executed if the code in the try doesn't raise an exception; if you put the code outside of the else block, it'd happen regardless of exceptions. Also, it happens before the finally , which is generally important.

This is generally useful when you have a brief setup or verification section that may error, followed by a block where you use the resources you set up in which you don't want to hide errors. You can't put the code in the try because errors may go to except clauses when you want them to propagate. You can't put it outside of the construct, because the resources definitely aren't available there, either because setup failed or because the finally tore everything down. Thus, you have an else block.

Q41 :   Why would you use metaclasses ?

Well, usually you don't. The main use case for a metaclass is creating an API. A typical example of this is the Django ORM.

It allows you to define something like this:

And if you do this:

It won't return an IntegerField object. It will return an int , and can even take it directly from the database.

This is possible because models.Model defines __metaclass__ and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.

Django makes something complex look simple by exposing a simple API and using metaclasses , recreating code from this API to do the real job behind the scenes.

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

python assignment expert questions

14 advanced Python interview questions (and answers)

python assignment expert questions

In today’s competitive tech landscape, the right Python developer can be hugely beneficial for your company, while the wrong choice can lead to various challenges. Underskilled developers are slow, write inefficient code, and require a significant amount of training to meet your standards. 

Hiring developers with a strong understanding of Python’s intricacies, powerful features, and real-world uses is essential to building robust and innovative applications. The best way to do this is using a multi-pronged hiring approach complete with Python interview questions . 

Here, we offer 14 advanced Python interview questions complete with high-level sample answers to help you hire the best talent for your position. 

Table of contents

Why use advanced python interview questions in your hiring process , 14 advanced python interview questions and answers, how to assess advanced python developers before hiring, hire leading python developers with testgorilla.

Advanced Python interview questions are a powerful tool that can help you identify the most suitable candidates for your position. Here are a few of the key benefits of using them as part of your hiring campaign. 

Testing candidates’ Python skills

First and foremost, advanced Python interview questions enable you to test each candidate’s Python skills. This separates those with advanced knowledge from the under-experienced beginners and ensures that candidates have the skills necessary to handle complex tasks. 

If you’re hiring for a specialized position, then you can customize your questions to ensure you’re assessing the appropriate knowledge. For example, you might like to ask Python data-scientist interview questions if you’re looking for individuals who excel in this area.  

Gauging problem-solving and critical-thinking ability

Advanced Python questions also present the opportunity to learn more about each candidate’s thought processes. Their answers will give you some insight into their problem-solving and critical-thinking abilities. 

For example, you could ask questions that require candidates to break down a problem, think about its components, and then provide a step-by-step explanation. The way they approach this and present their answer can help you understand how they think.

Understanding how candidates perform under pressure

Adding time constraints to your Python interview questions enables you to identify the applicants who perform well under pressure. You can use real-world scenarios to simulate the challenges candidates could face while working at your company to see how they handle them. 

Assessing candidates’ communication skills

Asking complex questions also gives candidates a chance to showcase their communication skills. There are two things that you can look for here. 

First up, candidates should be able to seek clarification if they don’t understand a question. This can help you understand how they approach problems, and you can gain insights into each individual’s knowledge through the questions they ask. 

The way that applicants present their answers is also extremely important. For example, do they present information in a clear, concise way that’s easily understandable to others? 

Understanding candidates’ strengths and weaknesses

Using Linux-specific questions during the hiring process also enables you to identify each candidate’s strengths and weaknesses. This is crucial in helping you decide which is the best fit for your company. 

Let’s say, for example, that you already employ one senior Python developer who excels in a certain area. It’s probably not the end of the world if a candidate is a little weak in this area, as they will be able to get support and guidance from their colleague. 

Below, we’ve listed 14 advanced Python interview questions that you can use to assess a candidate’s skills. We’ve also provided high-level sample answers for each question, but note that there are often multiple ways to solve a Python problem, so there could be other correct answers. 

Remember, you can adapt or change these questions so they target skills and experience that are directly relevant to the position you’re hiring for. 

1. What is PIP and how do you use it? 

PIP is a Python package manager that’s used to simplify the installation and management of third-party libraries. Some of the tasks it enables you to do include: 

Installing packages with the command pip install package_name  

Specifying versions with the command pip install package_name==version

Upgrading packages with the command pip install --upgrade package_name  

Uninstalling packages with the command pip uninstall package_name

Listing installed packages with the command pip list

Installing packages from a requirements.txt file with the command pip install -r requirements.txt

Most modern systems have PIP installed by default, but you may need to install it separately if you’re using a version older than Python 3.3. 

2. Can you tell me about Django and how it’s used by Python developers? 

Django is a powerful Python web framework that helps developers create robust, scalable, and maintainable web applications. It offers a suite of tools, conventions, and libraries to help developers work efficiently and focus on application-specific code. 

Some of the key features of Django include: 

Simplified form handling

Object-relational mapping (ORM)

URL routing and views

A smooth, user-friendly interface for managing application data

User authentication and permission management

Advanced built-in security

Python developers can use Django to create different types of web apps, including content management systems (CMS), e-commerce websites, APIs, social media platforms, and more. 

3. What are local and global namespaces, and how are they used in Python programming? 

Python namespaces are containers that hold the mapping of names to objects. You can use them to organize and manage classes, functions, variables, and other objects in your code. 

Local namespaces are created whenever functions are called and are only accessible within the function that defines them. 

Each function call creates a new local namespace, and they are destroyed when the function is complete. This ensures that they don’t interfere with each other, and they are designed to prevent naming conflicts between different functions. 

Global namespaces, on the other hand, exist throughout the Python script/model. It contains the names of variables defined at the top-level scope, and these variables are accessible from any part of the script. 

Global namespaces persist for as long as the script/model is in memory, and you can change global variables with the help of the global keyword. 

4. Explain exception handling in Python.

Exception handling refers to the process of managing and responding to runtime errors or unexpected situations that can occur when a program is being executed. 

You can catch and handle these errors with the try , except, else , and finally blocks. Here’s how. 

Place the code that could raise an exception/error in the try block. 

Use the except block to specify the exception you’re trying to catch. You can add multiple except blocks if necessary. If an exception is raised in the try block, it will execute the code in the relevant except block. 

Use the else block to add the code that you want to execute if there are no exceptions. This block is optional.  

The finally block is also optional and is executed last, regardless of whether or not there are exceptions. 

Here’s an example where a user enters a number, and an exception is raised if they enter zero or a non-numeric number: 

    num = int(input("Enter a number: "))

    result = 10 / num

except ZeroDivisionError:

    print("Cannot divide by zero.")

except ValueError:

    print("Invalid input. Please enter a number.")

    print("Result:", result)

    print("Exception handling complete.")

With proper exception handling, you can prevent crashes due to unforeseen errors, provide informative error messages to users, and log debugging information. 

5. Explain, with code, how you would copy an object in Python.

The easiest way to copy an object in Python is with the copy module. This enables you to create both shallow copies and deep copies. 

Shallow copies create new objects without copies of any nested objects. Because of this, changes to nested objects in the original can still affect the copied object. Here’s what the code looks like for a shallow copy: 

import copy

original_list = [[1, 2, 3], [4, 5, 6]]

shallow_copied_list = copy.copy(original_list)

original_list[0][0] = 99  # Modifying the original list

print(shallow_copied_list)  # Changes are reflected in the shallow copy

On the other hand, deep copies create new objects, along with copies of all nested objects. This means that changes to original nested objects aren’t reflected in the copy. Here’s what the code looks like for a deep copy. 

deep_copied_list = copy.deepcopy(original_list)

print(deep_copied_list)  # Deep copy remains unchanged

It’s important to note that not all objects can be copied. Objects that aren’t copyable will raise an exception with the copy module. 

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

PEP 8, or Python Enhancement Proposal 8, is the official Python style guide for writing readable and maintainable code. It contains clear guidelines for formatting your code to ensure it’s consistent and understandable. This makes it easier for other developers to read, maintain, and collaborate on your code. 

Hiring developers who are well-versed in PEP 8 will write high-quality, consistently formatted code. It also ensures that they will be able to collaborate effectively with the rest of your skilled team. 

7. Tell me how you would randomize the items on a list with Python.

The easiest way to randomize the items on a list in Python is with the random module. You can use the random.shuffle() function to shuffle the items and modify the original list. 

import random

my_list = [1, 2, 3, 4, 5]

# Shuffle the list in place

random.shuffle(my_list)

print(my_list)  # Output will be a shuffled version of the original list

Alternatively, you can use the random.sample() to randomize the items of a list and save them in a new list, rather than modifying the original list. 

# Get a new shuffled list without modifying the original list

shuffled_list = random.sample(my_list, len(my_list))

print(shuffled_list)  # Output will be a shuffled version of the original list

8. What is the Global Interpreter Lock (GIL)? Why is it important? 

The GIL is a mutex used by the CPython interpreter, which is the most widespread implementation of Python. The key function of the GIL is to limit Python bytecode execution to a single thread. 

This is important for various reasons, including simplifying memory management across multiple threads. It also prevents multiple threads from accessing shared data at the same time, which can cause data corruption. 

Finally, the GIL ensures compatibility with C extension models that aren’t designed to handle multi-threading.

9. What does the nonlocal statement do?

In Python, the nonlocal statement is used to indicate that a variable in a nested function isn’t local. It enables you to modify variables in an outer, but non-global scope from within a nested function. 

Here’s an example of how you can use nonlocal . We’re using the nonlocal statement to modify the outer_variable of the outer_function from within the inner_function .

def outer_function():

    outer_variable = 10

    def inner_function():

        nonlocal outer_variable

        outer_variable = 20  # Modify the variable in the enclosing scope

    inner_function()

    print("Outer variable:", outer_variable)  # Output: 20

outer_function()

10. What’s the difference between a Python package and a Python module? 

Packages and modules are both mechanisms for organizing and structuring code, but they have different purposes and characteristics. 

For starters, a Python module is a single file containing Python code. It can define functions, variables, and other objects that are used elsewhere in your program. Because of this, modules are particularly useful for organizing related code into separate files, enabling you to easily manage your codebase and improve code reuse. 

Meanwhile, packages are code packets that contain multiple modules and/or sub-packages. This enables you to organize related modules in a single directory. 

Packages are particularly important for larger projects that involve multiple code files and functionalities. 

11. How would you use Python to fetch every 10th item from a list? 

The easiest way to fetch every 10th item from a list is with a technique called “slicing”. Here’s an example of how you do it: 

original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

# Fetch every 10th item using slice notation

every_10th_item = original_list[::10]

print(every_10th_item)

This example would return 0, 10, and 20. If you want to start from a different number, you can modify the every_10th_item = original_list[::10] line. 

every_10th_item_starting_from_index_2 = original_list[2::10]

print(every_10th_item_starting_from_index_2)

This example would return 2, 12.

Remember that Python is a zero-based language, which means that the first element is at index 0. 

12. What are metaclasses in Python and why are they important? 

Metaclasses enable you to define the behavior of Python classes. 

In simple terms, you can think of metaclass as a class for classes. They define how classes are created, how they interact, and what attributes they have.

Here are a few reasons why python metaclasses are so important graphic

Here are a few reasons why Python metaclasses are so important: 

Code reusability. Since all classes within a metaclass are defined by the same behaviors, they contain a common logic. This makes it much easier to reuse code. 

Dynamically modifying classes. With metaclasses, you can dynamically modify class attributes and methods when you’re creating them, enabling dynamic code generation and automatic registration of subclasses, among other things. 

Customizing class creation. This enables you to define the behavior of all classes created with this metaclass. 

Enforcing best practices. With metaclasses, you can ensure that certain attributes are present or methods are defined in subclasses. This enables you to enforce design patterns or best practices in your code base. 

13. How would you locally save images with Python?  

The best way to locally save images with Python is using the open() function alongside the binary write mode ( 'wb' ). Image data needs to be read from the source and written to a new file. 

One of the best ways to fetch image data is with the requests library. If you don’t already have the requests library installed, you can install it by running pip install requests .

Here’s an example of the code you’d use: 

import requests

def save_image_from_url(url, filename):

    response = requests.get(url)    

    if response.status_code == 200:

        with open(filename, 'wb') as file:

            file.write(response.content)

        print(f"Image saved as {filename}")

        print("Failed to download the image")

# URL of the image

image_url = "https://example.com/image.jpg"

# Name for the saved image file

output_filename = "saved_image.jpg"

# Save the image

save_image_from_url(image_url, output_filename)

In this example, you need to replace "https://example.com/image.jpg" with the URL of the image you want to save and "saved_image.jpg" with the name of your saved image. 

14. What is the functools module used for in Python? 

With the functools module, you can perform higher-order functions and operations on callable objects. It contains a number of useful tools, including the following: 

The functools.partial function enables you to create a new function with preset augments. 

The functools.reduce function enables you to apply a binary function to the elements of a sequence in a cumulative way. 

The functools.wraps decorator can be used to maintain the original metadata of a decorated function. 

The functools.singledispatch function enables you to create a generic function that dispatches its execution to different specialized functions. 

Note that this is just a small example of the tool available within the functools module. Overall, it can help you improve code readability, reusability, and performance. 

The best way to assess talented Python developers is by using a well-rounded, multi-faceted hiring procedure. This should include a selection of advanced Python questions, alongside behavioral tests, cognitive assessments, and more. 

TestGorilla is a leading pre-employment screening platform that can help you identify the best candidates for your open position. We have a library containing more than 300 tests that you can use in your hiring campaign, including hard skills, soft skills, and behavioral assessments. 

You can use up to five of these tests alongside custom interview questions to screen candidates. Here are some of the tests you might consider incorporating to help you hire advanced Python developers: 

Python skills tests  

Python (Coding): Entry-Level Algorithms test

Python (Working With Arrays) test

Python (Coding): Data Structures and Objects test 

Python (Coding): Debugging test

Cognitive ability tests , such as the Problem Solving test or the Critical Thinking test . These can help you understand how applicants approach and solve complex problems.

Personality tests, such as the Culture Add or DISC test , can provide insights into a candidate’s personality and behavioral tendencies. 

Language ability tests for international hiring campaigns or for a position that requires fluency in a language other than English. 

Once you’ve put your TestGorilla prescreening assessment together, you can share it with candidates and view their results in real time. 

Hiring a Python developer who’s not right for your position can lead to various problems, including inefficient code, bug-prone software, project delays, and lower-quality solutions. Because of this, it’s essential to fully vet every candidate to ensure they’re appropriately skilled and equipped to meet your expectations. 

Using advanced Python interview questions is a great way to separate highly skilled developers from those with more basic experience. On top of this, candidates’ responses and the way they approach advanced questions can provide insights into their thought processes and critical-thinking abilities. 

TestGorilla’s multi-measure approach to hiring enables you to combine advanced Python interview questions with behavioral and job-specific skills tests for a comprehensive evaluation of your candidates. 

To find out more about how TestGorilla can help you hire top talent, you can request a live demo or get started with your Free plan .

Related posts

python assignment expert questions

TestGorilla vs. Maki

TestGorilla vs. Hire success

TestGorilla vs. Hire Success

python assignment expert questions

TestGorilla vs. Pulsifi

Hire the best candidates with TestGorilla

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

python assignment expert questions

Latest posts

python assignment expert questions

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

python assignment expert questions

This checklist covers key features you should look for when choosing a skills testing platform

python assignment expert questions

This resource will help you develop an onboarding checklist for new hires.

python assignment expert questions

How to assess your candidates' attention to detail.

python assignment expert questions

Learn how to get human resources certified through HRCI or SHRM.

python assignment expert questions

Learn how you can improve the level of talent at your company.

python assignment expert questions

Learn how CapitalT reduced hiring bias with online skills assessments.

python assignment expert questions

Learn how to make the resume process more efficient and more effective.

Recruiting metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

python assignment expert questions

Learn how Sukhi decreased time spent reviewing resumes by 83%!

python assignment expert questions

Hire more efficiently with these hacks that 99% of recruiters aren't using.

python assignment expert questions

Make a business case for diversity and inclusion initiatives with this data.

  • Data Engineering
  • Machine Learning
  • RESTful API
  • React Native
  • Elasticsearch
  • Ruby on Rails
  • How It Works

Get Online Python Expert Help in  6 Minutes

Codementor is a leading on-demand mentorship platform, offering help from top Python experts. Whether you need help building a project, reviewing code, or debugging, our Python experts are ready to help. Find the Python help you need in no time.

Get help from vetted Python experts

Python Expert to Help - Kazi Sohan

Within 15 min, I was online with a seasoned engineer who was editing my code and pointing out my errors … this was the first time I’ve ever experienced the potential of the Internet to transform learning.

Tomasz Tunguz Codementor Review

View all Python experts on Codementor

How to get online python expert help on codementor.

Post a Python request

Post a Python request

We'll help you find the best freelance Python experts for your needs.

Review & chat with Python experts

Review & chat with Python experts

Instantly message potential Python expert mentors before working with them.

Start a live session or create a job

Start a live session or create a job

Get Python help by hiring an expert for a single call or an entire project.

Codementor is ready to help you with Python

Online Python expert help

Live mentorship

Freelance Python developer job

Freelance job

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

python-assignment

Here are 21 public repositories matching this topic..., laibanasir / python-assignments.

Mini python programs for practice and better understanding

  • Updated Jul 16, 2019

Github-Classroom-Cybros / Python-Assignments

Add Assignments that can be practised by beginners learning Python.

  • Updated Oct 17, 2019

minhaj-313 / Python-Assignment-10-Questions

Python Assignment 10- Questions

  • Updated May 5, 2024

whonancysoni / pythonadvanced

This repository contains solutions of iNeuron Full Stack Data Science - Python Advanced Assignments.

  • Updated Sep 14, 2022
  • Jupyter Notebook

BIJOY-SUST / DL-Coursera

Python assignments for the deep learning class by Andrew ng on Coursera.

  • Updated Aug 31, 2021

edyoda / python-assignments

  • Updated Oct 15, 2020

Viztruth / Scientific-GUI-Calculator-FULL-CODE

GUI calculator built using Python’s Tkinter module that allows users to interact using buttons for performing mathematical operations.

  • Updated Jun 26, 2023

whonancysoni / pythonbasics

This repository contains solutions of iNeuron Full Stack Data Science - Python Basics Assignments.

  • Updated Aug 7, 2022

BIJOY-SUST / ML-Coursera

Welcome to a tour of Machine Learning. Python assignments for the machine learning class by Andrew ng on Coursera.

mhamzap10 / Python

This includes Python Assignments and Tasks done for AI program of PIAIC

  • Updated Jul 17, 2019

bbagchi97 / PythonAssignment-Sem1

All the assignments of Python Lab - Semester 1, MCA, SIT

  • Updated Mar 15, 2021

abhrajit2004 / Python-Lab-Assignment

These are some Python programs which I have written in my university practical classes. Hope you will get some benefit.

  • Updated Feb 4, 2024

Imteyaz5161 / Python-Assignment

Assignment python Theory & Practical

  • Updated Mar 17, 2023

montimaj / Python_Practice

Python assignments

  • Updated Mar 25, 2018

Jitendra1mp4 / prsu-mca-python-assignment

This repository comprises the Python assignments completed by Jitendra as part of the MCA program at PRSU.

  • Updated Jun 1, 2024

MUHAMMADZUBAIRGHORI110 / PIAIC-ASSIGNMENTS

PYTHON-ASSIGNMENT

  • Updated May 21, 2019

yasharth-ai / ProbAssignment

  • Updated Dec 18, 2019

Progambler227788 / Game-of-Life

Conway's Game of Life implementation in Python, with customizable initial patterns and interactive gameplay.

  • Updated Mar 28, 2023

spignelon / python

Python algorithms, assignments and practicals

  • Updated Jul 5, 2023

unrealapex / python-programming

Lab assignments solutions for problems given in my Python programming class(not accepting PRs)

  • Updated May 16, 2022

Improve this page

Add a description, image, and links to the python-assignment topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the python-assignment topic, visit your repo's landing page and select "manage topics."

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Python Operators
  • Precedence and Associativity of Operators in Python
  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic
  • Ternary Operator in Python
  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .

Here are the Assignment Operators in Python with examples.

Assignment Operator

Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.

S ubtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.

M ultiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.

D ivision Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.

M odulus Assignment Operator

The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.

F loor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.

Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.

Bitwise XOR Assignment Operator 

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.

Walrus Operator

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.

Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.

author

Please Login to comment...

Similar reads.

  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Comprehensive Learning Paths
  • 150+ Hours of Videos
  • Complete Access to Jupyter notebooks, Datasets, References.

Rating

101 Pandas Exercises for Data Analysis

  • April 27, 2018
  • Selva Prabhakaran

101 python pandas exercises are designed to challenge your logical muscle and to help internalize data manipulation with python’s favorite package for data analysis. The questions are of 3 levels of difficulties with L1 being the easiest to L3 being the hardest.

python assignment expert questions

You might also like to practice the 101 NumPy exercises , they are often used together.

1. How to import pandas and check the version?

2. how to create a series from a list, numpy array and dict.

Create a pandas series from each of the items below: a list, numpy and a dictionary

3. How to convert the index of a series into a column of a dataframe?

Difficulty Level: L1

Convert the series ser into a dataframe with its index as another column on the dataframe.

4. How to combine many series to form a dataframe?

Combine ser1 and ser2 to form a dataframe.

python assignment expert questions

5. How to assign name to the series’ index?

Give a name to the series ser calling it ‘alphabets’.

6. How to get the items of series A not present in series B?

Difficulty Level: L2

From ser1 remove items present in ser2 .

7. How to get the items not common to both series A and series B?

Get all items of ser1 and ser2 not common to both.

8. How to get the minimum, 25th percentile, median, 75th, and max of a numeric series?

Difficuty Level: L2

Compute the minimum, 25th percentile, median, 75th, and maximum of ser .

9. How to get frequency counts of unique items of a series?

Calculte the frequency counts of each unique value ser .

10. How to keep only top 2 most frequent values as it is and replace everything else as ‘Other’?

From ser , keep the top 2 most frequent items as it is and replace everything else as ‘Other’.

11. How to bin a numeric series to 10 groups of equal size?

Bin the series ser into 10 equal deciles and replace the values with the bin name.

Desired Output

12. How to convert a numpy array to a dataframe of given shape? (L1)

Reshape the series ser into a dataframe with 7 rows and 5 columns

13. How to find the positions of numbers that are multiples of 3 from a series?

Find the positions of numbers that are multiples of 3 from ser .

14. How to extract items at given positions from a series

From ser , extract the items at positions in list pos .

15. How to stack two series vertically and horizontally ?

Stack ser1 and ser2 vertically and horizontally (to form a dataframe).

16. How to get the positions of items of series A in another series B?

Get the positions of items of ser2 in ser1 as a list.

17. How to compute the mean squared error on a truth and predicted series?

Compute the mean squared error of truth and pred series.

18. How to convert the first character of each element in a series to uppercase?

Change the first character of each word to upper case in each word of ser .

19. How to calculate the number of characters in each word in a series?

20. how to compute difference of differences between consequtive numbers of a series.

Difference of differences between the consequtive numbers of ser .

21. How to convert a series of date-strings to a timeseries?

Difficiulty Level: L2

22. How to get the day of month, week number, day of year and day of week from a series of date strings?

Get the day of month, week number, day of year and day of week from ser .

Desired output

23. How to convert year-month string to dates corresponding to the 4th day of the month?

Change ser to dates that start with 4th of the respective months.

24. How to filter words that contain atleast 2 vowels from a series?

Difficiulty Level: L3

From ser , extract words that contain atleast 2 vowels.

25. How to filter valid emails from a series?

Extract the valid emails from the series emails . The regex pattern for valid emails is provided as reference.

26. How to get the mean of a series grouped by another series?

Compute the mean of weights of each fruit .

27. How to compute the euclidean distance between two series?

Compute the euclidean distance between series (points) p and q, without using a packaged formula.

28. How to find all the local maxima (or peaks) in a numeric series?

Get the positions of peaks (values surrounded by smaller values on both sides) in ser .

29. How to replace missing spaces in a string with the least frequent character?

Replace the spaces in my_str with the least frequent character.

30. How to create a TimeSeries starting ‘2000-01-01’ and 10 weekends (saturdays) after that having random numbers as values?

31. how to fill an intermittent time series so all missing dates show up with values of previous non-missing date.

ser has missing dates and values. Make all missing dates appear and fill up with value from previous date.

32. How to compute the autocorrelations of a numeric series?

Compute autocorrelations for the first 10 lags of ser . Find out which lag has the largest correlation.

33. How to import only every nth row from a csv file to create a dataframe?

Import every 50th row of BostonHousing dataset as a dataframe.

34. How to change column values when importing csv to a dataframe?

Import the boston housing dataset , but while importing change the 'medv' (median house value) column so that values < 25 becomes ‘Low’ and > 25 becomes ‘High’.

35. How to create a dataframe with rows as strides from a given series?

36. how to import only specified columns from a csv file.

Import ‘crim’ and ‘medv’ columns of the BostonHousing dataset as a dataframe.

37. How to get the n rows, n columns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.

Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of the dataframe.

38. How to extract the row and column number of a particular cell with given criterion?

Which manufacturer, model and type has the highest Price ? What is the row and column number of the cell with the highest Price value?

39. How to rename a specific columns in a dataframe?

Rename the column Type as CarType in df and replace the ‘.’ in column names with ‘_’.

Desired Solution

40. How to check if a dataframe has any missing values?

Check if df has any missing values.

41. How to count the number of missing values in each column?

Count the number of missing values in each column of df . Which column has the maximum number of missing values?

42. How to replace missing values of multiple numeric columns with the mean?

Replace missing values in Min.Price and Max.Price columns with their respective mean.

43. How to use apply function on existing columns with global variables as additional arguments?

Difficulty Level: L3

In df , use apply method to replace the missing values in Min.Price with the column’s mean and those in Max.Price with the column’s median.

Use Hint from StackOverflow

44. How to select a specific column from a dataframe as a dataframe instead of a series?

Get the first column ( a ) in df as a dataframe (rather than as a Series).

45. How to change the order of columns of a dataframe?

Actually 3 questions.

Create a generic function to interchange two columns, without hardcoding column names.

Sort the columns in reverse alphabetical order, that is colume 'e' first through column 'a' last.

46. How to set the number of rows and columns displayed in the output?

Change the pamdas display settings on printing the dataframe df it shows a maximum of 10 rows and 10 columns.

47. How to format or suppress scientific notations in a pandas dataframe?

Suppress scientific notations like ‘e-03’ in df and print upto 4 numbers after decimal.

48. How to format all the values in a dataframe as percentages?

Format the values in column 'random' of df as percentages.

49. How to filter every nth row in a dataframe?

From df , filter the 'Manufacturer' , 'Model' and 'Type' for every 20th row starting from 1st (row 0).

50. How to create a primary key index by combining relevant columns?

In df , Replace NaN s with ‘missing’ in columns 'Manufacturer' , 'Model' and 'Type' and create a index as a combination of these three columns and check if the index is a primary key.

51. How to get the row number of the nth largest value in a column?

Find the row position of the 5th largest value of column 'a' in df .

52. How to find the position of the nth largest value greater than a given value?

In ser , find the position of the 2nd largest value greater than the mean.

53. How to get the last n rows of a dataframe with row sum > 100?

Get the last two rows of df whose row sum is greater than 100.

54. How to find and cap outliers from a series or dataframe column?

Replace all values of ser in the lower 5%ile and greater than 95%ile with respective 5th and 95th %ile value.

55. How to reshape a dataframe to the largest possible square after removing the negative values?

Reshape df to the largest possible square with negative values removed. Drop the smallest values if need be. The order of the positive numbers in the result should remain the same as the original.

56. How to swap two rows of a dataframe?

Swap rows 1 and 2 in df .

57. How to reverse the rows of a dataframe?

Reverse all the rows of dataframe df .

58. How to create one-hot encodings of a categorical variable (dummy variables)?

Get one-hot encodings for column 'a' in the dataframe df and append it as columns.

59. Which column contains the highest number of row-wise maximum values?

Obtain the column name with the highest number of row-wise maximum’s in df .

60. How to create a new column that contains the row number of nearest column by euclidean distance?

Create a new column such that, each row contains the row number of nearest row-record by euclidean distance.

61. How to know the maximum possible correlation value of each column against other columns?

Compute maximum possible absolute correlation value of each column against other columns in df .

62. How to create a column containing the minimum by maximum of each row?

Compute the minimum-by-maximum for every row of df .

63. How to create a column that contains the penultimate value in each row?

Create a new column 'penultimate' which has the second largest value of each row of df .

64. How to normalize all columns in a dataframe?

  • Normalize all columns of df by subtracting the column mean and divide by standard deviation.
  • Range all columns of df such that the minimum value in each column is 0 and max is 1.

Don’t use external packages like sklearn.

65. How to compute the correlation of each row with the suceeding row?

Compute the correlation of each row of df with its succeeding row.

66. How to replace both the diagonals of dataframe with 0?

Replace both values in both diagonals of df with 0.

67. How to get the particular group of a groupby dataframe by key?

This is a question related to understanding of grouped dataframe. From df_grouped , get the group belonging to 'apple' as a dataframe.

68. How to get the n’th largest value of a column when grouped by another column?

In df , find the second largest value of 'taste' for 'banana'

69. How to compute grouped mean on pandas dataframe and keep the grouped column as another column (not index)?

In df , Compute the mean price of every fruit , while keeping the fruit as another column instead of an index.

70. How to join two dataframes by 2 columns so they have only the common rows?

Join dataframes df1 and df2 by ‘fruit-pazham’ and ‘weight-kilo’.

71. How to remove rows from a dataframe that are present in another dataframe?

From df1 , remove the rows that are present in df2 . All three columns must be the same.

72. How to get the positions where values of two columns match?

73. how to create lags and leads of a column in a dataframe.

Create two new columns in df , one of which is a lag1 (shift column a down by 1 row) of column ‘a’ and the other is a lead1 (shift column b up by 1 row).

74. How to get the frequency of unique values in the entire dataframe?

Get the frequency of unique values in the entire dataframe df .

75. How to split a text column into two separate columns?

Split the string column in df to form a dataframe with 3 columns as shown.

To be continued . .

More Articles

How to convert python code to cython (and speed up 100x), how to convert python to cython inside jupyter notebooks, install opencv python – a comprehensive guide to installing “opencv-python”, install pip mac – how to install pip in macos: a comprehensive guide, scrapy vs. beautiful soup: which is better for web scraping, add python to path – how to add python to the path environment variable in windows, similar articles, complete introduction to linear regression in r, how to implement common statistical significance tests and find the p value, logistic regression – a complete tutorial with examples in r.

Subscribe to Machine Learning Plus for high value data science content

© Machinelearningplus. All rights reserved.

python assignment expert questions

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free sample videos:.

python assignment expert questions

COMMENTS

  1. Python Answers

    ALL Answered. Question #350996. Python. Create a method named check_angles. The sum of a triangle's three angles should return True if the sum is equal to 180, and False otherwise. The method should print whether the angles belong to a triangle or not. 11.1 Write methods to verify if the triangle is an acute triangle or obtuse triangle.

  2. Python Exercises, Practice, Challenges

    These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.

  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 List Exercise with Solution [10 Exercise Questions]

    Exercise 1: Reverse a list in Python. Exercise 2: Concatenate two lists index-wise. Exercise 3: Turn every item of a list into its square. Exercise 4: Concatenate two lists in the following order. Exercise 5: Iterate both lists simultaneously. Exercise 6: Remove empty strings from the list of strings.

  5. Python Exercise with Practice Questions and Solutions

    The best way to learn is by practising it more and more. The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains.

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

    Python Tutorials → In-depth articles and video courses Learning Paths → Guided study plans for accelerated learning Quizzes → Check your learning progress Browse Topics → Focus on a specific area or skill level Community Chat → Learn with other Pythonistas Office Hours → Live Q&A calls with Python experts Podcast → Hear what's new in the world of Python Books →

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

    Return the Sum of Two Numbers. Create a function that takes two numbers as arguments and returns their sum. Examples addition (3, 2) 5 addition (-3, -6) -9 addition (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.

  8. 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.

  9. Python Practice Exercises and Challenges with Solutions

    These bite-sized challenges are perfect for quick practice sessions, making learning Python a breeze. Simply choose an exercise, read the instructions, and start coding! Solutions are available to keep you on the right track. Here are the exercises: Python Basics Exercise with Solutions. Python Input/Output Exercise with Solutions.

  10. Solve Python

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  11. 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.

  12. 35 Python Programming Exercises and Solutions

    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.

  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. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  15. 41 Advanced Python Interview Questions You Must Know

    A virtualenv is what Python developers call an isolated environment for development, running, debugging Python code.; It is used to isolate a Python interpreter together with a set of libraries and settings. Together with pip, it allows develop, deploy and run multiple applications on a single host, each with its own version of the Python interpreter, and a separate set of libraries.

  16. 14 advanced Python interview questions (and answers)

    Answer: The easiest way to copy an object in Python is with the copy module. This enables you to create both shallow copies and deep copies. Shallow copies create new objects without copies of any nested objects. Because of this, changes to nested objects in the original can still affect the copied object.

  17. 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 ...

  18. Python Expert Help (Get help right now)

    Python. Expert Help in. 6 Minutes. Codementor is a leading on-demand mentorship platform, offering help from top Python experts. Whether you need help building a project, reviewing code, or debugging, our Python experts are ready to help. Find the Python help you need in no time. Get help from vetted Python experts.

  19. python-assignment · GitHub Topics · GitHub

    To associate your repository with the python-assignment topic, visit your repo's landing page and select "manage topics." GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.

  20. Assignment Operators in Python

    The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.

  21. 101 Pandas Exercises for Data Analysis

    101 python pandas exercises are designed to challenge your logical muscle and to help internalize data manipulation with python's favorite package for data analysis. The questions are of 3 levels of difficulties with L1 being the easiest to L3 being the hardest. 101 Pandas Exercises. Photo by Chester Ho. You might also like to practice … 101 Pandas Exercises for Data Analysis Read More »

  22. Building a Python GUI Application With Tkinter (Overview)

    Python has a lot of GUI frameworks, but Tkinter is the only framework that's built into the Python standard library. Tkinter has several strengths. It's cross-platform, so the same code works on Windows, macOS, and Linux.Visual elements are rendered using native operating system elements, so applications built with Tkinter look like they belong on the platform where they're run.