w3resource

Python Basic (Part -I) - Exercises, Practice, Solution

Python Basic Exercises for Beginners

150 basic exercises/problems with solutions

[An editor is available at the bottom of the page to write and execute the scripts.  Go to the editor ]

1. Formatted Twinkle Poem

Write a Python program to print the following string in a specific format (see the output).
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
Output :

Twinkle, twinkle, little star,
	How I wonder what you are! 
		Up above the world so high,   		
		Like a diamond in the sky. 
Twinkle, twinkle, little star, 
	How I wonder what you are

Click me to see the sample solution

2. Python Version Checker

Write a Python program to find out what version of Python you are using.
Click me to see the sample solution

3. Current DateTime Display

Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014-07-05 14:34:14
Click me to see the sample solution

4. Circle Area Calculator

Write a Python program that calculates the area of a circle based on the radius entered by the user.
Sample Output :
r = 1.1
Area = 3.8013271108436504
Click me to see the sample solution

5. Reverse Full Name

Write a Python program that accepts the user's first and last name and prints them in reverse order with a space between them.
Click me to see the sample solution

6. List and Tuple Generator

Write a Python program that accepts a sequence of comma-separated numbers from the user and generates a list and a tuple of those numbers.
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
Click me to see the sample solution

7. File Extension Extractor

Write a Python program that accepts a filename from the user and prints the extension of the file.
Sample filename : abc.java
Output : java
Click me to see the sample solution

8. First and Last Colors

Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
Click me to see the sample solution

9. Exam Schedule Formatter

Write a Python program to display the examination schedule. (extract the date from exam_st_date).
exam_st_date = (11, 12, 2014)
Sample Output : The examination will start from : 11 / 12 / 2014
Click me to see the sample solution

10. Number Expansion Calculator

Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result :
615
Click me to see the sample solution

11. Function Documentation Printer

Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).
Sample function : abs()
Expected Result
:
abs(number) -> number
Return the absolute value of the argument.
Click me to see the sample solution

12. Monthly Calendar Display

Write a Python program that prints the calendar for a given month and year.
Note : Use 'calendar' module.
Click me to see the sample solution

13. Multi-line Here Document

Write a Python program to print the following 'here document'.
Sample string :
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
Click me to see the sample solution

14. Days Between Dates

Write a Python program to calculate the number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
Click me to see the sample solution

15. Sphere Volume Calculator

Write a Python program to get the volume of a sphere with radius six.
Click me to see the sample solution

16. Difference from 17

Write a Python program to calculate the difference between a given number and 17. If the number is greater than 17, return twice the absolute difference.
Click me to see the sample solution

17. Number Range Tester

Write a Python program to test whether a number is within 100 of 1000 or 2000.
Click me to see the sample solution

18. Triple Sum Calculator

Write a Python program to calculate the sum of three given numbers. If the values are equal, return three times their sum.
Click me to see the sample solution

19. Prefix "Is" String Modifier

Write a Python program to get a newly-generated string from a given string where "Is" has been added to the front. Return the string unchanged if the given string already begins with "Is".
Click me to see the sample solution

20. String Copy Generator

Write a Python program that returns a string that is n (non-negative integer) copies of a given string.
Click me to see the sample solution

21. Even or Odd Checker

Write a Python program that determines whether a given number (accepted from the user) is even or odd, and prints an appropriate message to the user.
Click me to see the sample solution

22. Count 4 in List

Write a Python program to count the number 4 in a given list.
Click me to see the sample solution

23. String Prefix Copies

Write a Python program to get n (non-negative integer) copies of the first 2 characters of a given string. Return n copies of the whole string if the length is less than 2.
Click me to see the sample solution

24. Vowel Tester

Write a Python program to test whether a passed letter is a vowel or not.
Click me to see the sample solution

25. Value in Group Tester

Write a Python program that checks whether a specified value is contained within a group of values.
Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False

Click me to see the sample solution

26. List Histogram

Write a Python program to create a histogram from a given list of integers.
Click me to see the sample solution

27. List to String Concatenator

Write a Python program that concatenates all elements in a list into a string and returns it.
Click me to see the sample solution

28. Even Numbers Until 237

Write a Python program to print all even numbers from a given list of numbers in the same order and stop printing any after 237 in the sequence.
Sample numbers list :

numbers = [    
    386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 
    399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 
    815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 
    958,743, 527
    ]

Click me to see the sample solution

29. Unique Colors Finder

Write a Python program that prints out all colors from color_list_1 that are not present in color_list_2.
Test Data :
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
Expected Output :
{'Black', 'White'}
Click me to see the sample solution

30. Triangle Area Calculator

Write a Python program that will accept the base and height of a triangle and compute its area.
Click me to see the sample solution

31. GCD Calculator

Write a Python program that computes the greatest common divisor (GCD) of two positive integers.
Click me to see the sample solution

32. LCM Calculator

Write a Python program to find the least common multiple (LCM) of two positive integers.
Click me to see the sample solution

33. Triple Sum with Equality Rule

Write a Python program to sum three given integers. However, if two values are equal, the sum will be zero.
Click me to see the sample solution

34. Conditional Sum to 20

Write a Python program to sum two given integers. However, if the sum is between 15 and 20 it will return 20.
Click me to see the sample solution

35. Equality or 5 Rule Checker

Write a Python program that returns true if the two given integer values are equal or their sum or difference is 5.
Click me to see the sample solution

36. Add Integers Validator

Write a Python program to add two objects if both objects are integers.
Click me to see the sample solution

37. Personal Info Formatter

Write a Python program that displays your name, age, and address on three different lines.
Click me to see the sample solution

38. Expression Solver

Write a Python program to solve (x + y) * (x + y).
Test Data : x = 4, y = 3
Expected Output : (4 + 3) ^ 2) = 49
Click me to see the sample solution

39. Future Value Calculator

Write a Python program to compute the future value of a specified principal amount, rate of interest, and number of years.
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
Click me to see the sample solution

40. Distance Between Points

Write a Python program to calculate the distance between the points (x1, y1) and (x2, y2).
Click me to see the sample solution

41. File Existence Checker

Write a Python program to check whether a file exists.
Click me to see the sample solution

42. Shell Mode Detector

Write a Python program to determine if a Python shell is executing in 32bit or 64bit mode on OS.
Click me to see the sample solution

43. OS and Platform Info

Write a Python program to get OS name, platform and release information.
Click me to see the sample solution

44. Python Site Packages Locator

Write a Python program to locate Python site packages.
Click me to see the sample solution

45. External Command Runner

Write a Python program that calls an external command.
Click me to see the sample solution

46. File Path and Name Finder

Write a Python program to retrieve the path and name of the file currently being executed.
Click me to see the sample solution

47. CPU Count Finder

Write a Python program to find out the number of CPUs used.
Click me to see the sample solution

48. String to Numeric Parser

Write a Python program to parse a string to float or integer.
Click me to see the sample solution

49. Directory Files Lister

Write a Python program to list all files in a directory.
Click me to see the sample solution

50. Print Without Newline

Write a Python program to print without a newline or space.
Click me to see the sample solution

51. Program Profiler

Write a Python program to determine the profiling of Python programs.
Note: A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.
Click me to see the sample solution

52. Print to STDERR

Write a Python program to print to STDERR.
Click me to see the sample solution

53. Access Environment Variables

Write a Python program to access environment variables.
Click me to see the sample solution

54. Get Current Username

Write a Python program to get the current username.
Click me to see the sample solution

55. Find Local IPs

Write a Python program to find local IP addresses using Python's stdlib.
Click me to see the sample solution

56. Console Dimensions

Write a Python program to get the height and width of the console window.
Click me to see the sample solution

57. Method Execution Time

Write a Python program to get the execution time of a Python method.
Click me to see the sample solution

58. Sum of First n Positives

Write a Python program to sum the first n positive integers.
Click me to see the sample solution

59. Height to Centimeters

Write a Python program to convert height (in feet and inches) to centimeters.
Click me to see the sample solution

60. Triangle Hypotenuse Calculator

Write a Python program to calculate the hypotenuse of a right angled triangle.
Click me to see the sample solution

61. Feet to Other Units

Write a Python program to convert the distance (in feet) to inches, yards, and miles.
Click me to see the sample solution

62. Time to Seconds Converter

Write a Python program to convert all units of time into seconds.
Click me to see the sample solution

63. Absolute File Path Finder

Write a Python program to get an absolute file path.
Click me to see the sample solution

64. File Timestamps

Write a Python program that retrieves the date and time of file creation and modification.
Click me to see the sample solution

65. Seconds to DHMS Converter

Write a Python program that converts seconds into days, hours, minutes, and seconds.
Click me to see the sample solution

66. BMI Calculator

Write a Python program to calculate the body mass index.
Click me to see the sample solution

67. Pressure Unit Converter

Write a Python program to convert pressure in kilopascals to pounds per square inch, a millimeter of mercury (mmHg) and atmosphere pressure.
Click me to see the sample solution

68. Sum of Digits

Write a Python program to calculate sum of digits of a number.
Click me to see the sample solution

69. Sort Three Numbers

Write a Python program to sort three integers without using conditional statements and loops.
Click me to see the sample solution

70. Sort Files by Date

Write a Python program to sort files by date.
Click me to see the sample solution

71. Directory Listing by Creation Date

Write a Python program to get a directory listing, sorted by creation date.
Click me to see the sample solution

72. Math Module Details

Write a Python program to get the details of the math module.
Click me to see the sample solution

73. Line Midpoint Calculator

Write a Python program to calculate the midpoints of a line.
Click me to see the sample solution

74. Word Hasher

Write a Python program to hash a word.
Click me to see the sample solution

75. Copyright Information

Write a Python program to get the copyright information and write Copyright information in Python code.
Click me to see the sample solution

76. Command-line Arguments

Write a Python program to get the command-line arguments (name of the script, the number of arguments, arguments) passed to a script.
Click me to see the sample solution

77. Endianness Checker

Write a Python program to test whether the system is a big-endian platform or a little-endian platform.
Click me to see the sample solution

78. List Built-in Modules

Write a Python program to find the available built-in modules.
Click me to see the sample solution

79. Object Size Finder

Write a Python program to get the size of an object in bytes.
Click me to see the sample solution

80. Current Recursion Limit

Write a Python program to get the current value of the recursion limit.
Click me to see the sample solution

81. Concatenate Strings

Write a Python program to concatenate N strings.
Click me to see the sample solution

82. Sum of Container Items

Write a Python program to calculate the sum of all items of a container (tuple, list, set, dictionary).
Click me to see the sample solution

83. List Greater-Than Test

Write a Python program to test whether all numbers in a list are greater than a certain number.
Click me to see the sample solution

84. Character Frequency Counter

Write a Python program to count the number of occurrences of a specific character in a string.
Click me to see the sample solution

85. File or Directory Checker

Write a Python program to check whether a file path is a file or a directory.
Click me to see the sample solution

86. Character ASCII Value

Write a Python program to get the ASCII value of a character.
Click me to see the sample solution

87. File Size Finder

Write a Python program to get the size of a file.
Click me to see the sample solution

88. Sum Expression Printer

Given variables x=30 and y=20, write a Python program to print "30+20=50".
Click me to see the sample solution

89. Conditional Action

Write a Python program to perform an action if a condition is true.
Given a variable name, if the value is 1, display the string "First day of a Month!" and do nothing if the value is not equal.
Click me to see the sample solution

90. Self-replicating Program

Write a Python program to create a copy of its own source code.
Click me to see the sample solution

91. Swap Variables

Write a Python program to swap two variables.
Click me to see the sample solution

92. Special Characters in String

Write a Python program to define a string containing special characters in various forms.
Click me to see the sample solution

93. Object Identity and Type

Write a Python program to get the Identity, Type, and Value of an object.
Click me to see the sample solution

94. String Bytes to Integers

Write a Python program to convert the bytes in a given string to a list of integers.
Click me to see the sample solution

95. Check if String is Numeric

Write a Python program to check whether a string is numeric.
Click me to see the sample solution

96. Print Call Stack

Write a Python program to print the current call stack.
Click me to see the sample solution

97. List Special Variables

Write a Python program to list the special variables used in the language.
Click me to see the sample solution

98. Get System Time

Write a Python program to get system time.

Note : The system time is important for debugging, network information, random number seeds, or something as simple as program performance.
Click me to see the sample solution

99. Clear Terminal

Write a Python program to clear the screen or terminal.
Click me to see the sample solution

100. Get Host Name

Write a Python program to get the name of the host on which the routine is running.
Click me to see the sample solution

101. URL Content Printer

Write a Python program to access and print a URL's content to the console.
Click me to see the sample solution

102. System Command Output

Write a Python program to get system command output.
Click me to see the sample solution

103. Extract Filename

Write a Python program to extract the filename from a given path.
Click me to see the sample solution

104. Process Group and User IDs

Write a Python program to get the effective group id, effective user id, real group id, and a list of supplemental group ids associated with the current process.
Note: Availability: Unix.
Click me to see the sample solution

105. User Environment Retriever

Write a Python program to get the users environment.
Click me to see the sample solution

106. Path Extension Splitter

Write a Python program to divide a path by the extension separator.
Click me to see the sample solution

107. File Properties Retriever

Write a Python program to retrieve file properties.
Click me to see the sample solution

108. File or Directory Path Finder

Write a Python program to find the path to a file or directory when you encounter a path name.
Click me to see the sample solution

109. Resolve Path Name

Write a Python program to find the path to a file or directory when you encounter a path name.
Click me to see the sample solution

110. Divisible by 15 Finder

Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.
Click me to see the sample solution

111. Wildcard File Lister

Write a Python program to make file lists from the current directory using a wildcard.
Click me to see the sample solution

112. Remove First List Item

Write a Python program to remove the first item from a specified list.
Click me to see the sample solution

113. Number Input Validator

Write a Python program that inputs a number and generates an error message if it is not a number.
Click me to see the sample solution

114. Filter Positive Numbers

Write a Python program to filter positive numbers from a list.
Click me to see the sample solution

115. List Product Calculator

Write a Python program to compute the product of a list of integers (without using a for loop).
Click me to see the sample solution

116. Print Unicode Characters

Write a Python program to print Unicode characters.
Click me to see the sample solution

117. String Memory Location Test

Write a Python program to prove that two string variables of the same value point to the same memory location.
Click me to see the sample solution

118. Create Bytearray from List

Write a Python program to create a bytearray from a list.
Click me to see the sample solution

119. Round Float to Decimals

Write a Python program to round a floating-point number to a specified number of decimal places.
Click me to see the sample solution

120. String Formatter with Length Limit

Write a Python program to format a specified string and limit the length of a string.
Click me to see the sample solution

121. Variable Defined Checker

Write a Python program to determine if a variable is defined or not.
Click me to see the sample solution

122. Empty Variable Without Deletion

Write a Python program to empty a variable without destroying it.

Sample data: n=20
d = {"x":200}
Expected Output : 0
{}

Click me to see the sample solution

123. Max and Min of Number Types

Write a Python program to determine the largest and smallest integers, longs, and floats.
Click me to see the sample solution

124. Variable Equality Checker

Write a Python program to check whether multiple variables have the same value.
Click me to see the sample solution

125. Sum Collection Counts

Write a Python program to sum all counts in a collection.
Click me to see the sample solution

126. Get Module Object

Write a Python program to get the actual module object for a given object.
Click me to see the sample solution

127. Integer Fits in 64 Bits

Write a Python program to check whether an integer fits in 64 bits.
Click me to see the sample solution

128. Lowercase Letters Checker

Write a Python program to check whether lowercase letters exist in a string.
Click me to see the sample solution

129. Add Leading Zeroes

Write a Python program to add leading zeroes to a string.
Click me to see the sample solution

130. Double Quotes String Display

Write a Python program that uses double quotes to display strings.
Click me to see the sample solution

131. Split Variable Length String

Write a Python program to split a variable length string into variables.
Click me to see the sample solution

132. List Home Directory

Write a Python program to list the home directory without an absolute path.
Click me to see the sample solution

133. Program Runtime Calculator

Write a Python program to calculate the time runs (difference between start and current time) of a program.
Click me to see the sample solution

134. Input Two Integers

Write a Python program to input two integers on a single line.
Click me to see the sample solution

135. Print Variable Without Spaces

Write a Python program to print a variable without spaces between values.
Sample value : x =30
Expected output : Value of x is "30"
Click me to see the sample solution

136. Files Only in Directory

Write a Python program to find files and skip directories in a given directory.
Click me to see the sample solution

137. Extract Dictionary Pair

Write a Python program to extract a single key-value pair from a dictionary into variables.
Click me to see the sample solution

138. Boolean to Integer Converter

Write a Python program to convert true to 1 and false to 0.
Click me to see the sample solution

139. IP Address Validator

Write a Python program to validate an IP address.
Click me to see the sample solution

140. Binary with Leading Zeroes

Write a Python program to convert an integer to binary that keeps leading zeros.
Sample data : x=12
Expected output : 00001100
0000001100
Click me to see the sample solution

141. Decimal to Hexadecimal

Write a python program to convert decimal to hexadecimal.
Sample decimal number: 30, 4
Expected output: 1e, 04
Click me to see the sample solution

142. Consecutive Zero-One Checker

Write a Python program to check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones of same length in a given string. Return True/False.
Original sequence: 01010101
Check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones in the said string:
True
Original sequence: 00
Check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones in the said string:
False
Original sequence: 000111000111
Check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones in the said string:
True
Original sequence: 00011100011
Check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones in the said string:
False
Click me to see the sample solution

143. Shell Bit Mode Detector

Write a Python program to determine if the Python shell is executing in 32-bit or 64-bit mode on the operating system.
Click me to see the sample solution

144. Variable Type Checker

Write a Python program to check whether a variable is an integer or string.
Click me to see the sample solution

145. Check List, Tuple, or Set

Write a Python program to test if a variable is a list, tuple, or set.
Click me to see the sample solution

146. Locate Python Module Sources

Write a Python program to find the location of Python module sources.
Click me to see the sample solution

147. Divisibility Tester

Write a Python function to check whether a number is divisible by another number. Accept two integer values from the user.
Click me to see the sample solution

148. Max and Min Without Built-ins

Write a Python function to find the maximum and minimum numbers from a sequence of numbers.
Note: Do not use built-in functions.
Click me to see the sample solution

149. Cube Sum of Smaller Integers

Write a Python function that takes a positive integer and returns the sum of the cube of all positive integers smaller than the specified number.
Click me to see the sample solution

150. Odd Product Pair Checker

Write a Python function to check whether a distinct pair of numbers whose product is odd is present in a sequence of integer values.
Click me to see the sample solution

Python Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/python-basic-exercises.php