Python tasks with answers

Содержание
  1. Practice Python Exercises and Challenges with Solutions
  2. Basic Exercise for Beginners
  3. Python Input and Output Exercise
  4. Python Loop Exercise
  5. Python Functions Exercise
  6. Python String Exercise
  7. Python Data Structure Exercise
  8. Python List Exercise
  9. Python Dictionary Exercise
  10. Python Set Exercise
  11. Python Tuple Exercise
  12. Python Date and Time Exercise
  13. Python OOP Exercise
  14. Python JSON Exercise
  15. Python NumPy Exercise
  16. Python Pandas Exercise
  17. Python Matplotlib Exercise
  18. Random Data Generation Exercise
  19. Python Database Exercise
  20. Exercises for Intermediate developers
  21. Exercise 1: Reverse each word of a string
  22. Exercise 2: Read text file into a variable and replace all newlines with space
  23. Exercise 3: Remove items from a list while iterating
  24. Exercise 4: Reverse Dictionary mapping
  25. Exercise 5: Display all duplicate items from a list
  26. Exercise 6: Filter dictionary to contain keys present in the given list
  27. Exercise 7: Print the following number pattern
  28. Exercise 8: Create an inner function
  29. Exercise 9: Modify the element of a nested list inside the following list
  30. Exercise 10: Access the nested key increment from the following dictionary
  31. Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
  32. Python Date and Time Exercise with Solutions
  33. Python Dictionary Exercise with Solutions
  34. Python Tuple Exercise with Solutions
  35. Python Set Exercise with Solutions
  36. Python if else, for loop, and range() Exercises with Solutions
  37. Python Functions Exercise
  38. Python Input and Output Exercise
  39. Python List Exercise with Solutions
  40. Python JSON Exercise
  41. Python Data Structure Exercise for Beginners
  42. Python String Exercise with Solutions
  43. Python Matplotlib Exercise
  44. Python Pandas Exercise
  45. Python NumPy Exercise
  46. Python Basic Exercise for Beginners
  47. Useful Python Tips and Tricks Every Programmer Should Know
  48. Python random Data generation Exercise
  49. Python Database Programming Exercise
  50. Online Python Code Editor
  51. About PYnative
  52. Explore Python
  53. Follow Us
  54. Legal Stuff
Читайте также:  Css selectors all elements

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics, Data structure, to Data analytics. As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. 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.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve.

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics: Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics: print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics: If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics: Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics: Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics: Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics: random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question:

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string
# Exercise to reverse each word of a string def reverse_words(Sentence): # Split string on whitespace words = Sentence.split(" ") # iterate list and reverse each word using ::-1 new_word_list = [word[::-1] for word in words] # Joining the new list of words res_str = " ".join(new_word_list) return res_str # Given String str1 = "My Name is Jessa" print(reverse_words(str1)) 

Exercise 2: Read text file into a variable and replace all newlines with space

Given: Assume you have a following text file (sample.txt).

Line1 line2 line3 line4 line5

Expected Output:

Line1 line2 line3 line4 line5
  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ‘ ‘ ).

Steps to solve this question: —

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ‘ ‘ ).
  • Display final string
with open('sample.txt', 'r') as file: data = file.read().replace('\n', ' ') print(data)

Exercise 3: Remove items from a list while iterating

Description:

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Expected Output: —

  • Get the list’s size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] i = 0 # get list's size n = len(number_list) # iterate list till i is smaller than n while i < n: # check if number is greater than 50 if number_list[i] >50: # delete current index from list del number_list[i] # reduce the list size n = n - 1 else: # move to next item i = i + 1 print(number_list)

Solution 2: Using for loop and range()

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] for i in range(len(number_list) - 1, -1, -1): if number_list[i] > 50: del number_list[i] print(number_list)

Exercise 4: Reverse Dictionary mapping

Expected Output:

ascii_dict = # Reverse mapping new_dict = print(new_dict)

Exercise 5: Display all duplicate items from a list

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]

Expected Output: —

  1. Use the counter() method of the collection module.
  2. Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1: — Using collections.Counter()

import collections sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80] duplicates = [] for item, count in collections.Counter(sample_list).items(): if count > 1: duplicates.append(item) print(duplicates)
sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80] exist = <> duplicates = [] for x in sample_list: if x not in exist: exist[x] = 1 else: duplicates.append(x) print(duplicates)

Exercise 6: Filter dictionary to contain keys present in the given list

# Dictionary d1 = # Filter dict using following keys l1 = ['A', 'C', 'F']

Expected Output: —

# Dictionary d1 = # Filter dict using following keys l1 = ['A', 'C', 'F'] new_dict = print(new_dict)

Exercise 7: Print the following number pattern

1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

Refer to Print patterns in Python to solve this question.

  • set x = 0
  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop
rows = 5 x = 0 # reverse for loop from 5 to 0 for i in range(rows, 0, -1): x += 1 for j in range(1, i + 1): print(x, end=' ') print('\r')

Exercise 8: Create an inner function

Question description: —

  • Create an outer function that will accept two strings, x and y . ( x= ‘Emma’ and y = ‘Kelly’ .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word ‘developer’ to it.

Expected Output: —

def manipulate(x, y): # concatenate two strings def inner_fun(x, y): return x + y z = inner_fun(x, y) return z + 'Developers' result = manipulate('Emma', 'Kelly') print(result) 

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50]

Expected Output: —

[5, [10, 15, [20, 25, [30, 3500], 40], 45], 50]
list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50] # modify item list1[1][2][2][1] = 3500 # print final result print(list1) # print(list1[1]) = [10, 15, [20, 25, [30, 400], 40], 45] # print(list1[1][2]) = [20, 25, [30, 400], 40] # print(list1[1][2][2]) = [30, 40] # print(list1[1][2][2][1]) = 40

Exercise 10: Access the nested key increment from the following dictionary

emp_dict = < "company": < "employee": < "name": "Jess", "payable": < "salary": 9000, "increment": 12 >> > > print(emp_dict['company']['employee']['payable']['increment'])

Under Exercises: —

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on: December 8, 2021 | 47 Comments

Python Date and Time Exercise with Solutions

Updated on: December 8, 2021 | 9 Comments

Python Dictionary Exercise with Solutions

Python Tuple Exercise with Solutions

Updated on: December 8, 2021 | 83 Comments

Python Set Exercise with Solutions

Updated on: October 20, 2022 | 24 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on: September 6, 2021 | 257 Comments

Python Functions Exercise

Python Input and Output Exercise

Updated on: September 6, 2021 | 89 Comments

Python List Exercise with Solutions

Updated on: December 8, 2021 | 173 Comments

Python JSON Exercise

Updated on: December 8, 2021 | 6 Comments

Python Data Structure Exercise for Beginners

Updated on: December 8, 2021 | 107 Comments

Python String Exercise with Solutions

Updated on: October 6, 2021 | 195 Comments

Python Matplotlib Exercise

Python Pandas Exercise

Python NumPy Exercise

Python Basic Exercise for Beginners

Updated on: September 26, 2022 | 428 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Python random Data generation Exercise

Updated on: December 8, 2021 | 13 Comments

Python Database Programming Exercise

Online Python Code Editor

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com

Источник

Оцените статью