Python Basics: Extracting Initials from a Name – A Step-by-Step Guide for Beginners As a Python enthusiast, I love sharing simple code snippets that can help beginners understand the basics of string manipulation. Today, let’s break down a short Python script that extracts the initials from a full name and prints them in uppercase. This is perfect for tasks like generating acronyms or user badges. Here’s the code using the name “Kannan Srinivasan”: name = "Kannan Srinivasan" initials = "".join([word[0].upper() for word in name.split()]) print(initials) When you run this, it outputs: KS Now, let’s explain it step by step for beginners—no prior experience needed! I’ll walk you through what each part does: 1 Assign the name to a variable: name = "Kannan Srinivasan" This creates a string variable called name and stores the full name in it. Strings are just text enclosed in quotes. Here, the name has two words separated by a space. 2 Split the name into words: Inside the code: name.split() The .split() method breaks the string into a list of words using spaces as the separator. For “Kannan Srinivasan”, this gives: ['Kannan', 'Srinivasan']. (A list is like a collection of items, e.g., [item1, item2].) 3 Extract the first letter of each word and make it uppercase: Inside the list comprehension: [word[0].upper() for word in name.split()] This is a “list comprehension”—a compact way to create a new list by looping over the words. ◦ for word in name.split(): Loops through each word in the list from step 2. ◦ word[0]: Gets the first character of the word (index 0, since Python counts from 0). ◦ .upper(): Converts that character to uppercase (e.g., ‘k’ becomes ‘K’). Result: For our name, this creates ['K', 'S']. 4 Join the initials into a single string: "".join(...) The .join() method combines the list of initials into one string. The "" means no spaces or separators between them, so ['K', 'S'] becomes "KS". This is assigned to the variable initials. 5 Print the result: print(initials) This simply outputs the initials to the console: “KS”. In a real app, you could use this for displaying on a profile or generating an avatar. This snippet is concise thanks to Python’s list comprehensions, but it’s a great intro to strings, lists, and methods. Try it yourself in a Python editor like VS Code or an online REPL—change the name and see what happens! #Python #CodingForBeginners #TechTips
How to Extract Initials from a Name in Python
More Relevant Posts
-
🌟 New Blog: Mastering Data Types in Python — The Foundation of Every Code! Every great Python project starts with one thing — understanding data types. In my latest blog, I break down this fundamental concept in a clear, simple, and practical way — perfect for beginners and aspiring data scientists. Here’s what you’ll learn 👇 💡 What are Data Types and why they matter in Python ⚙️ The key types — Integers, Floats, Strings, Lists, Tuples, Sets, and Dictionaries 🧠 How Python handles data behind the scenes 🚀 Real-world examples and interview insights If you’re just starting your Python or Data Science journey, this blog will help you build a strong foundation that makes advanced topics easier to understand later. I explored all of this in my first Medium blog: 👉 “Python and Its Data Types: Where Logic Meets Magic” https://lnkd.in/ghv5jvyX Big Thanks to Vishwanath Nyathani, Kanav Bansal, Raghu Ram Aduri, Supriya Seetharam, Naman Goswami, Harsha Mg for guiding me throughout this journey. #DataAnalytics #Python #DataTypes #LogicMeetsMagic #DataScience #Programming #StudentsWhoCode #MediumBlog #Learning https://lnkd.in/g28NQ4hC
To view or add a comment, sign in
-
Python Essentials: Most Commonly Used Methods (Clean & Simple) Master these, and you’ll cover 80% of real-world Python usage 👇 1. LIST (Most Used) append() – Add item to end extend() – Add multiple items insert() – Insert at index remove() – Remove by value pop() – Remove by index / last sort() – Sort list reverse() – Reverse list count() – Count occurrences copy() – Copy list 2. TUPLE (Most Used) count() – Count value index() – Find index (Tuples are immutable, so only these matter.) 3. STRING (Most Used) lower() – Convert to lowercase upper() – Convert to uppercase strip() – Remove surrounding spaces split() – Split into list join() – Join strings with separator replace() – Replace text find() – Find substring startswith() – Check start endswith() – Check end 4. DICTIONARY (Most Used) get() – Safe key lookup keys() – Return all keys values() – Return all values items() – Key–value pairs update() – Update dictionary pop() – Remove key clear() – Remove all items 5. SET (Most Used) add() – Add element remove() – Remove element union() – Combine sets intersection() – Common elements difference() – Elements not in other set clear() – Empty set
To view or add a comment, sign in
-
Python Functions!⚙️ Functions help us write reusable and neat code like loops. They are one of the core concepts of python and therefore, today we are going to review what I learned about python functions so far! 👇 👉Basics of functions: grouping statements to perform specific tasks, avoiding repetition, and understanding how to define and call them. ⚙️Parameters & arguments: passing values to functions, using default values, and learning the difference between parameters and arguments. ⚙️Return vs print: how return sends a value back to the caller and print just displays output, and why functions without return give None. ⚙️Recursion: functions calling themselves, importance of base cases, factorial calculation, and printing sequences both forwards and backwards using recursion. 💪Mini exercises: I have added simple and beginner friendly beginner exercises in my jupyter notebook for python functions! Dropping link down below! 😊 😊Good News: My Jupyter Notebook for Python Functions Is Up On My Github! Make sure to check it out and try to do mini projects for python functions that i made there! Good Luck Python Beginners! 😊What Is Coming Next?: Python Lists In detail for Beginners like me! --------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- #pythonfunctions #functionsinpython #pythonforbeginnners #pythonprogramming #pythonfordatascience #pythonformachinelearning
To view or add a comment, sign in
-
-
🚀 Master Python’s Hidden Power — Lambda Functions! When you first start learning Python, you quickly get used to using def to define functions. But there’s a hidden gem that can make your code shorter, cleaner, and even more powerful — Lambda Functions. Let’s break it down in simple terms 👇 💡 What is a Lambda Function? A lambda function is an anonymous one-line function in Python — meaning it doesn’t need a name. It’s written using the lambda keyword and is perfect for quick, temporary operations. Think of it as a “mini function” that you use once and move on. Syntax: lambda arguments: expression ⚙️ Key Highlights * You can pass any number of arguments but only one expression. * The expression is evaluated and returned automatically — no return keyword needed. * It has its own local scope, which means it doesn’t interfere with variables outside. * Best suited for short-term or inline operations like sorting, filtering, or data transformation. 🔥 Why You Should Use Lambda Functions 1️⃣ Compact and Clean Code Instead of defining full functions, you can achieve the same with a single line. 2️⃣ Anonymous and Temporary When you just need a function once — like inside another function — lambda is the perfect fit. 3️⃣ Functional Programming Style They work seamlessly with Python’s functional tools like map(), filter(), and reduce(). ✅ Higher-Order Functions This is where lambda really shines: map() → Apply a transformation to every element (e.g., Celsius → Fahrenheit). filter() → Keep only elements that match a condition (e.g., numbers > 50). reduce() → Combine all elements into a single value (e.g., find product of all numbers). 🧩 Think of Lambda Like This A lambda function is like a calculator button — small, precise, and made for instant tasks. You don’t use it to build the entire calculator, but you can’t work efficiently without it. ---- 💾 Save this post if you found it helpful and want to refer back when practicing Python. 📢 Note: Soon I’ll release a 1000+ page free Python tutorial PDF— covering everything from basics to advanced Python. Stay connected to get your copy first!
To view or add a comment, sign in
-
Day 7 of My 30-Day Python Learning Challenge 👉 Python Modules & Packages – Organizing Code Like a Real Project** Today’s learning took Python from basic scripts to real-world project structure. Modules and packages are what turn simple Python code into scalable, reusable, and organized applications — exactly how professional developers build software. 🔧 1️⃣ What Are Modules in Python? A module is simply a Python file (.py) that contains reusable code — functions, classes, or variables. Instead of writing long scripts, you divide your logic into separate files and import them when needed. ✔ Helps keep code clean ✔ Makes debugging easier ✔ Encourages reusability ✔ Ideal for team projects Example: utilities.py def add(a, b): return a + b You can use this in any other file: import utilities print(utilities.add(5, 10)) 📝 2️⃣ How to Create Your Own Module 1. Create a Python file (example: math_operations.py) 2. Add functions inside it 3. Import it into your main script math_operations.py def multiply(x, y): return x * y main.py from math_operations import multiply print(multiply(4, 5)) This is how real applications stay structured and maintainable. 📦 3️⃣ Built-in Python Modules Python provides hundreds of built-in modules that save time and effort. Today, I explored some essential ones: ✔ math Used for mathematical calculations import math print(math.sqrt(25)) ✔ datetime Used to handle dates and time from datetime import datetime print(datetime.now()) ✔ random Used for generating random numbers import random print(random.randint(1, 10)) Instead of writing logic from scratch, these modules allow you to perform complex operations with one line of code. 📥 4️⃣ How to Import Functions Different ways to import: 1. Import the whole module import math 2. Import specific functions from math import sqrt 3. Import with alias (short name) import datetime as dt 4. Import everything (not recommended) from math import * Imports make your code readable and avoid repetition across multiple files. 📦 5️⃣ What Are Packages? A package is a collection of modules stored in a folder. Inside the folder, an __init__.py file tells Python “this folder is a package.” Packages help you group similar modules together for large projects. Example folder structure: analytics/ __init__.py data_cleaning.py data_visualization.py calculations.py This structure is used in real-world applications like Django, Flask, Pandas, NumPy, etc. 🏗️ 6️⃣ Structuring Large Projects Using Modules & Folders A scalable Python project usually follows this format: project/ │ ├── main.py ├── config/ │ └── settings.py ├── utils/ │ └── helpers.py ├── services/ │ └── api.py └── modules/ └── salary.py This helps in: ✔ Organizing code logically ✔ Working better with teams ✔ Making the project easier to maintain ✔ Promoting code reuse across multiple files
To view or add a comment, sign in
-
Day 32 — Python: Modules & User-Defined Modules 🐍 Introduction to Modules What is a Module? A module is a Python file (.py) containing functions, classes, and variables. Modules help organize code into logical sections. Modules let you reuse code across multiple programs. Modules make code more readable and maintainable. Modules support collaborative development. Types of Modules in Python User-Defined Modules — created by you. Built-in Modules — provided by Python (e.g., math, os). (Covered separately.) External Modules — third-party packages installed via pip. This post focuses on user-defined modules and how to use them. Importing Modules in Python — common ways a. Import entire module: import my_module print(my_module.function_name()) b. Import specific items: from my_module import function_name print(function_name()) c. Import with an alias: import my_module as mm print(mm.function_name()) d. Avoid: from my_module import * # can cause name conflicts User-Defined Modules — step-by-step Step 1 — Create the module file my_module.py: def greet(name): return f"Hello, {name}!" pi = 3.14159 Step 2 — Use the module in another file (main.py): import my_module print(my_module.greet("Alice")) print("Value of Pi:", my_module.pi) Import specific function: from my_module import greet print(greet("Bob")) Using an alias: import my_module as m print(m.greet("Charlie")) Python module search path When importing, Python searches: Current directory Directories in sys.path To view or modify: import sys print(sys.path) sys.path.append("C:/path/to/your/modules") # add custom path Using if name == "main" Use this to prevent code from running on import. inside my_module.py def greet(name): return f"Hello, {name}!" if name == "main": print(greet("Alice")) # runs only when file executed directly Run: python my_module.py → executes the block. If imported, the block is ignored. 7) Installing & using external modules Install with pip: pip install requests Example usage: import requests response = requests.get("https://www.example.com") print(response.status_code) ✨ Tip: Start organizing larger projects into packages (folders with init.py) for better structure. 💬 What module will you package into a module next? Share below! ⬇️ #Python #DaysOfCode #PythonModules #CodingJourney
To view or add a comment, sign in
-
🎃 Python Optimization Tip: Building Strings the Right Way It's Halloween, so freeCodeCamp provided the **SpOoKy~CaSe** coding challenge! This task required complex string manipulation, including case-insensitivity, custom separator replacement, and conditional, alternating capitalization. The goal was to convert `hello_world` to `HeLlO~wOrLd`. 👻 The Pythonic Solution My final code is efficient and easy to read, tackling the requirements in two clear steps: 1. **Preprocessing:** Use built-in `str.lower()` and `str.replace()` to handle case and separators (`_` and `-` become `~`). 2. **Casing Logic:** Iterate through the string, using a counter that **only increments on letters** to correctly apply the alternating capitalization pattern. ```python def spookify(boo: str) -> str: # 1. Preprocess the string boo_chars = boo.lower().replace('-', '~').replace('_', '~') count_alpha = 0 output_boo = [] # <-- Key for performance! for char in boo_chars: if char.isalpha(): count_alpha += 1 if count_alpha % 2 != 0: output_boo.append(char.upper()) else: output_boo.append(char) else: output_boo.append(char) return ''.join(output_boo) ``` Lesson Learned: `+=` vs. `.append()` The most important takeaway here is **performance** when building strings inside a loop. * **Avoid Repeated String Concatenation (`+=`):** In Python, strings are **immutable**. When you use `output_boo += char`, Python must create a brand **new string object** in memory every single time. This O(N^2) process can be a huge performance hit for large inputs. * **The Optimal Method (`.append()` + `.join()`):** By contrast, using a **list** (`output_boo = []`) and calling `.append()` is an O(1) operation. The final `''.join(output_boo)` is a single, efficient operation to stitch the parts together. This ensures the entire solution remains O(N) time complexity. Always prioritize building output with a list and `join()` over repeated string concatenation! Happy coding! #Python #CodingChallenge #SoftwareEngineering #Performance #Optimization #Halloween
To view or add a comment, sign in
-
🚀 New Blog Alert: Mastering Data Types in Python 🐍 Every successful Python project starts with a solid grasp of data types — the building blocks of logic and structure in your code. In my first Medium blog, “Python and Its Data Types”, I break down this essential concept in a way that’s clear, practical, and beginner-friendly — ideal for aspiring developers and data scientists. 🔍 What you’ll learn: 🧩 Why data types matter — and how they shape your code 🔢 The core types: Integers, Floats, Strings, Lists, Tuples, Sets, Dictionaries 🧬 How Python handles data under the hood 🎯 Real-world examples and interview-ready insights Whether you're just starting your Python journey or brushing up on the basics, this guide will help you build a foundation that makes advanced topics easier to tackle. Big Thanks to Vishwanath Nyathani ,Kanav Bansal,Supriya Seetharam ,Naman Goswami Harsha M. for guiding me throughout this journey.. #DataAnalytics #Python #DataTypes #LogicMeetsMagic #DataScience #Programming #StudentsWhoCode #MediumBlog #Learning #InnomaticsResearchLabs
To view or add a comment, sign in
-
🚀 My First Python Menu-Driven Project — Simple Calculator 🧮 Today, I’m excited to share my very first menu-driven Python project — a Simple Calculator! 🎉 This project helped me understand how to make interactive programs using loops, conditions, and exception handling. 💡 What I learned: ✅ Creating functions and reusing them effectively ✅ Using while loops to keep programs running until the user chooses to exit ✅ Handling user input safely with try and except blocks ✅ Implementing menu-driven logic for multiple operations ✅ Using Python’s eval() function carefully for BODMAS rule evaluation ✅ Formatting output using f-strings 🧩 Features of My Calculator: 1️⃣ Addition 2️⃣ Subtraction 3️⃣ Multiplication 4️⃣ Division (with ZeroDivisionError handling) 5️⃣ Percentage Calculation 6️⃣ Power Operation 7️⃣ BODMAS Expression Evaluation 8️⃣ Exit Option Here’s a small preview of my code 👇 def menu(): print('### Simple Calculator ###') print('1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Percentage\n6. Power\n7. BODMAS\n8. Exit') while True: try: menu() choice = int(input('Enter the number (1-8): ')) except ValueError: print('Invalid input! Enter a number.') continue if choice in {1,2,3,4,5,6}: num1 = float(input('Enter number 1: ')) num2 = float(input('Enter number 2: ')) if choice == 1: print('Addition:', num1 + num2) elif choice == 2: print('Subtraction:', num1 - num2) elif choice == 3: print('Multiplication:', num1 * num2) elif choice == 4: print('Division:', num1 / num2 if num2 != 0 else 'Cannot divide by zero!') elif choice == 5: print('Percentage of num1:', num1 / 100, '%') print('Percentage of num2:', num2 / 100, '%') elif choice == 6: print('Power:', num1 ** num2) elif choice == 7: bodmas = input('Enter expression: ') print('BODMAS Result:', eval(bodmas)) elif choice == 8: print('Thank you for using my calculator!') break else: print('please enter between 1 to 8 only!') 🎯 My Learning Goal: I’m continuously improving my Python skills to build a strong foundation for Data Science and Machine Learning. This small step motivates me to take on bigger projects like database systems, data visualization, and ML models soon! 💪 👩💻 If you’re also learning Python, let’s connect and share knowledge! 💬 Suggestions and feedback are always welcome. #Python #CodingJourney #BeginnerProject #MenuDrivenProgram #WomenInTech #LearningInPublic #DataScience #dataAnalyst #engineeringinkannada simple_output:
To view or add a comment, sign in
-
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