PYTHON JOURNEY - Day 44 / 50..!! TOPIC – Functions (Basics) Today I explored Functions — the building blocks of reusable code. Instead of writing the same logic over and over, I can now wrap it in a function and call it whenever I need it! 1. Defining a Function We use the def keyword followed by the function name and parentheses. Python def greet(): print("Hello! Welcome to Day 44.") # Calling the function greet() 2. Functions with Parameters You can pass information into a function so it can perform dynamic tasks. Python def welcome_user(name): print(f"Hi {name}, keep up the great coding!") welcome_user("Srikanth") 3. The return Statement Functions can send data back to the main part of the program. Python def add_numbers(a, b): return a + b result = add_numbers(10, 20) print(f"The total is: {result}") Why Use Functions? Reusability: Write once, use everywhere! Organization: Breaks a large, messy program into small, manageable chunks. Testing: It’s much easier to test a small function than a 100-line script. Mini Task Write a program that: Defines a function called calculate_area that takes length and width as parameters. The function should return the area (length * width). Call the function with values 5 and 10 and print the result. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
Srikanth parikibanda’s Post
More Relevant Posts
-
PYTHON JOURNEY - Day 46 / 50..!! TOPIC – Python Modules Today I explored Modules — a way to organize code into separate files and use pre-written code from Python’s massive library. It’s like having a giant toolbox where you only pick the tools you need! 1. Importing Built-in Modules Python comes with many "batteries included" modules. To use them, we simply use the import keyword. Python import math print(math.sqrt(64)) # Output: 8.0 print(math.pi) # Output: 3.14159... 2. Using the random Module Perfect for games or selecting random data. Python import random options = ["Rock", "Paper", "Scissors"] print(random.choice(options)) # Picks a random item print(random.randint(1, 10)) # Random number between 1 and 10 3. Using alias and from You can give a module a nickname or import only a specific part of it to save memory. Python import datetime as dt from math import factorial print(dt.datetime.now()) print(factorial(5)) # Output: 120 Why Use Modules? Efficiency: Don't reinvent the wheel! Use proven code written by experts. Organization: Keep your project files clean by separating logic. Power: Modules allow Python to do everything from web scraping to Data Science and AI. Mini Task Write a program that: Imports the random module. Creates a list called players = ["Alice", "Bob", "Charlie", "David"]. Uses random.choice() to pick a random "Winner" from the list. Prints: "And the winner is... <name>! #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
🔤 Master These Python String Methods & Level Up Your Code 🚀 Strings are everywhere in Python from user input to data processing. If you know these core string methods, your code instantly becomes cleaner, safer, and more professional. ✨ Must-know methods: • split() --> Break a sentence into words for text analysis • strip() --> Clean extra spaces from user input • join() --> Combine list items into a single string • replace() --> Update or sanitize text values • upper() --> Convert text to uppercase for consistency • lower() --> Normalize text for case-insensitive comparison • isalpha() --> Validate name fields (letters only) • isdigit() --> Check if input contains only numbers • startswith() --> Verify prefixes like country codes or URLs • endswith() --> Validate file extensions (.pdf, .jpg, etc.) • find() --> Locate a word or character inside a string 💡 Why they matter? ✔ Clean messy user input ✔ Validate data effortlessly ✔ Write readable, efficient logic ✔ Avoid common bugs in real projects If you’re learning Python , bookmark this 📌 Keep up the 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞 👍 𝐂𝐨𝐧𝐬𝐢𝐬𝐭𝐞𝐧𝐜𝐲 is the 𝐊𝐞𝐲 in 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 💯 👇 Comment “Python” if you want a part-2 with real examples! #Python #PythonProgramming #Coding #LearnToCode #Developer #ProgrammingTips #CleanCode
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 47 / 50..!! TOPIC – List Comprehensions Today I explored one of Python’s most "elegant" features — List Comprehensions. It’s a shorthand way to create new lists based on existing ones, turning 4 lines of code into just 1! 1. The Traditional Way vs. Comprehension Normally, to create a list of squares, you’d need a for loop and .append(). With comprehension, it’s a single line! Python # Traditional Way nums = [1, 2, 3] squares = [] for x in nums: squares.append(x * x) # List Comprehension (The Pythonic Way) squares = [x * x for x in nums] print(squares) # Output: [1, 4, 9] 2. Adding a Condition (The if part) You can filter items while creating the list. Python prices = [10, 55, 80, 25, 100] # Only keep prices over 50 expensive = [p for p in prices if p > 50] print(expensive) # Output: [55, 80, 100] 3. String Manipulation It works perfectly for transforming text data too. Python names = ["srikanth", "python", "dev"] capitalized = [n.capitalize() for n in names] print(capitalized) # Output: ['Srikanth', 'Python', 'Dev'] Why Use List Comprehensions? Readability: Once you learn the syntax, it's much easier to read at a glance. Performance: They are generally faster than standard for-loops for creating lists. Professional: It is a hallmark of "Pythonic" code—showing you really know the language! Mini Task Write a program that: Creates a list of numbers from 1 to 10. Uses List Comprehension to create a new list containing only the even numbers. Prints the resulting list. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
Weekend Project Series - 1: Built a Chain of Thought Prompting Library Just completed a Python library that implements Chain of Thought (CoT) prompting - the technique that helps LLMs break down complex problems into reasoning steps. What I built: Multi-provider support (OpenAI + Anthropic) 3 CoT strategies: Standard, Zero-Shot, Self-Consistency Python module, CLI app, and REST API Conversation memory for contextual follow-up questions SQLite persistence for reasoning history Also wrote a beginner-friendly guide explaining each strategy with diagrams and code examples. The interesting bug I found: Python's __len__ returning 0 makes objects "false" - my memory wasn't saving because `if memory:` evaluated to False when empty! Fixed with a simple __bool__ method. Key learnings: → CoT improves LLM accuracy on complex reasoning tasks → Strategy pattern makes it easy to swap reasoning approaches → Always add __bool__ when __len__ returns 0 for empty containers GitHub: https://lnkd.in/gcjx88rN #AIEngineering #LLM #Python #WeekendProject #MachineLearning #OpenAI #Anthropic
To view or add a comment, sign in
-
🚀 From String Splits to Structured Data: A Quick Python Evolution Ever watched a simple Python script evolve? 😄 Started with extracting first names from a list: names = ["Charles Oladimeji", "Ken Collins"] fname = [] for i in names: fname.append(i.split()[0]) # Result: ['Charles', 'Ken'] Then flipped to last names: fname.append(i.split()[1]) # Result: ['Oladimeji', 'Collins'] Finally transformed it into clean, structured dictionaries: names = ["Charles Oladimeji", "Ken Collins", "John Smith"] fname = [] for i in names: parts = i.split() fname.append({"first": parts[0], "last": parts[1]}) # Result: [{'first': 'Charles', 'last': 'Oladimeji'}, ...] Why I love this progression: 1. Shows how small tweaks solve different problems 2. Demonstrates data structure thinking (list → list of dicts) 3. Real-world applicable for data cleaning/API responses 4. Sometimes the most satisfying code journeys start with a simple .split()! #DataEngineer #Python #Coding #DataTransformation #Programming
To view or add a comment, sign in
-
-
#Python has become the lingua franca of #optimization. 6 years ago, if you were building serious optimization models, C++ was the default. Today, Python dominates the field. Why the shift? - Ease of Use: Clean syntax that shortens development cycles and lowers barriers to entry. - Rich Ecosystem: Seamless integration with data (Pandas), visualization (Plotly), and ML (Scikit-learn) for end-to-end decision intelligence pipelines. - Community: Python is what students are learning. It's democratizing optimization. But there are trade-offs to watch: ⚠️ Performance: Python is slower than C++. For large-scale applications, this matters. ⚠️ Efficiency: Know your bottlenecks. Most practitioners focus on solve time when model build time is the real culprit. The solution? Write efficient Python code: ✅ Use NumPy arrays and vectorization ✅ Leverage list comprehension instead of explicit loops ✅ Avoid nested for loops that kill performance ✅ Use the right data structures FICO Xpress's Python API makes this easy with native support for NumPy arrays, efficient problem building with addVariables(), and seamless integration with the full optimization suite. Link in the comments for some Xpress Numpy examples. The move to Python is democratizing optimization. More people than ever are building powerful decision models. Are you leveraging Python for your optimization projects? #DecisionIntelligence #DataScience #Xpress
To view or add a comment, sign in
-
-
industrial strength optimization requires a shell that enables regular looking tables to dynamically personalized each specific model. see work by milne and Orzell. knowing when and when not to use nest arrays goes back to work by Jim brown, ibm
#Python has become the lingua franca of #optimization. 6 years ago, if you were building serious optimization models, C++ was the default. Today, Python dominates the field. Why the shift? - Ease of Use: Clean syntax that shortens development cycles and lowers barriers to entry. - Rich Ecosystem: Seamless integration with data (Pandas), visualization (Plotly), and ML (Scikit-learn) for end-to-end decision intelligence pipelines. - Community: Python is what students are learning. It's democratizing optimization. But there are trade-offs to watch: ⚠️ Performance: Python is slower than C++. For large-scale applications, this matters. ⚠️ Efficiency: Know your bottlenecks. Most practitioners focus on solve time when model build time is the real culprit. The solution? Write efficient Python code: ✅ Use NumPy arrays and vectorization ✅ Leverage list comprehension instead of explicit loops ✅ Avoid nested for loops that kill performance ✅ Use the right data structures FICO Xpress's Python API makes this easy with native support for NumPy arrays, efficient problem building with addVariables(), and seamless integration with the full optimization suite. Link in the comments for some Xpress Numpy examples. The move to Python is democratizing optimization. More people than ever are building powerful decision models. Are you leveraging Python for your optimization projects? #DecisionIntelligence #DataScience #Xpress
To view or add a comment, sign in
-
-
PYTHON Versus C - Expressiveness versus raw control I have had this debate...C is too much! Situation: I have a variable that stores the value "spaces" I want to convert this to "s p a c e s" In python: print(" ".join("spaces")) In C: (Warning: Don't use in Production) #include <stdio.h> int main() { char text[] = "spaces"; size_t text_len = sizeof(text) - 1; size_t out_len = 2 * text_len - 1; char spaced_text[out_len + 1]; // +1 for trailing null int i = 0, j = 0; for(i = 0; i < out_len; i++) { if(i%2 == 0) { spaced_text[i] = text[j++]; } else { spaced_text[i] = ' '; } } spaced_text[out_len] = '\0'; printf("%s\n", spaced_text); return 0; } After I learnt C - I realized just what it takes to get to " ".join(<string>). Python is just abstracting away a lot of things to make life easy for the programmer. Naturally for those who like to go a level deeper " ".join(<string>) is not satisfying enough... I am sure some of you will relate with this 😊 Have a restful Sunday!
To view or add a comment, sign in
-
Day 456: 3/1/2026 Why Numba Makes Python Fast (Part 1)? One of the biggest performance gaps in Python comes from how code is executed, not what the code looks like. 🐌 Pure Python: Interpreter Overhead Everywhere Python executes code using an interpreter: → Every loop iteration is interpreted → Every operation involves dynamic type checks → Every value is a Python object → Reference counting happens constantly Even simple numeric loops pay a heavy price: → Type resolution happens at runtime → Python bytecode is executed instruction by instruction → CPU spends more time managing objects than doing math This design prioritizes: → flexibility → safety → developer productivity …but it severely limits raw performance for compute-heavy workloads. ⚡ Numba: Compiled Execution with Static Types Numba takes a completely different approach: → Functions are compiled using LLVM → Types are inferred once at compile time → Python objects are eliminated inside hot loops → Code runs as native machine instructions With @njit: → No Python interpreter in the loop → No dynamic dispatch → No repeated type checks → CPU executes raw arithmetic operations 🚀 Key Takeaway → Python executes logic dynamically and safely → Numba compiles logic into static, native code Stay tuned for more AI insights! 😊 #Python #Numba #Performance #Optimization
To view or add a comment, sign in
-
Day 461: 8/1/2026 Why Python Strings Are Immutable? Python strings cannot be modified after creation. At first glance, this feels restrictive — but immutability is a deliberate design choice with important performance and correctness benefits. Let’s break down why Python does this. ⚙️ 1. Immutability Enables Safe Hashing Strings are commonly used as: --> dictionary keys --> set elements --> For this to work reliably, their hash value must never change. If strings were mutable: --> changing a string would change its hash --> dictionary lookups would break --> internal hash tables would become inconsistent By making strings immutable: --> the hash can be computed once --> cached inside the object --> reused safely for O(1) lookups This is a foundational guarantee for Python’s data structures. 🔐 2. Immutability Makes Strings Thread-Safe Immutable objects: --> cannot be modified --> can be shared freely across threads --> require no locks or synchronization This simplifies Python’s memory model and avoids subtle concurrency bugs. Even in multi-threaded environments, the same string object can be reused safely without defensive copying. 🚀 3. Enables Memory Reuse and Optimizations Because strings never change, Python can: --> reuse string objects internally --> safely share references --> avoid defensive copies Example: --> multiple variables can point to the same string --> no risk that one modification affects another This reduces: --> memory usage --> allocation overhead --> unnecessary copying 🧠 4. Predictable Performance Characteristics Immutability allows Python to store: --> string length --> hash value --> directly inside the object. As a result: --> len(s) is O(1) --> hashing is fast after the first computation --> slicing and iteration don’t need recomputation --> This predictability improves performance across many operations. Stay tuned for more AI insights! 😊 #Python #Programming #Performance #MemoryManagement
To view or add a comment, sign in
More from this author
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