Python Programming Practice Questions
Python Programming Practice Questions
This Python essential exercise is to help Python beginners to learn necessary Python skills quickly. Practice Python basic concepts such as loops, control flow, data types, operators, list, strings, input-output, and built-in functions. Also, See: Python QuizzesPython Basics 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 helps you solve the exercise. When you complete each question, you get more familiar with the basics of Python. Use Online Code Editor to solve exercise questions.
Also, try to solve the basic Python Quiz for beginners Given two integer numbers return their product only if the product is equal to or lower than 1000, else return their sum. Given 1: number1 = 20 number2 = 30 Expected Output: The result is 600 Given 2: number1 = 40 number2 = 30 Expected Output: The result is 70 Refer: Accept user input in
PythonCalculate an Average in Python Show Hint Create a function that will take two numbers as parametersNext, Inside a function, multiply two numbers and save their product in a product variableNext, use the if condition to check if the product >1000. If yes, return the productOtherwise, use the else block to calculate the sum of two numbers
and return it. Show Solution def multiplication_or_sum(num1, num2): # calculate product of two number product = num1 * num2 # check if product is less then 1000 if product <= 1000: return product else: # product is greater than 1000 calculate sum return num1 + num2 # first condition result = multiplication_or_sum(20, 30) print("The result is",
result) # Second condition result = multiplication_or_sum(40, 30) print("The result is", result) Write a program to iterate the first 10 numbers and in each iteration, print the sum of the current and previous number. Expected Output: Printing current and previous number sum in a range(10) Current Number 0 Previous Number 0 Sum: 0 Current
Number 1 Previous Number 0 Sum: 1 Current Number 2 Previous Number 1 Sum: 3 Current Number 3 Previous Number 2 Sum: 5 Current Number 4 Previous Number 3 Sum: 7 Current Number 5 Previous Number 4 Sum: 9 Current Number 6 Previous Number 5 Sum: 11 Current Number 7 Previous Number 6 Sum: 13 Current Number 8 Previous
Number 7 Sum: 15 Current Number 9 Previous Number 8 Sum: 17 Reference article for help: Python range() functionCalculate sum and average in Python Show Hint Create a variable called previous_num and assign it to 0Iterate the first 10 numbers one by one using for loop and range() functionNext, display the current number (i), previous
number, and the addition of both numbers in each iteration of the loop. At last, change the value previous number to current number ( previous_num = i). Show Solution print("Printing current and previous number and their sum in a range(10)") previous_num = 0 # loop from 1 to 10 for i in range(1, 11): x_sum = previous_num + i print("Current
Number", i, "Previous Number ", previous_num, " Sum: ", x_sum) # modify previous number # set it to the current number previous_num = i Write a program to accept a string from the user and display characters that are present at an even index number. For example, str = "pynative" so you should display ‘p’, ‘n’, ‘t’, ‘v’. Expected Output: Orginal
String is pynative Printing only even index chars p n t v Reference article for help: Python Input and Output Show Hint Use Python input() function to accept a string from a user.Calculate the length of string using the len() functionNext, iterate each character of a string using for loop and range() function.Use start = 0, stop = len(s)-1, and step =2.
the step is 2 because we want only even index numbersin each iteration of a loop, use s[i] to print character present at current even index number Show Solution Solution 1: # accept input string from a user word = input('Enter word ') print("Original String:", word) # get the length of a string size = len(word) # iterate a each character of a string #
start: 0 to start with first character # stop: size-1 because index starts with 0 # step: 2 to get the characters present at even index like 0, 2, 4 print("Printing only even index chars") for i in range(0, size - 1, 2): print("index[", i, "]", word[i]) Solution 2: Using list slicing # accept input string from a user word = input('Enter word ') print("Original
String:", word) # using list slicing # convert string to list # pick only even index chars x = list(word) for i in x[0::2]: print(i) Write a program to remove characters from a string starting from zero up to n and return a new string. For example: remove_chars("pynative", 4) so output must be tive. Here we need to remove first four characters from a
string.remove_chars("pynative", 2) so output must be native. Here we need to remove first two characters from a string. Note: n must be less than the length of the string. Show Hint Use string slicing to get the substring.
For example, to remove the first four characters and the remeaning use s[4:]. Show Solution def remove_chars(word, n): print('Original string:', word) x = word[n:] return x print("Removing characters from a string") print(remove_chars("pynative", 4)) print(remove_chars("pynative", 2)) Also, try to solve Python String Exercise Write a function to
return True if the first and last number of a given list is same. If numbers are different then return False. Given: numbers_x = [10, 20, 30, 40, 10] numbers_y = [75, 65, 35, 75, 30] Expected Output: Given list: [10, 20, 30, 40, 10] result is True numbers_y = [75, 65, 35, 75, 30] result is False Show Solution def first_last_same(numberList): print("Given
list:", numberList) first_num = numberList[0] last_num = numberList[-1] if first_num == last_num: return True else: return False numbers_x = [10, 20, 30, 40, 10] print("result is", first_last_same(numbers_x)) numbers_y = [75, 65, 35, 75, 30] print("result is", first_last_same(numbers_y)) Iterate the given list of numbers and print only those numbers
which are divisible by 5 Expected Output: Given list is [10, 20, 33, 46, 55] Divisible by 5 10 20 55 Show Solution num_list = [10, 20, 33, 46, 55] print("Given list:", num_list) print('Divisible by 5:') for num in num_list: if num % 5 == 0: print(num) Also, try to solve Python list Exercise Write a program to find how many times substring “Emma” appears
in the given string. Given: str_x = "Emma is good developer. Emma is a writer" Expected Output: Emma appeared 2 times Show Hint Use string method count(). Show Solution Solution 1: Use the count() method str_x = "Emma is good developer. Emma is a writer" # use count method of a str class cnt = str_x.count("Emma") print(cnt) Solution 2:
Without string method def count_emma(statement): print("Given String: ", statement) count = 0 for i in range(len(statement) - 1): count += statement[i: i + 4] == 'Emma' return count count = count_emma("Emma is good developer. Emma is a writer") print("Emma appeared ", count, "times") 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Hint: Print Pattern using for
loop Show Solution for num in range(10): for i in range(num): print (num, end=" ") #print number # new line after each row to display pattern correctly print("") Write a program to check if the given number is a palindrome number. A palindrome number is a number that is same after reverse. For example 545, is the palindrome numbers Expected
Output: original number 121 Yes. given number is palindrome number original number 125 No. given number is not palindrome number Show Hint Reverse the given number and save it in a different variableUse the if condition to check if the original number and reverse number are the same. If yes, return True. Show Solution def
palindrome(number): print("original number", number) original_num = number # reverse the given number reverse_num = 0 while number > 0: reminder = number % 10 reverse_num = (reverse_num * 10) + reminder number = number // 10 # check numbers if original_num == reverse_num: print("Given number palindrome") else: print("Given
number is not palindrome") palindrome(121) palindrome(125) Create a new list from a two list using the following condition Given a two list of numbers, write a program to create a new list such that the new list should contain odd numbers from the first list and even numbers from the second list. Given: list1 = [10, 20, 25, 30, 35] list2 = [40, 45, 60,
75, 90] Expected Output: result list: [25, 35, 40, 60, 90] Show Hint Create an empty list named result_listIterate first list using a for loopIn each iteration, check if the current number is odd number using num % 2 != 0 formula. If the current number is an odd number, add it to the result listNow, Iterate the first list using a loop.In each iteration, check
if the current number is odd number using num % 2 == 0 formula. If the current number is an even number, add it to the result listprint the result list Show Solution def merge_list(list1, list2): result_list = [] # iterate first list for num in list1: # check if current number is odd if num % 2 != 0: # add odd number to result list result_list.append(num) #
iterate second list for num in list2: # check if current number is even if num % 2 == 0: # add even number to result list result_list.append(num) return result_list list1 = [10, 20, 25, 30, 35] list2 = [40, 45, 60, 75, 90] print("result list:", merge_list(list1, list2)) Note: Try to solve Python list Exercise For example, If the given int is 7536, the output shall
be “6 3 5 7“, with a space separating the digits. Show Solution Use while loop number = 7536 print("Given number", number) while number > 0: # get the last digit digit = number % 10 # remove the last digit and repeat the loop number = number // 10 print(digit, end=" ") Taxable IncomeRate (in %)First $10,0000Next $10,00010The remaining20
Expected Output: For example, suppose the taxable income is 45000 the income tax payable is 10000*0% + 10000*10% + 25000*20% = $6000. Show Solution income = 45000 tax_payable = 0 print("Given income", income) if income <= 10000: tax_payable = 0 elif income <= 20000: # no tax on first 10,000 x = income - 10000 # 10% tax
tax_payable = x * 10 / 100 else: # first 10,000 tax_payable = 0 # next 10,000 10% tax tax_payable = 10000 * 10 / 100 # remaining 20%tax tax_payable += (income - 20000) * 20 / 100 print("Total tax to pay is", tax_payable) Expected Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15
20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 See: How two use nested loops in Python Show Hint Create the outer for loop to iterate numbers from 1 to 10. So total number of iteration of the outer loop is 10.Create a inner
loop to iterate 10 times.For each iteration of the outer loop, the inner loop will execute ten times.In the first iteration of the nested loop, the number is 1.
In the next, it 2. and so on till 10.In each iteration of an inner loop, we calculated the multiplication of two numbers. (current outer number and curent inner number) Show Solution for i in range(1, 11): for j in range(1, 11): print(i * j, end=" ") print("\t\t") * * * * * * * * * * * * * * * Hint: Print Pattern using for loop Show Solution for i in range(6, 0, -1):
for j in range(0, i - 1): print("*", end=' ') print(" ") Note here exp is a non-negative integer, and the base is an integer. Expected output Case 1: base = 2 exponent = 5 2 raises to the power of 5: 32 i.e. (2 *2 * 2 *2 *2 = 32) Case 2: base = 5 exponent = 4 5 raises to the power of 4 is: 625 i.e. (5 *5 * 5 *5 = 625) Show Solution def exponent(base, exp): num
= exp result = 1 while num > 0: result = result * base num = num - 1 print(base, "raises to the power of", exp, "is: ", result) exponent(5, 4) I want to hear from you. What do you think of this basic exercise? If you have better alternative answers to the above questions, please help others by commenting on this exercise. I have shown only 15 questions
in this exercise because we have Topic-specific exercises to cover each topic exercise in detail. Please have a look at it. 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. Practice and Quickly learn Python’s necessary skills by solving simple questions and problems. Topics: Variables, Operators, Loops, String, Numbers, List Solve input and output operations in Python. Also, we practice file handling. Topics: print() and input(), File I/O This Python loop exercise aims
to help developers to practice branching and Looping techniques in Python.
Topics: If-else statements, loop, and while loop. 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. Solve Python String exercise to learn and practice String operations and manipulations. Practice widely used Python
types such as List, Set, Dictionary, and Tuple operations in Python This Python list exercise aims to help Python developers to learn and practice list operations. This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations. This exercise aims to help Python developers to learn and practice set operations.
This exercise aims to help Python developers to learn and practice tuple operations. This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems. Topics: Date, time, DateTime, Calendar. This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and
practice OOP concepts. Topics: Object, Classes, Inheritance Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.
Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics. Practice Data visualization using Python Matplotlib.
Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot. Practice and Learn the various techniques to generate random data in Python. Topics: random module, secrets module, UUID module 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 Given: str = 'My Name is Jessa' Expected Output yM emaN si asseJ Show Hint 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 Show Solution 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 Solution: # 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 Show Hint First, read a text file. Next, use string replace() function to replace all newlines () with space (' '). Show Solution 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 () with space (' '). Display final string with open('sample.txt', 'r') as file: data = file.read().replace('', ' ') 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 Given: number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Expected Output: - [10, 20, 30, 40, 50] Show Hint 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 Show Solution 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 Given: ascii_dict = {'A': 65, 'B': 66, 'C': 67, 'D': 68} Expected Output: {65: 'A', 66: 'B', 67: 'C', 68: 'D'} Show Solution ascii_dict = {'A': 65, 'B': 66, 'C': 67, 'D': 68} #
Reverse mapping new_dict = {value: key for key, value in ascii_dict.items()} print(new_dict) Exercise 5: Display all duplicate items from a list Given: sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80] Expected Output: - [20, 60, 30] Show Hint Use the counter() method of the collection module. Create a dictionary that will maintain the count of each
item of a list. Next, Fetch all keys whose value is greater than 2 Show Solution 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) Solution 2: - 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 Given: # Dictionary d1 = {'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70} # Filter dict using following keys l1 = ['A', 'C', 'F']
Expected Output: - new dict {'A': 65, 'C': 67, 'F': 70} Show Solution # Dictionary d1 = {'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70} # Filter dict using following keys l1 = ['A', 'C', 'F'] new_dict = {key: d1[key] for key in l1} 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. Show Hint 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 Show Solution 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: - EmmaKellyDevelopers Show Solution 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 Given: list1 = [5,
[10, 15, [20, 25, [30, 35], 40], 45], 50] Expected Output: - [5, [10, 15, [20, 25, [30, 3500], 40], 45], 50] Show Solution 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 Given: emp_dict = { "company": { "employee": { "name": "Jess", "payable": { "salary": 9000, "increment": 12 } } } } Show Solution emp_dict = { "company": { "employee": { "name": "Jess", "payable": { "salary": 9000, "increment":
12 } } } } print(emp_dict['company']['employee']['payable']['increment']) Under Exercises: - April 24, 2023 Whether you're just starting your learning journey or looking to brush up before a job interview, getting the right Python practice can make a big difference. Studies on learning have repeatedly shown that people learn best by doing. So here are
79 ways to practice Python online by writing actual code. Practice with Free Python Coding Exercises Click on any of these links to sign up for a free account and dive into interactive online practice exercises where you'll write real code! These exercises are great for beginniners. These are just the tip of the iceberg. We have many more free Python
practice problems. Practice with Online Python Courses If you're looking for more structure, then practicing with Python courses online may be your cup of tea. See below for some recommended courses. Python Introduction Data Analysis and Visualization Data Cleaning Machine Learning Probability and Statistics Throughout these courses, you'll be
given questions and assignments to test your skills. Additionally, some of these courses contain a guided project that allows you to apply everything you've learned. Practice with Python Projects One of the most effective ways to practice Python online is with projects. Here are a few projects you can use to start practicing right now. The links below
will take you to a course that contains the project you're looking for. If these didn't spark your interest, here are plenty of other online Python projects you can try. Practice with Online Python Tutorials If online practice exercises, courses, and projects don't appeal to you, here are a few blog-style tutorials that will help you learn Python. The web is
full of thousands of other beginner Python tutorials, too.
As long as you've got a solid foundation in the Python basics, you can find great practice through many of them. Frequently Asked Questions Where can I practice Python programming? Dataquest.io has dozens of free interactive practice questions, as well as free interactive lessons, project ideas, tutorials, and more. HackerRank is a great site for
practice that’s also interactive. CodingGame is a fun platform for practice that supports Python. Edabit has Python challenges that can be good for practicing or self-testing. You can also practice Python using all of the interactive lessons listed above How can I practice Python at home? Install Python on your machine. You can download it directly
here, or download a program like Anaconda Individual Edition that makes the process easier.
Or you can find an interactive online platform like Dataquest and write code in your browser without installing anything. Find a good Python project or some practice problems to work on. Make detailed plans. Scheduling your practice sessions will make you more likely to follow through. Join an online community. It's always great to get help from a
real person. Reddit has great Python communities, and Dataquest's community is great if you're learning Python data skills. Can I learn Python in 30 days? In 30 days, you can definitely learn enough Python to be able to build some cool things. You won't be able to master Python that quickly, but you could learn to complete a specific project or do
things like automate some aspects of your job. Read more about how long it takes to learn Python. Can I practice Python on mobile? Yes, there are many apps that allow you to practice Python on both iOS and Android. However, this shouldn't be your primary form of practice if you aspire to use Python in your career— it's good to practice installing
and working with Python on desktops and laptops since that's how most professional programming work is done. How quickly can you learn Python? You can learn the fundamentals of Python in a weekend. If you're diligent, you can learn enough to complete small projects and genuinely impact your work within a month or so. Mastering Python takes
much longer, but you don’t need to become a master to get things done! Read more about how long it takes to learn Python.