Day 11/30 🔹 Problem: Build a calculator using functions 🔹 What I focused on today: Breaking a problem into small reusable functions and controlling flow using a menu 🔹 My Thinking Process: Create separate functions for each operation (add, subtract, multiply, divide) Show a menu to the user Take user choice Call the corresponding function 👉 Functions + menu = clean and organized program 🔹 Inputs I used: Two numbers Operation choice 🔹 Code: def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b == 0: return "Cannot divide by zero" return a / b print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter your choice: ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == "1": print("Result:", add(num1, num2)) elif choice == "2": print("Result:", subtract(num1, num2)) elif choice == "3": print("Result:", multiply(num1, num2)) elif choice == "4": print("Result:", divide(num1, num2)) else: print("Invalid choice") 🔹 Example: Choice = 1, Numbers = 10 and 5 Output → 15 🔹 Key Takeaway: Using functions makes code modular, reusable, and easier to manage, especially when multiple operations are involved #Day11 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving
Building a Calculator with Functions in Python
More Relevant Posts
-
Day 3/30 Comparing options is easy… but choosing the better one requires understanding the logic behind it. 🔹 Problem: Compare Simple Interest and Compound Interest 🔹 What I focused on today: Understanding the difference in calculation logic between simple and compound interest 🔹 My Thinking Process: Simple Interest is calculated only on the principal amount Compound Interest is calculated on principal + accumulated interest Compare both results to see how compounding makes a difference 👉 Even small changes in logic can lead to big differences in output 🔹 Inputs I used: Principal amount Rate of interest Time (in years) 🔹 Code: principal = float(input("Enter principal amount: ")) rate = float(input("Enter rate of interest: ")) time = float(input("Enter time (in years): ")) # Simple Interest simple_interest = (principal * rate * time) / 100 # Compound Interest amount = principal * (1 + rate / 100) ** time compound_interest = amount - principal print("Simple Interest:", simple_interest) print("Compound Interest:", compound_interest) 🔹 Example: Principal = 1000, Rate = 10%, Time = 2 years Simple Interest = 200 Compound Interest = 210 🔹 Key Takeaway: Compound interest grows faster because it builds on previous interest, not just the original amount #Day3 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving
To view or add a comment, sign in
-
Callbacks are one of those concepts that seem simple at first, but become incredibly powerful once you start building real applications. At its core, a callback is just a function passed into another function, designed to run when a certain event happens or a task completes. This pattern is especially important in async programming, where you don't want your program to pause while waiting for something like data from an API or user input. But where callbacks really clicked for me was when I started using Plotly Dash. In Dash, callbacks are the backbone of interactivity. Instead of writing step-by-step instructions, you define relationships: "When this input changes → update that output." A user selects a value from a dropdown. A graph updates instantly. You don't manually trigger anything, Dash calls your function behind the scenes. This shifts your mindset from: "Do this, then do that..." To: "If this happens, respond like this." It's a small conceptual shift. But it opens the door to building dynamic, reactive apps with surprisingly little code. If you're learning data visualization or building dashboards — understanding callbacks is a game changer. #Python #Plotly #PlotlyDash #DataVisualization #Programming
To view or add a comment, sign in
-
-
🚀 Stop looping through your DataFrames! I recently refactored a script processing 10 million rows. We were using a standard row-wise loop, which was choking our CI/CD pipeline and causing memory spikes. Before optimisation: for i, row in df.iterrows(): df.at[i, 'tax_total'] = row['price'] * 1.08 if row['state'] == 'NY' else row['price'] After optimisation: import numpy as np conditions = [df['state'] == 'NY'] choices = [df['price'] * 1.08] df['tax_total'] = np.select(conditions, choices, default=df['price']) Performance gain: 45x faster and 90% lower memory usage. By moving from row-wise iteration to NumPy’s vectorized selection, we eliminated the Python-level overhead entirely. The code is not only faster but cleaner and more readable for the rest of the team. Vectorization turns O(n) Python operations into high-performance C-level loops. It’s the single biggest quick win you can apply to any data pipeline. Have you ever seen a loop-heavy process that you successfully migrated to vectorized operations? #DataEngineering #Python #Pandas #PerformanceTuning #CodingTips
To view or add a comment, sign in
-
My new ebook just dropped. 👇 I spent weeks documenting the exact Claude Code automations our team uses to save 20 hours every week. The result: "Automate Everything" — 10 copy-paste automations for dev teams who are tired of doing manually what AI can do in seconds. What's inside: → Auto-triage GitHub issues (saves ~3 hrs/wk) → PR code review bot (saves ~5 hrs/wk) → Unit test generator (saves ~4 hrs/wk) → + 7 more production-ready automations Every automation includes a workflow diagram + Python/Bash code you can drop into your repo today. No fluff. Instant download. 🔗 https://lnkd.in/dvCxkpDp #ClaudeCode #AIAutomation #DevTools #Productivity #SoftwareEngineering
To view or add a comment, sign in
-
A small constraint can completely change the algorithm you need. Spent last weekend revisiting an algorithm I find genuinely beautiful: feasibility circulation on flow networks with lower bounds. Take vehicle assignment: If every vehicle only has a maximum capacity, standard max-flow works nicely. But if every vehicle also has a minimum capacity, the problem becomes more interesting. Now the question shifts from simple capacity to overall feasibility. Each assignment must not only fit within limits, but also justify using the vehicle at all. That is where feasibility circulation with lower bounds comes in. The problem setup: Assign exactly T people to a set of vehicles where: • each vehicle has a minimum and maximum capacity • each person has a maximum walking distance to a pickup point • the final assignment must satisfy all constraints The minimum capacity constraint is what makes the problem interesting. Standard max-flow handles upper bounds naturally, but lower bounds need a different modelling approach. The trick is a reduction: Convert each lower bound into a node demand, add a super-source and super-sink, then check whether max-flow can satisfy all demands. - If it can, the original assignment is feasible. - If it cannot, no valid assignment exists. I implemented the solution in Python with test cases and an independent verifier to check correctness. Time complexity: O(S·T + L + R log L) Repo and README walking through the algorithm: https://lnkd.in/gmQXYkbB #algorithms #python #operationsresearch #optimization
To view or add a comment, sign in
-
Day 6/10 🚀 This is where your data starts to take shape. Collections — the backbone of every Python program. Without the right one? Slower code, messy logic. With the right one? Faster lookups, cleaner design. 📋 What I covered today: 01 → Lists — slicing & comprehensions 02 → Tuples — immutability & unpacking 03 → Dictionaries — CRUD & O(1) lookup 04 → Sets — unique values & operations 05 → Frozenset 06 → Advanced — defaultdict, Counter, namedtuple 07 → Iterators — iter() & next() 08 → Mini Project — Inventory Management System Built a simple system using dictionaries to manage stock & pricing — a real-world pattern used in inventory and data pipelines. Day 1 ✅ Day 2 ✅ Day 3 ✅ Day 4 ✅ Day 5 ✅ Day 6 ✅ 4 more to go. Drop a 🐍 if you’ve ever used a list when a set would’ve been better 😄 #Python #Collections #DataEngineering #LearningInPublic #CleanCode #10DaysOfPython #DataStructures
To view or add a comment, sign in
-
Day 7/30 🔹 Problem: Split expenses among friends (equal & custom split) 🔹 What I focused on today: Handling multiple scenarios based on user choice 🔹 My Thinking Process: Take total expense and number of people Ask user how they want to split (equal or custom) If equal → divide total by number of people If custom → take individual contributions 👉 Same problem, different approaches based on user need 🔹 Inputs I used: Total expense Number of people Choice (equal/custom) Individual amounts (for custom split) 🔹 Code: total = float(input("Enter total expense: ")) people = int(input("Enter number of people: ")) choice = input("Enter '1' for equal split or '2' for custom split: ") # Equal Split if choice == "1": share = total / people print("Each person should pay:", share) # Custom Split elif choice == "2": sum_amount = 0 for i in range(people): amount = float(input("Enter amount paid: ")) sum_amount = sum_amount + amount if sum_amount == total: print("Expenses match the total.") else: print("Amounts do not match total.") else: print("Invalid choice") 🔹 Example: Total = 1000, People = 4 Equal → Each pays 250 🔹 Key Takeaway: Real-world problems often need flexible logic to handle different scenarios, not just one fixed solution #Day7 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving
To view or add a comment, sign in
-
I often see Excel used extensively among scientists, and for good reasons. It's accessible, visual, and fast to get started with. But as analyses grow, a few things start to bite: - Debugging is hard. Logic is scattered across cells and sheets, with no easy way to write a test to catch when something breaks. - Change tracking is limited (and optional!). Who changed what, and when? - Data and logic live in the same file. One accidental keystroke can silently corrupt the underlying data, and it's up to the user to set up protections (i.e., lock cells) every time. A Python or R workflow with Git handles all of this pretty naturally. Code is testable, every change is tracked and reversible, and raw data stays separate from analysis logic. Not the right fit for every situation, but worth considering as projects get more complex. #ResearchSoftware #Reproducibility #ScientificComputing
To view or add a comment, sign in
-
I often see Excel used extensively among scientists, and for good reasons. It's accessible, visual, and fast to get started with. But as analyses grow, a few things start to bite: - Debugging is hard. Logic is scattered across cells and sheets, with no easy way to write a test to catch when something breaks. - Change tracking is limited (and optional!). Who changed what, and when? - Data and logic live in the same file. One accidental keystroke can silently corrupt the underlying data, and it's up to the user to set up protections (i.e., lock cells) every time. A Python or R workflow with Git handles all of this pretty naturally. Code is testable, every change is tracked and reversible, and raw data stays separate from analysis logic. Not the right fit for every situation, but worth considering as projects get more complex. #ResearchSoftware #Reproducibility #ScientificComputing
To view or add a comment, sign in
-
📁 Day 24: Mastering File Systems & Mail Merging I just automated a tedious administrative task by building a Mail Merge program that handles file I/O and string manipulation with ease! 💡 Fun Fact: The concept of "Mail Merge" dates back to the 1970s with early word processors like WordStar, saving humans millions of hours by separating the content from the contact list. 🚀 Key Features: • File Automation: Reads template files and recipient lists dynamically. • String Cleaning: Uses .strip() and .replace() to personalize content. • Scalable Output: Automatically generates and saves unique letters for every name. Explore the automation logic here: 🔗https://lnkd.in/gwdWmATu #Python #Automation #FileHandling #PythonProjects #Coding #100DaysOfCode
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development