YouTip LogoYouTip

Python 100 Examples

# Python 100 Examples: Practical Programming Exercises Welcome to **YouTip's Python 100 Examples** reference guide. This comprehensive compilation is designed to help developers of all levels master Python through practical, hands-on exercises. While the original exercises were historically tested on Python 2.7, this modern guide has been fully updated and optimized for **Python 3.x**. It covers core programming concepts, mathematical algorithms, data structures, file handling, and built-in libraries. --- ## Categorized Index of the 100 Exercises To help you navigate this extensive collection, we have grouped the 100 classic exercises into logical learning paths: ### 1. Basic Algorithms & Mathematics * **Examples 1–5:** Combinations, tax/bonus calculations, square roots, calendar date calculations, sorting three integers. * **Examples 6–10:** Fibonacci sequence, list copying, multiplication tables, time delays, formatting time. * **Examples 11–15:** Prime number generation, Narcissistic numbers (Armstrong numbers), prime factorization, conditional operators, score grading. * **Examples 16–20:** Date formatting, character counting, sum of series ($a + aa + aaa$), perfect numbers, free-falling ball physics. ### 2. Logic, Loops & Recursion * **Examples 21–25:** Peach-eating monkey puzzle, ping-pong match pairings, diamond pattern printing, fraction series sum, factorial sums. * **Examples 26–30:** Factorial using recursion, string reversal via recursion, age word problems, palindrome checking, digit extraction. ### 3. Data Structures & String Manipulation * **Examples 31–35:** Letter-based weekday guessing, list reversal, list slicing, template string formatting, text styling. * **Examples 36–40:** Prime numbers in a range, selection sort, matrix diagonal sum, inserting into a sorted list, array inversion. ### 4. Scope, Variables & Object-Oriented Programming * **Examples 41–45:** Static variables, auto variables, external variables, static/global variables, class instantiation. * **Examples 46–50:** Macro simulation, bitwise operators (AND, OR, XOR, inversion), shift operators. ### 5. Graphics, GUI & System Operations * **Examples 51–55:** Bitwise mask operations, drawing circles, drawing rectangles, drawing lines, drawing ellipses. * **Examples 56–60:** Creative graphics, drawing polygons, custom patterns, system time retrieval, time formatting. ### 6. Advanced Data Structures & Algorithms * **Examples 61–65:** Pascal's Triangle, string manipulation, dictionary sorting, list-to-dictionary conversion, custom sorting. * **Examples 66–70:** Sorting three numbers, swapping variable values, array rotation, Josephus circle problem, string length calculation. ### 7. Functions, Pointers & Memory Simulation * **Examples 71–75:** Input/output functions, linked list simulation, list reversal, list concatenation, odd/even series sum. * **Examples 76–80:** Function pointers, loop structures, string sorting, structure simulation, division problems. ### 8. Mathematical Puzzles & Number Theory * **Examples 81–85:** Octal to decimal conversion, odd number combinations, division by prime numbers, sum of prime numbers, division puzzles. * **Examples 86–90:** String concatenation, structure output, read-only variables, encryption algorithms, matrix manipulation. ### 9. File I/O & System Integration * **Examples 91–95:** Time module usage, execution time measurement, date calculations, random number generation, file writing. * **Examples 96–100:** Substring counting, file reading/writing, character sorting, file merging, dictionary serialization. --- ## Selected Code Examples & Solutions Below are five highly representative examples from the collection, complete with problem statements, Python 3 code, and detailed explanations. ### Example 1: Permutations and Combinations **Problem:** How many mutual, distinct three-digit numbers can be formed using the digits `1`, `2`, `3`, and `4`? What are they? ```python # Python 3 Solution count = 0 for i in range(1, 5): for j in range(1, 5): for k in range(1, 5): # Ensure that the digits are distinct if (i != j) and (i != k) and (j != k): print(f"{i}{j}{k}") count += 1 print(f"\nTotal number of combinations: {count}") ``` ### Example 11: The Fibonacci Rabbit Problem **Problem:** A pair of rabbits produces a new pair of rabbits every month starting from their third month of life. Assuming no rabbits die, how many pairs of rabbits will there be each month for the first 12 months? (Fibonacci Sequence). ```python # Python 3 Solution f1 = 1 f2 = 1 for i in range(1, 7): print(f"{f1:12d} {f2:12d}", end=" ") if i % 2 == 0: print() # Print a newline every 4 values f1 = f1 + f2 f2 = f1 + f2 ``` ### Example 14: Prime Factorization **Problem:** Decompose a positive integer into its prime factors (e.g., input `90`, output `90 = 2 * 3 * 3 * 5`). ```python def decompose(n): print(f"{n} = ", end="") if not isinstance(n, int) or n <= 0: print("Please enter a valid positive integer.") return elif n == 1: print("1") return while n > 1: for i in range(2, n + 1): if n % i == 0: n = int(n / i) if n == 1: print(i) else: print(f"{i} * ", end="") break # Test the function decompose(90) ``` ### Example 37: Selection Sort **Problem:** Sort 10 numbers entered by the user using the selection sort algorithm. ```python # Python 3 Solution if __name__ == "__main__": N = 10 print("Please enter 10 numbers:") l = [] for i in range(N): l.append(int(input(f"Number {i+1}: "))) print("\nOriginal list:") print(l) # Selection Sort Algorithm for i in range(N - 1): min_idx = i for j in range(i + 1, N): if l < l: min_idx = j # Swap the found minimum element with the first element l, l = l, l print("\nSorted list:") print(l) ``` ### Example 61: Pascal's Triangle **Problem:** Print Pascal's Triangle up to 10 rows. ```python # Python 3 Solution if __name__ == '__main__': a = [] for i in range(10): a.append([]) for j in range(i + 1): a.append(0) for i in range(10): a = 1 a = 1 for i in range(2, 10): for j in range(1, i): a = a + a # Print the formatted triangle for i in range(10): # Print leading spaces for alignment print(" " * (10 - i), end="") for j in range(i + 1): print(f"{a} ", end="") print() ``` --- ## Bonus Case: Finding Prime Numbers up to 100 In addition to the 100 standard exercises, finding prime numbers is a fundamental task in programming interviews and academic courses. ### Python - Get Prime Numbers Within 100 ```python # Python 3 program to find all prime numbers up to 100 primes = [] for num in range(2, 101): is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: primes.append(num) print("Prime numbers between 1 and 100:") print(primes) ``` --- ## Key Considerations for Modern Python Developers When practicing these exercises, keep the following Python 3 best practices in mind: 1. **Division Operators:** In Python 3, `/` performs float division (e.g., `5 / 2 = 2.5`), whereas `//` performs floor integer division (e.g., `5 // 2 = 2`). 2. **Print Function:** Always use `print()` as a function with parentheses. Use the `end` parameter (e.g., `print(val, end=" ")`) to control trailing characters instead of the Python 2 trailing comma. 3. **Range vs. Xrange:** Python 3's `range()` behaves like Python 2's `xrange()`. It returns a lazy iterable sequence, which is highly memory-efficient. 4. **String Encoding:** All strings in Python 3 are Unicode by default, making internationalization and special character handling seamless.
← Python Exercise Example5Python Exercise Example4 β†’