The code provided here demonstrates the usage of the exec() function in Python for educational purposes only. By providing this code, no responsibility or liability is assumed for any consequences arising from its use. The user is solely responsible for understanding the risks associated with executing dynamic code and should exercise caution when running code provided by others.
"Python Tips and Tricks" is a curated guide offering practical, effective tips for enhancing your Python skills. Each topic includes concise code examples, outputs, and explanations for easy comprehension. Where relevant, links to external resources and official documentation are provided, allowing you to dive deeper. While the content is designed to be accessible, familiarity with basic Python concepts will enhance your experience and enable you to make the most of these tips.
Topics | Description | Links | Level |
---|---|---|---|
Lambda |
Anonymous functions used for short expressions | Lambda | All Levels |
String Functions - strip() |
Removes whitespace from the start and end of a string | Remove Space Character | All Levels |
String Functions - isalpha() / isdigit() / isalnum() |
Checks for alphabetic, digit, or alphanumeric characters | String Checks | All Levels |
String Functions - capitalize() / upper() / lower() / title() |
Modifies text capitalization | String Case Manipulation | All Levels |
String Functions - count() |
Counts occurrences of a substring in a string | Count Of Substring | All Levels |
String Functions - startswith() / endswith() |
Checks if a string starts or ends with a specific substring | String Boundary Check | All Levels |
String Functions - replace() |
Replaces parts of a string with a specified substring | Replace | All Levels |
String Functions - find() / index() |
Finds the position of a substring; raises an error if not found (index() ) |
Substring Locator | All Levels |
String Functions - center() / ljust() / rjust() |
The center(), ljust(), and rjust() methods align a string within a specified width, filling the extra space with a chosen character, either centering, left-aligning, or right-aligning the string. | Text Alignment | All Levels |
String Functions - format_map() |
The format_map() function replaces placeholders in a string with values from a dictionary, allowing for flexible, key-based string formatting without requiring individual variable assignments. | String Formatting | All Levels |
String Functions - partition() / lpartition() / rpartition() |
This example demonstrates how to use partition(), rpartition(), and the concept of lpartition() to split a string into sections based on the first or last occurrence of a separator, allowing for targeted string manipulation. | String Partition | All Levels |
For Loop |
The for...else construct in Python allows you to pair a loop with an else block that executes only if the loop completes without hitting a break statement. This pattern can make code more readable by clearly distinguishing cases where a condition wasn't met during iteration. Here’s how it works: the else block runs if the loop completes all iterations without interruption; if a break is encountered, the else block is skipped. This is especially useful for search tasks, where break exits the loop if a match is found, and else handles the "no match found" case. | for...else Loop | Beginner |
Modulo (%) Operator |
This program uses the modulo % operator to determine divisibility, replacing numbers divisible by 3 with "Fizz," by 5 with "Buzz," and by both with "FizzBuzz," creating a simple yet iconic game for learning conditional logic. | FizzBuzz | Beginner |
Reversing Lists And Strings |
Techniques for reversing the order of elements in lists and strings | Reversing Lists | Beginner |
List Slicing |
This code demonstrates a simple yet useful trick for named list slicing in Python. By defining key parts of a day (morning, afternoon, evening) and associating them with specific slices of a list, the code allows for dynamic access to subsets of a list based on a user-defined key. It is an example of how to combine dictionaries and list slicing to create intuitive and readable code. | Daily Tasks | Beginner |
Difference of sort() and sorted() |
Explains in-place vs. out-of-place sorting in Python | sort() vs sorted() | Beginner |
Useful Function - Random.choice() |
TIt is a magic ball program that generates random answers to yes or no questions it receives from the user with the random.choice method. | Magic 8 | Beginner |
Useful Function - Random.randint() |
This program simulates the roll of a dice using Python's random.randint function, which generates a random integer between 1 and 6. Each time the code runs, it mimics rolling a standard six-sided dice, making it perfect for games or random number generation scenarios. | Dice Roller | Beginner |
Useful Function - Random.uniform() |
This Python program generates a random floating-point number within a specified range using random.uniform(a, b). It demonstrates how to introduce randomness in applications, such as creating delays or simulating unpredictable events. | Reaction Tester | Beginner |
Useful Function - sorted() |
Returns a new sorted list from an iterable | sorted() | Beginner |
Useful Function - insort from bisect library |
Inserts elements into a list in sorted order | Insort | Beginner |
Useful Function - enumerate() |
Adds a counter to an iterable for use in loops | enumerate() | Beginner |
Useful Functions - enumerate() sum() |
This ATM Simulator replicates real-life banking activities like checking balance, depositing money, withdrawing money, and viewing transaction history. It uses built-in functions like input() for user interaction, enumerate() to display transaction history, and sum() to update balances dynamically. It's interactive, practical, and fun! 🏦💵 | enumerate() | Beginner |
Useful Function - join() |
Joins elements of an iterable into a single string, separated by a specified delimiter | join() | Beginner |
Useful Function - set() |
Creates a collection of unique items from an iterable | set() | Beginner |
Useful Function - set() isalpha() sorted() |
This script analyzes the frequency of letters in a given text and displays the results as a simple ASCII bar graph.It first filters out non-alphabetic characters and normalizes the text to lowercase. Then, it calculates the frequency of each letter using a dictionary and visualizes the counts using █ characters. This makes it both functional and visually engaging for quick analysis. | ASCII Frequency Analysis | Beginner |
Useful Function - frozenset() |
Creates an immutable set | frozenset() | Beginner |
Useful Function - zip() |
Combines multiple iterables element-wise | zip() | Beginner |
Useful Function - zip() and zip(*) |
This code demonstrates the use of Python's zip() function to pair elements from two lists into a single iterable. The inventory is displayed as a clean table, and the bonus section showcases how to reverse the process with zip(*zip(...)). This is a simple yet powerful trick for organizing and working with paired data. | zip() and zip(*) | Beginner |
Useful Function - bin() |
Converts an integer to a binary string | bin() | Beginner |
Useful Function - min() |
Returns the smallest item in an iterable | min() | Beginner |
Useful Function - filter() |
Filters elements in an iterable based on a condition | filter() | Beginner |
Useful Functions - filter() and stirng manipulation |
This code checks whether a given string is a palindrome. It normalizes the input by removing non-alphanumeric characters and converting it to lowercase, then compares the processed string with its reverse to determine if they are identical. | Palindrome Checker | Beginner |
Useful Functions - filter() map() and sum() |
This code takes a list of numbers, filters out the even ones using filter() and a lambda function, and calculates their total using sum(). It’s a concise and powerful example of combining built-in Python functions for clean and efficient code! | Sum Of Even Numbers | Beginner |
Useful Function - abs() |
This code calculates the Manhattan distance between two 2D points by summing up the absolute differences of their x and y coordinates, showcasing a practical application of the abs() function. | abs() | Beginner |
Useful Function - all() and any() |
This program uses all() to check if everyone in a group meets a condition (e.g., eligible to vote) and any() to check if at least one person meets the condition. It’s a quick way to validate data in Python. | Voter Eligibility Checker | Beginner |
Simple Text Analysis with set() and len() |
This code extracts unique words from a given text using the set() function and calculates their lengths. It creates a dictionary where keys are the unique words (case-insensitive) and values are their lengths. Simple, efficient, and useful! | analysis with set() and len() | Beginner |
Simple Text Frequency Analysis with collections.Counter |
This beginner-friendly Python program analyzes a given text to identify unique words and count their frequencies, using simple text-cleaning techniques and the powerful Counter function from the collections module. | analysis with collections.Counter | Beginner |
List Comprehension |
This program demonstrates the use of list comprehension, a powerful and concise way to create lists in Python. The code filters even numbers from 1 to (max values +1), calculates their squares, and stores the results in a single line of code. This is a practical example for scenarios where quick filtering and transformation of data are needed, such as generating specific numerical sequences or processing datasets. | even number generator | Beginner |
List And Dictionary Iteration |
A program that demonstrates iteration over a dictionary and a list, matching items from a shopping list with their prices in a price dictionary to calculate the total cost of the shopping. | Grocery Shopping Helper | Beginner |
Dictionary Usage |
This code is Python program that converts distances between different units such as kilometers, miles, meters, and feet using a dictionary of conversion rates. | Unit Converter | Beginner |
Dictionary Usage |
This program manages a list of students and their grades using a Python dictionary. It calculates and displays average grades for each student, demonstrates how to update data,adds new students and delete existing student. This example provides a foundational understanding of dictionary operations and their practical applications in real-world scenarios. | Grade Tracker | Beginner |
Dictionary Navigation Tools |
These methods provide efficient ways to access and iterate over the contents of a dictionary. .items() is ideal for working with both keys and values, .keys() focuses on the dictionary's keys, and .values() allows easy retrieval of all stored values. | Dict Navigation | Beginner |
Dictionary Clear |
The clear() method removes all items from a dictionary, leaving it empty. | dict.clear() | Beginner |
Dictionary Update |
The update() function merges a dictionary with another dictionary or key-value pairs, adding new keys and updating existing ones. | dict.update() | Intermediate |
Dictionary Unpack with ** and format() |
This is a code example that quickly unpacks dictionaries with the **dict statement and sends them as arguments to functions. | Unpack Dictinary with ** | Intermediate |
Dictionary Fromkeys |
The fromkeys() function creates a new dictionary with specified keys and assigns a single value to all of them. | dict.fromkeys() | Intermediate |
Dictionary Usage and get() |
This program uses dictionaries to compare the planned travel budget with the actual expenses for various categories (e.g., food, transport). It calculates and displays the remaining budget or overspending for each category, along with a total budget summary. The code demonstrates intermediate-level dictionary operations, including the get() method and dictionary comprehensions. | Travel Budget Tracker | Intermediate |
Dictionary And List Usage And defaultdict() |
This Python script organizes a list of names alphabetically by their first letter. It uses defaultdict to group names efficiently and displays the results in a clean, user-friendly format. | Auto-Sorting and Grouping Names by First Letter | Intermediate |
sort() , lambda And defaultdict() |
This program uses defaultdict from the collections module, a hidden gem in Python that allows you to avoid key errors by automatically initializing missing keys. In this case, it counts email domains in a list of email addresses, sorts them by frequency, and displays the results. It's a cool and practical tool for analyzing datasets containing email addresses! 🚀 | E-mail Domain Analysis | Intermediate |
Tuple |
This program uses tuples to manage and analyze weekly expenses for various categories. The budget and actual expenses are stored in tuples, and the program calculates whether each category stayed within the budget or not. It also provides a total summary of the budget vs. actual expenses. | Weekly Budget Tracker | Intermediate |
Useful Functions - map(), sum() and lambda |
It is a Python program that recommends increased salaries for employees based on their overtime hours. lambda, map, list built-in Python functions were used. | Salary Suggestion | Intermediate |
Lambda and filter() |
This script uses a lambda function and filter to identify credit card transactions exceeding a set spending limit. It demonstrates the practical application of functional programming for financial data analysis. | Spending Limit Control with lambda and filter() | Intermediate |
Condition Utils |
This code demonstrates how to use the any() and all() functions to evaluate conditions across an iterable. It checks whether at least one condition is met (any) or if all conditions are satisfied (all) within a list, tuple, or generator. These functions are particularly useful for concise and readable logical validations in Python. | Condition Utils | Intermediate |
Useful Function - callable() |
This code demonstrates how callable() identifies objects or functions that can be invoked like functions, including instances of classes with a call method. | callable() | Intermediate |
OOP And Inheritance |
A fully functional Pet Hotel management system with OOP, Inheritance, and error handling! | Pet Hotel | Intermediate |
Itertools Combination And Permutation |
Use permutations and combinations from itertools to explore all possible orders and selections of elements. | Combination And Permutation | Intermediate |
Itertools Combination And math |
This Python program implements Goldbach's conjecture, which states that every even number greater than 2 can be expressed as the sum of two prime numbers. | Goldbach Decomposition | Intermediate |
Itertools Chain |
Demonstrates how itertools.chain flattens nested lists into a single iterable, showcasing its power in simplifying complex data structures. | Chain | Intermediate |
Itertools Cycle |
The itertools.cycle function creates an infinite iterator that repeats the elements of a sequence in order, cycling back to the start when it reaches the end. | Cycle | Intermediate |
Itertools Product |
Generate all possible combinations of Turkish dishes, appetizer, and desserts using itertools.product for menu planning or brainstorming. | Product | Intermediate |
Itertools Accumulate |
This script visualizes a business's daily income, expenses, and cumulative net income over a week. It calculates the daily net income by subtracting expenses from income, then computes the cumulative net total. The data is plotted using matplotlib, showing daily income, expenses, and cumulative net income with custom styling. | Accumulate- Sales Example | Intermediate |
Itertools Reduce |
This code filters even numbers from a list using filter, calculates their squares with map, and sums the squares using reduce, demonstrating functional programming concepts in Python. | Reduce- Sum of Squared Even Numbers | Intermediate |
Itertools next() and yield |
By combining the itertools next() function and the yield keyword, we created a simple animation that waits for the colors in the color array to play on the screen. | Simple Color Animation | Intermediate |
yield |
This script creates a fun emoji-based animation using Python's yield. The emoji_animation generator cycles through a list of emojis, and the display_animation function controls the animation flow. The script uses \r to refresh the same line, creating a seamless visual effect. | Emoji Animation | Intermediate |
Generate Anagram |
This is a Python code that combines the useful functions itertools.permutations(), str.join(), str.strip(), and sorted() to find all anagrams of a given word. | Generate Anagrams | Intermediate |
Math Module - math.sqrt |
This Python program solves quadratic equations by taking user input for the coefficients (a), (b), and (c) of the equation (ax^2 + bx + c = 0). It uses mathematical calculations to determine the discriminant and roots, demonstrating basic to intermediate usage of mathematical functions and error handling in Python. | Solve Quadratic Equation | Intermediate |
Math Module - math.sqrt, math.gcd |
This program generates all Pythagorean triples (a, b, c) such that a^2 + b^2 = c^2 and c ≤ limit. | Pythagorean Triples | Intermediate |
Math Module - math.sqrt, collections.Counter |
This Python code efficiently finds the prime factors of a given number. The loop checks divisors up to the square root of the number, while the final condition (if n > 2 ) ensures that any remaining number greater than 2 (which must be prime) is included in the list of factors. |
Prime Factorization With Exponents | Intermediate |
Math Module - math.factorial and itertools.permutations |
A program that calculates the given r-permutation of an entered word. | rPermute | Intermediate |
Math Module |
This program calculates and visualizes the convergence of Fibonacci sequence ratios to the Golden Ratio as the sequence progresses. | Fibonacci And Golden Ratio | Intermediate |
Math Module |
This function checks if a number is a perfect square by calculating its integer square root and verifying if squaring it returns the original number. | Perfect Square | Intermediate |
Math Module - math.gcd and abs function |
Python script to calculate the GCD (Greatest Common Divisor) and LCM (Least Common Multiple) of two positive integers with input validation. | Greatest Common Divisor and Least Common Multiple | Intermediate |
Math Module - math.hypot And Matplotlib |
This code calculates and visualizes a right triangle based on user-input side lengths. The triangle is drawn with accurate proportions on a coordinate plane using Matplotlib. The hypotenuse is calculated using math.hypot, and the triangle's area is highlighted with a filled color for better visualization. | Perfect Square | Intermediate |
Math Module - math.pow, math.pi, math.cos, math.sin And Matplotlib |
This program calculates the circumference and area of a circle based on user input and visualizes the circle with proper scaling. | Calculator the Circumference and Area of a Circle | Intermediate |
Math Module - math.log And Matplotlib, Numpy |
This program allows users to calculate the logarithm of a positive number with a chosen base (natural, base 10, or custom) and visualize the logarithmic function using matplotlib . It utilizes numpy.linspace to generate a range of values for plotting the logarithmic curve and highlights the input value on the graph. |
Logarithm Calculation And Visualization | Intermediate |
Math Module - math.cos, math.sin, math.tan, math.radians And Matplotlib |
Visualizes a triangle using Matplotlib by plotting its sides with specified lengths and colors. | Cosine Theorem | Intermediate |
Math Module - math.cos, math.sin, math.radians And Matplotlib |
This program calculates triangle sides and angles using the Sine Theorem and visualizes the triangle with its circumcircle. | Sine Theorem | Intermediate |
statistics Module - mean, stdev And Matplotlib |
A Python-based grading system that uses bell curve statistics to assign letter grades to students. | Bell Curve Based Grading | Intermediate |
statistics Module - mean, mode, median, stdev And Matplotlib |
This code generates random customer data for 30 days, calculates basic statistics, and visualizes the data using a bar chart. | Restaurant Statistic | Intermediate |
Matplotlib |
This Python program visualizes daily coffee sales using a bar chart created with Matplotlib. It demonstrates basic data visualization techniques, including adding labels, titles, and annotations for better readability. The program is simple yet effective for beginners learning to work with data visualization libraries. | Sales Visualization | Intermediate |
Matplotlib |
This Python program calculates the area of a polygon using the Shoelace Theorem. It takes user input for the polygon's vertices, checks for invalid entries, computes the area, and visualizes the polygon. | Area Of Polygon With Shoelace Theorem | Intermediate |
Mathplotlib and List, string.translate |
Input text, search words, and visualize word counts in a bar chart. | Choosen Word Frequency | Intermediate |
Numpy Module - numpy.sum and Time module |
A Python code comparing the performance of numpy.sum and the built-in sum function. | sum() vs Numpy.sum() | Intermediate |
Numpy Module - numpy.unique , set() and Time module |
A Python code comparing the set() function and the numpy.unique() function to determine the faster method for removing duplicate elements. | Remove Duplicates Data Faster | Intermediate |
Numpy Module - numpy.convolve and Matplotlib |
This code generates random data, applies a moving average filter, and visualizes the smoothed results using NumPy and Matplotlib. | Moving Average | Intermediate |
Numpy Module - numpy.zeros_like, numpy.round and Matplotlib |
This function plots the original data along with different EMA curves. | Exponential Moving Average | Intermediate |
Numpy Module - numpy.sin, numpy.cos, np.tan, numpy.pi and Matplotlib |
This script generates and visualizes sine and cosine waves using NumPy for mathematical calculations and Matplotlib for plotting, demonstrating the periodic nature of trigonometric functions. | Trigonometric Wave Visualization | Intermediate |
Numpy Module - numpy.linalg.norm, np.linspace, np.meshgrid, np.vectorize and Matplotlib |
This code generates a 3D plot visualizing the Euclidean distance from the origin using NumPy's meshgrid, vectorization, and linear algebra norm functions. | 3D Euclidean Wave Surface | Intermediate |
Numpy Module - numpy.linalg.norm, np.linspace, np.meshgrid, np.vectorize and Matplotlib |
This Python script generates a 3D sine and cosine wave surface based on the Euclidean distance from the origin. Using NumPy and Matplotlib, it visualizes the effect of trigonometric functions on a 2D grid, creating dynamic wave patterns. | 3D Sine - Cosine Waves | Intermediate |
Numpy Module - np.mean, np.arange, np.sum, an.random.randn and Matplotlib |
Linear Regression using the Least Squares Method to find the best-fitting line. | Linear Regression With Least Squares Method | Intermediate |
Numpy Module - numpy.ones, numpy.hstack, numpy.linalg.inv and Matplotlib |
A simple linear regression model to predict coffee sales based on past data | Caffeine Forecast | Intermediate |
Numpy Module - numpy.ones, numpy.hstack, numpy.linalg.inv, numpy.column_stack and Matplotlib |
Implementation of Multiple Linear Regression using the Least Squares Method and the Normal Equation for Optimal Coefficient Estimation | Multiple Linear Regression With Least Squares Method | Intermediate |
Numpy Module - numpy.polynomial.Polynomial and Matplotlib |
This code demonstrates real-world polynomial regression using NumPy to model and predict complex trends on bread sales | Bread Sales Prediction with Polynomial Regression | Intermediate |
Numpy Module - numpy.polynomial.Polynomial and Matplotlib |
This code uses polynomial regression with NumPy to predict future sales trends based on past weekly sales data. | Smart Sales Prediction | Intermediate |
Numpy Module - numpy.polynomial.Polynomial and Matplotlib |
This code predicts future temperatures using polynomial regression based on past temperature data. | Smart Weather Prediction | Intermediate |
Numpy Module - numpy.linalg.norm, numpy.argmin, numpy.argmin, numpy.vstack, numpy.array and Matplotlib |
This code implements K-Means clustering from scratch using NumPy, allowing us to group similar data points into clusters and predict new data points' clusters. | Simple K-Means Clustering | Intermediate |
Numpy Module - numpy.random.uniform and Matplotlib |
Monte Carlo Simulation that estimating π using numpy.random.uniform to random sampling | Monte Carlo Pi | Intermediate |
Numpy Module - numpy.random.randint, numpy.sum, pandas value_counts, pandas.sort_values and Matplotlib |
This simulation rolls a fair six-sided die multiple times (100,000 in this case) and estimates the probability of rolling a 6 by calculating the frequency of occurrence relative to the total rolls. The results are visualized in a bar chart. | Monte Carlo Dice | Intermediate |
Numpy Module - numpy.random.binomial and Matplotlib |
This code simulates a binomial distribution, calculates key statistics such as mean and standard deviation, counts the occurrences of a specified number of successes, and visualizes the distribution using a histogram. | Binomial Distribution | Intermediate |
Memory Usage Check |
Examines memory consumption in Python programs | Memory Usage | Intermediate |
Variables |
Mutable objects can be modified after creation (e.g., lists, dictionaries), while immutable objects cannot be changed once created (e.g., strings, tuples). | Mutable vs Immutable | Intermediate |
is or == |
Explains identity (is ) vs. equality (== ) operators in Python |
== vs is | Intermediate |
Merging Dictionaries |
Shows methods for combining dictionaries in Python | Merge Dictionaries | Intermediate |
Overriding Dictionaries |
This script demonstrates how to combine menus from two restaurants using the | operator in Python dictionaries. If an item exists in both menus, the price from the second menu overrides the first, creating a unified menu with the latest updates. | Override Dictionaries | Intermediate |
Heap |
Covers priority queues and heap data structures in Python | Heap | Intermediate |
Flatten a list |
Techniques for unnesting nested lists | Flatten A list | Intermediate |
Fibonacci Generator with yield |
This code demonstrates two methods to generate the Fibonacci sequence: one using a list for storing all values (memory-intensive but straightforward) and another using a generator with yield to produce values on demand (memory-efficient and ideal for large sequences). | Fibonacci Generator with yield | Intermediate |
File Operations |
Basic file handling, including reading, writing, and managing files | File Operations | Intermediate |
max() + collections.Counter() |
This Python script combines Counter for counting element frequencies and max with a custom key to efficiently find the most frequent element in a list. | max() func | Intermediate |
Text Frequency Analysis with collections.Counter and Matplotlib |
This Python program processes a sample text to test various functionalities, such as text analysis, visualization, or formatting. It can be used to practice working with strings, test text-based algorithms, or perform operations like word counting and sentiment analysis. | Text Frequncy Visualizer | Intermediate |
Text Analysis with WorldCloud, collections.Counter, nltk, Matplotlib |
This Python program performs text analysis by processing a sample text, generating a word cloud visualization, and extracting common words using NLP techniques. | Text Frequncy Visualizer | Intermediate |
Class Method vs Static Method |
This example highlights the difference between @staticmethod for independent tasks and @classmethod for managing class-level data and behaviors. | @classmethod vs @ staticmethod | Intermediate |
Random Module |
This Python script generates a strong, random password using the string and random modules. It ensures the password is secure by including uppercase letters, lowercase letters, digits, and special characters. Users can define the length of the password, and the script guarantees unpredictability by shuffling the characters. | Random Password Generator | Intermediate |
Random Module |
This code generates a random dream vacation plan by selecting a destination, activity, and duration. Every time you run the program, it creates a new unique vacation idea, adding a fun and inspiring touch to your day. | Random Vacation Planner | Intermediate |
Ceasar Chipher |
The Caesar Cipher is one of the simplest and most famous encryption algorithms. It shifts each character in the alphabet by a fixed number of positions, creating an encrypted text that can be reversed with the same shift value. | Ceasar Cipher | Intermediate |
filter(), lambda functions, and the := walrus operator |
This code is of intermediate level, utilizing advanced Python features such as filter(), lambda functions, and the := walrus operator. It demonstrates functional programming concepts, focusing on filtering valid email addresses by checking conditions like the presence of exactly one "@" symbol and a valid domain structure. Understanding these elements requires knowledge of Python's built-in functions and conditional expressions. | E-mail Validation | Intermediate |
:= walrus operator |
This code showcases the assignment expression operator :=, also known as the "walrus operator," which allows assigning a value to a variable as part of an expression. Here, it is used to update the total_spent while simultaneously checking if it exceeds the budget, making the code more concise and readable. | Shopping Limit Tracker | Intermediate |
try - except and Errors |
This script converts currencies safely using a dictionary of exchange rates. It demonstrates the use of try-except to handle errors such as missing exchange rates (KeyError), invalid inputs (ValueError), or unexpected errors (Exception). The finally block ensures a clean termination message is always shown, making it user-friendly. | Currency Converter | Intermediate |
Error Handling And Custom Errors |
This program calculates the Body Mass Index (BMI) and body fat percentage based on the US Navy standards. It classifies individuals into different BMI and body fat categories based on gender, providing a comprehensive evaluation of body composition. | BMI Calculator | Intermediate |
Error Handling And Custom Errors |
This Python program simulates a coffee ordering system with a menu, pricing, and size options. It includes: custom exceptions for invalid coffee types and sizes and a realistic coffee-making delay using time.sleep(2) . |
Coffee Order | Intermediate |
Useful Functions - enumerate(), pop(), append() and try-except) |
This is a simple and interactive To-Do List Manager built with Python. It uses built-in list operations and functions like sorted, append, and pop to let users add, view, sort, and delete tasks, making task management easy and fun! | To Do List Manager | Intermediate |
Error Handling And datetime.now() And timedelta() |
This script simulates a simple book borrowing system in a library. It uses Python's datetime module to calculate and display the borrowing and return dates. It also includes error handling to ensure valid user inputs. | Book Borrowing System | Intermediate |
Error Handling And datetime module and os module |
This Python program is a personal event calendar that allows users to add, view, and save events. It uses the datetime module for date manipulation and os module file handling for persistent event storage, demonstrating intermediate-level Python skills in creating a functional and user-friendly application. | Event Calendar | Intermediate |
today.toordinal() + hash() |
This program generates a personalized motivational quote based on the user's mood, leveraging datetime and random modules to ensure consistent results for the same date and mood combination. | Mood Quotes | Advanced |
Function |
A first-class function is a function treated as a first-class citizen, meaning it can be passed as an argument, returned from another function, and assigned to a variable, just like any other object. This enables flexible and dynamic programming, allowing functions to be used as building blocks within other functions or data structures. | First Class Function | Advanced |
Memoization |
A closure is a function that "remembers" the environment in which it was created, retaining access to variables from its containing scope even after that scope has finished executing. Closures are often used to create factory functions and encapsulate state. | Closures | Advanced |
Effective Use Of Memory |
Generators are a type of iterable in Python that allow you to iterate over a sequence of values, but unlike lists, they generate values on the fly using yield, which makes them memory-efficient. Instead of storing the entire sequence in memory, they produce one item at a time as needed. This is particularly useful for working with large datasets. | Generators | Advanced |
Useful Function - exec() |
The exec() function in Python dynamically executes Python code passed as a string. It can be used to run code that is generated or stored at runtime, making it powerful but also potentially risky, as it can execute arbitrary code. It's typically used for tasks like dynamic code execution or creating code templates. | exec() | Advanced |
Vigenère Cipher |
This code implements the Vigenère Cipher, a polyalphabetic encryption method that uses a keyword to perform letter shifting. It handles both encryption and decryption of text while leaving non-alphabetic characters unaltered. | Vigenère Cipher | Advanced |
Generators - send, next() and yield() |
This code simulates a parking lot system using a Python generator. The parking_lot function uses yield to dynamically manage the parking spots, allowing cars to enter or exit in real-time while keeping track of the lot's state. It demonstrates how yield can pause and resume execution, making it perfect for scenarios like monitoring dynamic systems. The send() method enables communication with the generator, passing actions (like "enter" or "exit") to simulate real-world operations effectively. | Vehicle Entry-Exit to the Parking Lot | Advanced |
Pathlib |
This script organizes files in any given folder into categorized subfolders based on their file extensions. It utilizes the pathlib library for robust and clean path handling. By categorizing files into pre-defined subfolders (e.g., Documents, Images, Videos), it offers a practical and efficient way to keep any directory well-organized with minimal effort. Simply point the script to the desired folder, and it will handle the rest! | File Organizer | Advanced |
os module, psutil module, datetime module |
This Python script logs the square root of the system's uptime along with the current date and time to a file. It uses the psutil library for cross-platform uptime calculation, ensuring compatibility with both Windows and Linux systems. | System Performance Log | Advanced |
For more detailed information and resources on the topics covered in this repository, consider referring to the following sources:
-
Python 3.10.2 Documentation - Built-in Functions: Official documentation page for built-in functions in Python 3.10.2.
-
Python Documentation: Official Python documentation homepage for accessing additional resources and information.