🚀 Understanding Object References and Instance Variables in Python Today I explored an interesting concept in Python Object-Oriented Programming (OOP) — how objects can be passed as input to functions, returned from functions, and assigned to another reference variable. 🔹 Key Concepts I Practiced: 1️⃣ Instance Variables Instance variables are variables defined inside a class using self. They belong to the object and store data specific to that object. 2️⃣ Object as Function Input In Python, an object can be passed to a function just like a normal variable. The function receives the reference of the object. 3️⃣ Returning an Object from a Function A function can also create and return a new object, which can then be stored in another reference variable. 4️⃣ Multiple References to the Same Object When one object is assigned to another variable, both variables refer to the same object in memory. Changing the value through one reference affects the other. 💻 Example Code class Person: def __init__(self, salary, empid): self.salary = salary self.empid = empid def greet(person): print("Salary:", person.salary, "EmpID:", person.empid) # Creating a new object new_person = Person(550000, 102) return new_person # Creating object p = Person(100000, 101) # Passing object to function x = greet(p) # Assigning returned object to another reference y = x # Printing values using another reference print(y.salary) print(y.empid) 📌 What I Learned Objects are passed by reference in Python Instance variables store object-specific data Functions can return objects Multiple variables can refer to the same object Learning these small concepts step by step makes understanding Python OOP much easier. #Python #OOP #Programming #LearningPython #DeveloperJourney
Understanding Python OOP: Objects and Instance Variables
More Relevant Posts
-
Day 50 : Python Type Conversion in Python Today I understood how to convert data types in Python and how it is useful for easy processing. Hands-on : - Today I learned about type conversion in Python, which is essential for transforming data from one type to another based on requirements. - I started by converting strings to integers using functions like int(), which is useful when working with numerical input stored as text. - Next, I explored how to convert between lists, sets, and tuples, allowing flexibility in handling collections. - For example, converting a list to a set helps remove duplicates, while converting to a tuple makes the data immutable. - I also learned about converting dictionaries, such as extracting keys, values, or items into list formats for easier processing. - Additionally, I practiced converting strings to lists, where each character or word can be separated into elements using functions like list() or split(). - These conversions are crucial for data cleaning, transformation, and preparation in real-world projects. Result : - Successfully understood how to convert between different data types in Python to make data more usable and structured. Key Takeaways : - Type conversion helps adapt data for different operations. - int() converts strings into numeric values. - Lists, sets, and tuples can be converted based on use case. - Dictionary data can be extracted into keys, values, or items. - Strings can be converted into lists for easier manipulation. #Python #Programming #DataAnalytics #LearningJourney #TypeConversion #CodingBasics #DataScience #BeginnerPython #AnalyticsSkills
To view or add a comment, sign in
-
-
🚀 Python Basics – Ordered Sequence Data Type (Lists) Today, I practiced working with lists in Python. A list is an ordered collection of items, meaning the elements keep their position and can be accessed using indexing. 💻 Example Code: list0 = [1, 2, 3] # List of integers list1 = [1, 2.5, 3] # List with mixed numeric types (int + float) list2 = ['a', 'b'] # List of strings list3 = [True, False] # List of boolean values print(list0) print(list1) print(list2) print(list3) ✅ Key Points: Lists are ordered → items have a fixed position Lists are mutable → you can change, add, or remove elements Lists can store different data types (int, float, string, bool, etc.) Elements are accessed using indexing (e.g., list0[0] → 1) 📌 Example Output: [1, 2, 3] [1, 2.5, 3] ['a', 'b'] [True, False] ✅ Key Points: Lists in Python are ordered sequences of elements. You can access, modify, and slice list items using their index. Lists can store different data types like integers, floats, strings, and booleans. Practicing simple programs helps build a strong foundation in Python. 🐍💡 Step by step, growing my Python skills! #Python #Programming #DataTypes #List #CodingJourney #Learning #PythonBasics #BeginnerFriendly
To view or add a comment, sign in
-
-
🖥️ Day 1 of python journey What I learned today: Variables and the 4 core data types. Python has four fundamental types that appear in every program ever written: int — whole numbers. Every user ID, every age, every count, every loop index in every application is an integer. float — decimal numbers. Every price, every percentage, every measurement is a float. One important thing I learned: 0.1 + 0.2 in Python equals 0.30000000000000004, not 0.3. This is a floating-point precision issue that causes real bugs in financial applications. Professional developers use Python's Decimal module for money calculations. str — text. Every API response your application receives, every database field it reads, every message it displays is a string. bool — True or False. The entire logic of every program — every condition, every decision, every filter — is powered by boolean values. The insight that changed how I think about Python: input() always returns a string. Always. Even if the user types 100, Python gives you "100" — the text, not the number. If you try to do arithmetic on it without casting, you get a TypeError. The fix: int(input("Enter your age: ")) — convert the string to an integer immediately. This is the very first thing that trips up beginners. I learned it on Day 1. What I built today: A personal profile program that takes 5 inputs — name, age, city, is_employed, salary — stores them in correctly typed variables, and prints a formatted summary using f-strings: f"Name: {name} | Age: {age} | City: {city}" Simple? Yes. But this exact pattern — collect input, store in typed variables, format and display output — appears in every data entry form, every registration page, every dashboard in every Python application. #Day1#Python#PythonBasic#codewithharry#w3schools.com
To view or add a comment, sign in
-
🐍 Python Operators: The Building Blocks of Logic In Python, operators are special symbols used to perform operations on variables and values. They are the "verbs" of your code, telling Python how to process data. 1. Arithmetic Operators Used to perform common mathematical operations. + Addition: x + y - Subtraction: x - y * Multiplication: x * y / Division: x / y (returns a float) // Floor Division: Rounds the result down to the nearest whole number. % Modulus: Returns the remainder of a division. ** Exponentiation: x ** y (x to the power of y). 2. Comparison (Relational) Operators These compare two values and always return a Boolean (True or False). == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to 3. Logical Operators Used to combine conditional statements. and: Returns True if both statements are true. or: Returns True if at least one statement is true. not: Reverses the result (True becomes False). 4. Assignment Operators Used to assign values to variables. = : Simple assignment (x = 5) += : Add and assign (x += 3 is the same as x = x + 3) -= : Subtract and assign *= : Multiply and assign 5. Identity & Membership Operators These are unique to Python and make code very readable. Identity (is, is not): Checks if two variables point to the same object in memory. Membership (in, not in): Checks if a sequence (like a list or string) contains a specific value. 6. Bitwise Operators Used to perform operations on binary numbers. & (AND), | (OR), ^ (XOR), ~ (NOT). Useful for low-level programming or optimizing specific data science tasks. #Python #PythonProgramming #Coding #DataScience
To view or add a comment, sign in
-
Machine Learning Graph Data using python igraph #machinelearning #datascience #graphdata #pythonigraph igraph is a fast open source tool to manipulate and analyze graphs or networks. It is primarily written in C. python-igraph is igraph’s interface for the Python programming language. python-graph includes functionality for graph plotting and conversion from/to networkx. Python interface of igraph, a fast and open source C library to manipulate and analyze graphs (aka networks). It can be used to: Create, manipulate, and analyze networks. Convert graphs from/to networkx, graph-tool and many file formats. Plot networks using Cairo, matplotlib, and plotly. https://lnkd.in/gzzzK7eU
To view or add a comment, sign in
-
🐍 Python Functions (def) ⚙️ Functions help organize code into reusable blocks, making programs cleaner and more efficient. Essential for writing modular and scalable code. 👉 They are very important for avoiding repetitive code and building complex applications. 🔹 1. What is a Function? A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function. Example: def greet(): print("Hello from a function!") 🔹 2. Defining & Calling a Function We use the def keyword to define a function, then call it by its name. Syntax: def function_name(parameters): # code to execute function_name(arguments) # call the function Example: def say_hello(): print("Hello, Python learner!") say_hello() # calling the function Output: Hello, Python learner! 🔹 3. Functions with Parameters & Arguments Parameters are variables listed inside the parentheses in the function definition. Arguments are the actual values sent when calling the function. Example: def welcome_user(name): # 'name' is a parameter print(f"Welcome, {name}!") welcome_user("Alice") # "Alice" is an argument welcome_user("Bob") Output: Welcome, Alice! Welcome, Bob! 🔹 4. Return Values Functions can return data as a result using the return keyword. Example: def add_numbers(a, b): return a + b result = add_numbers(5, 7) print(result) Output: 12 🔹 5. Common Function Uses • Calculations: Performing mathematical operations. • Data Processing: Transforming inputs. • User Interaction: Handling prompts and responses. • Code Reusability: Doing the same task many times. 🎯 Today's Goal ✔️ Understand what functions are ✔️ Define and call functions ✔️ Use parameters and arguments ✔️ Return values from functions 👉 Functions are fundamental building blocks in almost every Python project.
To view or add a comment, sign in
-
🚀 Python Practice – Updating List Elements Dynamically! Today I explored how to update list elements using user input in Python 🐍 🔹 Sample Code: alist = ["praveen","ajay","san","kiran","chandru","fun","joy","rrrr"] po = int(input("Enter the position: ")) newele = input("Enter the new element: ") alist[po] = newele print(alist) ✅ Key Learnings: 🔸 Taking user input using input() 🔸 Converting input to integer using int() 🔸 Updating list element using index → alist[po] = newele 🔸 Understanding how dynamic data works in Python 💡 Example: If user enters: Position → 2 New Element → cloud 👉 Updated list: ['praveen', 'ajay', 'cloud', 'kiran', 'chandru', 'fun', 'joy', 'rrrr'] ⚠️ Note: Make sure the index is within range, otherwise it will throw an error. 📌 Simple programs like this help in building strong logic for real-time applications and automation tasks. #Python #Learning #DevOps #Automation #Coding #Programming #Beginners
To view or add a comment, sign in
-
Master Python Essentials: Lists & Functions 📒 Are you looking to sharpen your Python skills? Whether you are a beginner or a seasoned developer, mastering Lists and Functions is fundamental to writing clean, efficient code. Here is a breakdown of the core concepts from my latest study notes: 📋 Python Lists: Organizing Your Data Lists are ordered, changeable collections that allow duplicate members. * Accessing Items: Use Indexing to grab specific values or Negative Indexing (like -1) to start from the end of the collection. * Slicing: Specify a range (e.g., [2:5]) to return a new list containing the third, fourth, and fifth items. * Modifying: Use .append() to add to the end, .insert() for specific positions, or .remove() and .pop() to delete items. * Pro Tip on Copying: Never use list2 = list1 to copy! This only creates a reference. Use .copy() or the list() method instead to ensure changes in one don't affect the other. ⚙️ Python Functions: Building Reusable Logic Functions are blocks of code that only run when called, helping you avoid redundancy. * Parameters vs. Arguments: A parameter is the variable listed in the function definition, while an argument is the value sent to the function during a call. * Handling the Unknown: * Use *args (Arbitrary Arguments) to receive a tuple when the number of arguments is unknown. * Use **kwargs (Keyword Arguments) to receive a dictionary for unknown named arguments. * Recursion: Python allows a function to call itself! It’s an elegant approach for complex mathematical problems, but be careful—always include a base case to prevent infinite loops. * Variable Scope: Remember that local variables defined inside a function cannot be accessed outside of it, whereas global variables are available throughout the program. 🌟Which Python concept did you find most challenging when you started? Let's discuss in the comments! 👇 #PythonProgramming #CodingTips #SoftwareDevelopment #DataScience #WebDevelopment #PythonDeveloper #LearningToCode #PythonFunctions #CleanCode
To view or add a comment, sign in
-
Python Variables Explained Simply (With Real Examples) In Python, everything you work with is data. When you create a variable, Python: Creates the data in memory Assigns a reference (variable name) to it Think of a variable as a label stuck on a box. Simple code = age = 25 Here , Age is a variable and 25 is the value assigned to it. Python does not require any type declaration. Because it's type is already determined. age = 25 # integer price = 19.99 # float name = "Alex" # string is_active = True # boolean A simple coding example which defines about user profile by using different datatypes : name = "Rahul" age = 24 height = 5.9 is_student = True print("Name:", name) print("Age:", age) print("Height:", height) print("Student Status:", is_student) Dynamic Typing : As informed earlier ,Python allows changing type dynamically. x = 10 print(type(x)) x = "hello" print(type(x)) Output : <class 'int'> <class 'str'> Because of this flexibility, python is fast for development. Important Concept: Checking Data Type Python provides type().Useful in debugging and validation. age = 22 print(type(age)) output : <class 'int'> #Python #Programming #Coding #LearnToCode #Beginners #TechCareer #SelfLearning
To view or add a comment, sign in
-
🚀 #python #Ep 2: Understanding #Data Types in Python In Python, everything is an object, and every object has a data type. Data types define what kind of value a variable holds and what operations you can perform on it. 🔗 Code reference: https://lnkd.in/ei6STRqT 🧠 Why Data Types Matter? Prevent errors in your code Help Python understand how to store and process data Make your programs efficient and readable 📌 Common Python Data Types 🔢 Numeric Types int → Whole numbers (10, -5) float → Decimal numbers (3.14) complex → Complex numbers (2+3j) 📝 String (str) Used to store text Example: "Hello Python" ✅ Boolean (bool) Only two values: True or False 📦 Sequence Types list → Ordered & mutable → [1, 2, 3] tuple → Ordered & immutable → (1, 2, 3) 🗂️ Mapping Type dict → Key-value pairs → {"name": "Hari"} 🔁 Set Types set → Unordered & unique values → {1, 2, 3} 💡 Pro Tip Python is dynamically typed, meaning you don’t need to declare data types explicitly — Python figures it out at runtime 🔍 Example x = 10 # int y = 3.14 # float name = "Hari" # str is_active = True # bool 📣 Final Thought Mastering data types is the foundation of Python programming. Once you understand them, everything else becomes easier! #Python #Coding
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