Learn Python step by step → https://lnkd.in/d8-NH2BY Recommended Python courses → Python for Everybody https://lnkd.in/dw3T2MpH → CS50’s Introduction to Programming with Python https://lnkd.in/dkK-X9Vx → IBM Data Science Professional Certificate https://lnkd.in/dwkPTFGV Explore more free programming courses → https://lnkd.in/dPkQP6Bt Python string methods help you manipulate and analyze text efficiently. ⬇️ Change case → capitalize() Convert first letter to uppercase Example "hello world".capitalize() Result Hello world → lower() Convert all characters to lowercase Example "HELLO WORLD".lower() Result hello world → upper() Convert all characters to uppercase Example "hello world".upper() Result HELLO WORLD ⬇️ Formatting strings → center(width, char) Align string in the center with padding Example "Python".center(10, "*") Result Python ⬇️ Searching inside strings → count(substring) Count occurrences of a character or word Example "HELLO WORLD".count("L") Result 3 → index(value) Return index of first occurrence Example "HELLO WORLD".index("O") Result 4 → find(value) Locate substring position Example "HELLO WORLD".find("OR") Result 7 ⬇️ Replace and split → replace(old, new) Replace part of a string Example "31/01/2022".replace("/", "-") Result 31-01-2022 → split(separator) Split string into list Example "31/01/2022".split("/") Result ['31', '01', '2022'] ⬇️ Validation methods → isalnum() Check if string contains letters and numbers Example "abc123".isalnum() Result True → isnumeric() Check if string contains only numbers Example "12345".isnumeric() Result True → islower() Check if characters are lowercase Example "hello world".islower() Result True → isupper() Check if characters are uppercase Example "HELLO WORLD".isupper() Result True #Python #Programming #LearnPython #Coding #DataScience #ProgrammingValley
Programming Valley’s Post
More Relevant Posts
-
🧙♂️ Magic Methods in Python (Dunder Methods) Python is known for its powerful and flexible object-oriented features. One of the most interesting concepts in Python is Magic Methods, also called Dunder Methods (Double Underscore Methods). Magic methods allow developers to define how objects behave with built-in operations such as addition, printing, comparison, and more. These methods always start and end with double underscores (__). Example: __init__ __str__ __add__ __len__ They are automatically called by Python when certain operations are performed. --- 🔹 Why Magic Methods are Important? Magic methods help to: ✔ Customize the behavior of objects ✔ Make classes behave like built-in types ✔ Improve code readability ✔ Implement operator overloading They allow developers to write clean, powerful, and Pythonic code. --- 🔹 Commonly Used Magic Methods 1️⃣ __init__ – Constructor This method is automatically called when an object is created. class Student: def __init__(self, name): self.name = name s = Student("Vamshi") --- 2️⃣ __str__ – String Representation Defines what should be displayed when we print the object. class Student: def __init__(self, name): self.name = name def __str__(self): return f"Student name is {self.name}" s = Student("Vamshi") print(s) --- 3️⃣ __len__ – Length of Object Allows objects to work with the len() function. class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) t = Team(["A", "B", "C"]) print(len(t)) 4️⃣ __add__ – Operator Overloading Defines how the + operator works for objects. class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value n1 = Number(10) n2 = Number(20) print(n1 + n2) 🔹 Key Takeaway Magic methods make Python classes more powerful and flexible by allowing objects to interact naturally with Python's built-in operations. Understanding magic methods helps developers write cleaner and more advanced object-oriented programs. #Python #PythonProgramming #MagicMethods #DunderMethods #OOP #Coding #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
-
💡 Python Exception Handling: Writing More Reliable Code While writing programs in Python, errors can sometimes occur during execution. These are known as runtime errors, such as: • Dividing by zero • Entering an invalid data type • Trying to open a file that does not exist If not handled properly, these errors may stop the program unexpectedly. Exception handling helps manage such situations gracefully. 1️⃣ Basic try/except Code that may cause an error is placed inside the try block. If an error occurs, the except block runs instead of stopping the program. Example: try: number = int(input("Enter a number: ")) print(1000 / number) except: print("An error occurred") ➡️ The program tries to convert the input and divide 1000 by it. If the input is invalid or 0, the except block runs instead of crashing. 2️⃣ Handling specific exceptions We can handle different errors separately. Example: try: number = int(input("Enter a number: ")) result = 1000 / number except ValueError: print("Invalid input") except ZeroDivisionError: print("Cannot divide by zero") This example handles different types of errors separately. ➡️ If the user enters an invalid value, a ValueError occurs. ➡️ If the user enters 0, a ZeroDivisionError occurs. 3️⃣ Using else The else block runs only if no exception occurs. Example: try: number = int(input("Enter number: ")) result = 1000 / number except ZeroDivisionError: print("Cannot divide by zero") else: print("Result is:", result) ➡️ This separates normal logic from error handling. 4️⃣ Using finally The finally block runs whether an exception occurs or not. Example: file = None try: file = open("data.txt", "r") print("File opened successfully") except FileNotFoundError: print("The file does not exist") finally: if file: file.close() print("File closed") ➡️ file is first set to None, meaning the variable exists but is not linked to a file yet. ➡️ The program tries to open data.txt. If the file is opened successfully, a message is printed. ➡️ If the file does not exist, a FileNotFoundError occurs and the except block runs. ➡️ The finally block always runs and ensures the file is closed if it was opened. 🔹 The finally block is commonly used for cleanup tasks such as closing files, database connections, or releasing system resources. 5️⃣ Capturing the error message Example: try: x = 10 / 0 except Exception as e: print("Error:", e) ➡️ The error message is stored in e, which helps in debugging. 🔹 Summary try and except make Python programs more robust by preventing crashes and handling unexpected situations properly. #Python #Programming #AI #DataAnalytics #ExceptionHandling #Coding
To view or add a comment, sign in
-
🚀 Day 3 – Python Practice Progress( 6 of 50 questions solved) Problems I practiced today: ✔ Check if a number is even or odd ✔ Find the largest of three numbers ✔ Print numbers from 1 to N ✔ Find the sum of numbers from 1 to N ✔ Check if a number is prime ✔ Check if a string is a palindrome While solving these, I practiced using: • Conditional statements • Loops (while / for) • Input validation using try–except • String slicing (for palindrome checking) 💡 One interesting concept I explored today was Python slicing: s = "python" print(s[::-1]) This reverses the string because the step -1 makes Python traverse the sequence backwards. Small problems like these are helping me build stronger problem-solving skills in Python. Looking forward to practicing more tomorrow. #Python #DataScience #Programming 1 Check if a number is even or odd. try: num1=int(input("Enter a Number : ")) if num1%2==0: print("number is even") else: print("number is odd") except ValueError: print("invalid input. Please enter a number") 2. Find the largest of three numbers. try: num1=int(input("Enter first Number: ")) num2=int(input("Enter second Number: ")) num3=int(input("Enter third Number: ")) if num1>num2 and num2>num3: print("Larget Number is :", num1) elif num2>num3 and num2>num1: print("Largest Number is :", num2) else: print("Largest Number is :", num3) except ValueError: print("invalid Input. Please enter a number") 3 Print numbers from 1 to N try: num1=int(input("Enter a Number: ")) if num1>0: s=0 while s<=num1: print(s) s=s+1; else: p=0 while p>=num1: print(p) p=p-1; except ValueError: print("invalid input, please enter a number") 4 Find the sum of numbers from 1 to N. try: num=int(input("Enter a number : ")) if num>0: s=0 i=0 while i<=num: s=s+i; i=i+1; print(s) else: p=0 q=0 while q >=num: p=p+q; q=q-1; print(p) except ValueError: print("invalid input. Enter correct Number") Check if a number is prime. try: num=int(input("Enter a number : ")) if num>1: is_prime=True i=2 while i <num: if num%i==0: is_prime=False break i=i+1 if is_prime: print("Number is prime") else: print("Number is not prime") else: print("Enter a number greater than 1") except ValueError: print("Invalid Input. enter valid number") 6. Check if a string is a palindrome. try: num=str(input("Enter a sring:")) if num==num[::-1]: print("Palindrome") else: print("not a palindrome") except ValueError: print("invalid input. Enter a string")
To view or add a comment, sign in
-
python study day 12 1. Basics of Functions A function is a reusable block of code that performs a specific task when called. Functions are useful to organize code, make it reusable, and reduce redundancy. 2. Defining a Function You define a function using the def keyword followed by the function name, parentheses, and a colon :. Syntax: def function_name(parameters): # Block of code Example: Basic function to greet a user def greet(): print("Hello! Welcome to the Python course.") greet() Output: Hello! Welcome to the Python course. 3. Function Parameters Parameters are variables used to pass data into a function. Example: Function with a parameter def greet_user(name): print(f"Hello, {name}! Welcome to the Python course.") greet_user("Anand") Output: Hello, Anand! Welcome to the Python course. 4. Returning Values from a Function A function can return a value using the return keyword, which allows the output of the function to be reused elsewhere. Example: Function that adds two numbers and returns the result def add_numbers(a, b): return a + b result = add_numbers(10, 20) print("The sum is:", result) Output: The sum is: 30 5. Default Parameter Values You can define a default value for a parameter, which is used if no argument is passed when the function is called. Example: Function with a default parameter def greet(name="Student"): print(f"Hello, {name}! Welcome to the Python course.") greet() # Uses default value "Student" greet("Geetha") # Uses passed value "Geetha" Output: Hello, Student! Welcome to the Python course. Hello, Geetha! Welcome to the Python course. Here are the sections for Nested Functions and Local/Global Variables: 6. Local and Global Variables Local Variables are defined inside a function and are only accessible within that function. Global Variables are defined outside all functions and are accessible from anywhere in the code. Example: Local vs Global variables name = "Global Name" def greet(): name = "Local Name" print(name) greet() # Prints local variable print(name) # Prints global variable Output: Local Name Global Name In this example, the local variable name inside the function does not affect the global variable name.
To view or add a comment, sign in
-
🚀 Day 3 of My Python Learning Journey. Today was a very productive day as I continued building my Python fundamentals. Instead of just reading theory, I focused on writing code and practicing small programs to understand how Python actually works. Here are the key concepts I explored today: 🔹 Python Data Types I learned about the fundamental data types in Python such as: • Integer • Float • String • Boolean Understanding data types is important because they determine how Python stores and processes different kinds of data. 🔹 Type Conversion in Python One of the most interesting things I learned today was type conversion. Since the input() function always takes values as strings, I practiced converting them into the required data types using: • int() → convert to integer. • float() → convert to decimal number. • str() → convert to string. This is extremely important when building programs that perform calculations based on user input. These are of two types : Implicit (automatic in python) and Explicit (manual in python). 🔹 Operators in Python I explored operators and how Python performs calculations: • Arithmatic Operator -(+,-,*,/,%) • Comparison Operator - (==,!=,<=,>=,<,>) • Logical Operator - (and , or , not) • Assignment Operator - (=,+=,-=,*=,/=,%=,**=, //=) Understanding operators helps in writing programs that perform mathematical and logical operations. 🔹 Practice Problems To strengthen my understanding, I solved multiple practice programs including: • Writing a program to add two numbers. • Working with variables and expressions. • Practicing user input and calculations. 🔹 Assignment Problem I also completed an assignment where I built a small program that: ✔ Takes temperature input in Celsius from the user. ✔ Converts it into Fahrenheit using the formula. ✔ Converts it into Kelvin as well. Programs like these may look simple, but they help build the foundation for problem solving and logical thinking in programming. 📂 Today’s coding practice included creating multiple Python files in VS Code to organize my learning and experiments. What I’m realizing is that consistent daily practice is the real key to mastering programming. My goal is to build a strong Python foundation and eventually use it in Artificial Intelligence and Machine Learning. Step by step. Day by day. Code by code. Looking forward to learning more tomorrow. 🚀 #Python #PythonLearning #CodingJourney #LearnToCode #Programming #ComputerScience #TechLearning #AI #MachineLearning #FutureEngineer
To view or add a comment, sign in
-
-
Episode 8 of What I Can Do With Python This week, I tried something different. This time, instead of using the Streamlit Web App, I extended Microsoft Excel functionality by creating my own custom Excel formula powered by Python. Yes, a Python-Powered Excel function. For a long time, I considered learning VBA so I could build custom formulae tailored to my workflow. But the more I worked with Python, the harder it became to commit to VBA. Compared to VBA, Python just has more tools and is easier to work with, debug and maintain. Inspired by Felix Zumstein's idea in his book, 'Python for Excel', where he stated that "....by learning how to combine Excel with Python, you can have the best of both worlds.", I used the xlwings library to integrate Python directly into Excel. With this, I was able to build a custom Excel formula designed for something many researchers and data analysts deal with often, analysis of demographic characteristics of respondents... In academic research, we usually present the demographic characteristics of respondents as frequency and percentage distributions if categorical variables. Normally, this is done with Pivot Tables, but I wondered, "What if this entire summary could be generated with just one formula?" So I built exactly that. How the Formula Works The first argument is the Excel range containing the categorical data. Once you pass that range, the formula automatically generate a frequency and percentage distribution table. Other optional arguments allow you to: • Control the output • Include or exclude totals • Add or remove percentage signs • Combine summaries or generate them separately • Specify the number of decimal places for percentages. Controlling Category Order By default, the results appear in alphabetical order. But I also implemented a simple trick inspired by SPSS-style value labels. For example, if your dataset contains: Childhood Adolescent Early Twenties Late Twenties Adulthood You can structure the data like this: 1_childhood 2_adolescent 3_early twenties 4_late twenties 5_adulthood The numbers control the order while the prefixes are automatically removed in the final summary. What Happens Behind the Scenes? This project goes beyond basic Python. It involves: • Data manipulation with Pandas • Table reshaping and sorting • Data aggregation • Understanding how xlwings converts Excel ranges into Python objects. The result is a workflow where Python handles the heavy logic while Excel remains the interface. This is the beauty of it, you keep Excel's familiarity, but gain Python's power. This time, instead of a Streamlit app, I'm sharing a demo video showing how the formula works directly inside Excel. Watch the demo and let me know what you think.👇🏼 Is there a business logic or automation you've always wish Excel could do for you? Let's talk about it! See you in Episode 9. #Python #Excel #DataAnalysis #Automation #Researchers #xlwings #BuildingInPublic
To view or add a comment, sign in
-
🧠 Python doesn’t “free memory”. It negotiates with it. Most developers know that Python has Garbage Collection. Very few know how it actually works internally. Let’s break it down. 1. Reference Counting (Primary Memory Manager) At the core of Python’s memory management is reference counting. Every object in Python maintains a counter that tracks how many references point to it. Example: a = [1,2,3] b = a Now the list object has 2 references. Internally (in CPython): PyObject ├── ob_refcnt ← reference count └── ob_type Whenever a new reference is created → refcnt +1 Whenever a reference is deleted → refcnt -1 When the count hits 0, Python immediately deallocates the object. That’s why: a = [1,2,3] del a Memory is freed instantly. ⚡ This makes Python’s memory management very fast and deterministic. But there is a problem. 2. The Circular Reference Problem Reference counting cannot detect cycles. Example: a = [] b = [] a.append(b) b.append(a) Even if you delete both: del a del b Both objects still reference each other. So their reference count never reaches 0. Memory leak. This is where Python’s Garbage Collector comes in. 3. Generational Garbage Collector Python adds a cycle detector on top of reference counting. It uses a generational model. Objects are divided into 3 generations: Generation 0 → New objects Generation 1 → Survived one GC cycle Generation 2 → Long lived objects Why? Because most objects die young. This is called the Generational Hypothesis. So Python runs GC more frequently on young objects. Example thresholds: Gen0 threshold ≈ 700 allocations Gen1 threshold ≈ 10 Gen0 collections Gen2 threshold ≈ 10 Gen1 collections This keeps GC fast and efficient. 4. How Cycle Detection Works Internally Python uses a mark-and-sweep style algorithm. Steps: 1️⃣ Identify container objects (lists, dicts, classes) 2️⃣ Track references between them 3️⃣ Temporarily reduce reference counts 4️⃣ Objects that reach zero → unreachable cycle 5️⃣ Free them All of this is implemented in: Modules/gcmodule.c Inside CPython. 5. Interesting Internals You can actually inspect GC behavior: import gc gc.get_threshold() gc.get_count() gc.collect() You can even disable GC: gc.disable() Which some high-frequency trading systems and low latency apps do to avoid GC pauses. (Manual control > unpredictable pauses) 6. Why Python Rarely Leaks Memory Because it combines: ✔ Reference counting (instant cleanup) ✔ Generational GC (cycle detection) This hybrid model makes Python one of the most predictable memory managers among dynamic languages. Most developers use Python. Very few explore CPython internals. But once you understand things like: • PyObject • reference counters • generational GC You start seeing Python less like a language… and more like a beautifully engineered runtime system. #Python #CPython #GarbageCollection #Programming #PythonInternals #SoftwareEngineering
To view or add a comment, sign in
-
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
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