Understand Python: LESSON 14 FUNCTIONS IN PYTHON ■ First, What Is a Function? A function is a named set of instructions that tells Python how to perform a specific task. Think of it like this: 👉 A function is a machine, You give it a job, it does a job and gives you a result ▪︎ Let's use a real-life analogy. 👉 Imagine you have a juice machine. You put in oranges, you press a button, and the machine makes orange juice You don’t need to know how the machine works inside. You just use it. That’s exactly how a function works. ■ Why Do We Need Functions? Without functions, we tend to always repeat ourselves. > Example without a function: print("Welcome Ben") print("Welcome Ben") print("Welcome Ben") That’s boring and messy. > With a function: def greet(): print("Welcome Ben") We can now print as many "Welcome Ben" messages as we like by simply calling the great function. 👇 greet() greet() greet() Now the work is clean and organized. ■ Functions help us: • Avoid repeating code • Keep code neat • It makes programs easier to understand ■ The Basic Shape of a Function Every function has three parts: 1. The keyword def 2. The function name 3. The instructions inside it 👇 def say_hello(): print("Hello!") Let’s read this in English: “Python, define a function called say_hello that prints Hello.” ■ Calling a Function Creating a function is not enough. You must call it to make it run. say_hello() Think of it like: If you just write a recipe, it doesn't cook a food. You must use the recipe. Let's consider the following examples. Example 1: A Function That Prints a Welcome Message def welcome(): print("Welcome to Python") Calling it: > welcome() Example 2: A Function That Prints Numbers 1 to 5 def print_numbers(): for i in range(1, 6): print(i) Calling it: > print_numbers() #python
Python Functions: A Named Set of Instructions
More Relevant Posts
-
Custom Iterators and the Iterator Protocol in Python Iterators are everywhere in Python. Lists, files, generators and even dictionaries rely on the iterator protocol. Understanding how it works allows you to build efficient data pipelines and custom behaviors. 🔹 1. Iterable vs Iterator An iterable can return an iterator. An iterator produces values one by one. Iterable implements __iter__ Iterator implements __iter__ and __next__ 🔹 2. Creating a Custom Iterator class CountDown: def __init__(self, start): self.current = start def __iter__(self): return self def __next__(self): if self.current <= 0: raise StopIteration value = self.current self.current -= 1 return value Now it works naturally with for loops. 🔹 3. Why Use Custom Iterators? They are useful when: Processing large data streams Building lazy pipelines Avoiding loading everything into memory Controlling iteration logic precisely 🔹 4. Iterators Are Statefull Once exhausted, an iterator cannot be reused. If reuse is required, return a new iterator from __iter__. 🔹 5. Prefer Generators When Possible Generators are simpler and safer in most cases. def countdown(n): while n > 0: yield n n -= 1 Same behavior, much less code. 🔹 6. Iterators Work Everywhere Custom iterators integrate with: for loops list comprehensions sum, min, max any, all, sorted Iterators are a core Python concept that looks simple, but gives you a lot of power when used correctly. Do you usually build custom iterators, or do you rely mostly on generators?
To view or add a comment, sign in
-
Python Loops & Iterations: Loops are the backbone of automation and data processing in Python. 🔁 1. for Loop — Iterate Over a List Use for when you want to loop through items one by one. nums = [1, 2, 3, 4, 5] for num in nums: print(num) ⛔ 2. break — Exit the Loop Immediately Stops the loop as soon as a condition is met. nums = [10, 20, 30, 40, 50] for num in nums: if num == 40: print("Target hit! Exiting loop") break print(num) ⏭️ 3. continue — Skip Current Iteration Skips the rest of the loop for that iteration. for num in range(1, 11): if num % 2 != 0: continue print(f"Even → {num}") 🔂 4. Nested Loops — Loop Inside Another Loop Common in tables, combinations, and comparisons. for i in [2, 3, 4]: for j in range(1, 6): print(f"{i} × {j} = {i * j}") 🔢 5. range() — Numeric Iteration Perfect for counting and stepping through numbers. for i in range(5, 16): print(i) for i in range(0, 51, 5): print(i) 🔄 6. While Loop — Repeat While Condition Is True Best when the number of iterations is unknown. count = 8 while count > 0: print(f"T-minus {count}...") count -= 1 print("Launch!") ♾️ 7. Infinite Loop + break — Controlled Exit A powerful pattern for user input and games. secret = 6 while True: guess = int(input("Guess (1-10): ")) if guess == secret: print("Perfect! You got it!") break elif guess < secret: print("Too low!") else: print("Too high!") #Python
To view or add a comment, sign in
-
🧠 Python Concept You Must Understand: Iterator vs Iterable ✨ Many people use loops. ✨ Few understand what actually gets looped. ✨ This concept explains how for loops really work in Python. 🧒 Real World Explanation Imagine you have a box of chocolates 🍫🍫🍫. ✔️ The box contains chocolates ✔️ Your hand takes chocolates one by one In Python: 💻 The box is an Iterable 💻 The hand is an Iterator 🔹 What Is an Iterable? An iterable is something you can loop over. Examples: List Tuple String Dictionary numbers = [1, 2, 3] 👉 numbers is an iterable It contains items but doesn’t know how to move through them. 🔹 What Is an Iterator? An iterator is what actually gives values one at a time. it = iter(numbers) print(next(it)) print(next(it)) Output: 1 2 👉 The iterator remembers where it stopped 🧠 What a for Loop Really Does for x in numbers: print(x) Behind the scenes, Python does: it = iter(numbers) while True: try: x = next(it) print(x) except StopIteration: break 🤯 This is the secret behind loops. 🚀 Why This Concept Is VERY Important Understanding this helps you: ✔ Understand generators ✔ Understand yield ✔ Write memory-efficient code ✔ Debug iteration errors ✔ Answer interview questions Most advanced Python features depend on this. 🎯 Interview Gold Line “An iterable can create an iterator.” ✔️ Short sentence. ✔️ Deep understanding. 🧠 One-Line Rule 🖥️ Iterable = has items 🖥️ Iterator = gives items one by one ✨ Final Thought 💯 Python loops look simple because Python hides complexity. 💯 Once you understand iterators and iterables, Python feels logical instead of magical. 📌 Save this post — this concept unlocks many others. #Python #LearnPython #Programming #DeveloperLife #PythonTips #Freshers #TechCareers #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 Most Python Developers Misunderstand This (Even after years of coding 😳) 🌱 Growth Begins With Learning – Day 10 In Python interviews, some questions don’t test syntax… They test how well you understand how Python executes code 🧠✨ And this one does exactly that 👇 ❓ Python Interview Question (Day 10): Why does this code not raise an error? def func(): print(x) x = 10 func() ✅ Answer (Clear Explanation): This code raises an UnboundLocalError, not a NameError. Why? Because: • Python sees x = 10 inside the function • So it treats x as a local variable • But print(x) is executed before x is assigned So Python says: 👉 “You are using a local variable before assigning it” 🔹 Important Concept: LEGB Rule Python looks for variables in this order: 1️⃣ Local 2️⃣ Enclosing 3️⃣ Global 4️⃣ Built-in But assignment inside a function makes the variable local by default. 💡 How to fix it properly: def func(): global x print(x) x = 10 or pass it as a parameter (best practice). 🌱 Day 10 Takeaway: Python doesn’t run line by line like humans think. It decides variable scope before execution. Understanding scope turns: ❌ Confusion into clarity ❌ Bugs into confidence 🚀 One concept a day 🚀 One step closer to Python mastery If you’re learning Python and interviews confuse you, feel free to reach out — learning is easier together 🤝✨ #Day10 #PythonInterview #PythonScope #CareerByCode #LEGBRule #CodingConcepts #WomenInTech #CareerGrowth #GayuWithAI
To view or add a comment, sign in
-
A common question among Python developers is why a map object returns values the first time but appears empty on the second call. This behavior is not a bug. It is a direct result of how map is designed in Python. Example: x = ['1', '2', '3'] a = map(int, x) print(list(a)) print(list(a)) The first output contains values, while the second output is an empty list. Reason one: map returns an iterator, not a list In Python 3, map does not create a list in memory. Instead, it returns an iterator. An iterator is an object that generates values on demand rather than storing them. Reason two: iterators are single-use by design An iterator can be traversed only once. When list(a) is executed the first time, Python pulls all values from the iterator and converts them into a list. At this point, the iterator is fully consumed. Reason three: consumed iterators cannot be rewound Once an iterator has reached the end, it does not reset automatically. When list(a) is called again, there are no remaining elements to produce, so an empty list is returned. Reason four: this design improves memory efficiency By returning an iterator, map avoids creating intermediate lists. This makes Python more memory-efficient, especially when working with large datasets or streams of data. Correct approaches depending on use case If values are needed multiple times, convert the map to a list once and reuse it. Correct approaches depending on use case If values are needed multiple times, convert the map to a list once and reuse it. a = list(map(int, x)) print(a) print(a) If lazy evaluation is preferred, recreate the map iterator each time. print(list(map(int, x))) print(list(map(int, x))) Map follows Python’s iterator protocol. Its behavior is intentional, predictable, and optimized for performance. Once you understand iterators, concepts like map, filter, zip, generators, and file objects become much clearer.
To view or add a comment, sign in
-
🐍 Python Course – Day 5 (If-Else Conditions) 🔹 What is Decision Making in Python? Sometimes a program must make decisions based on conditions. Python uses if, else, and elif to control decision making. 🔹 The if Statement The if statement runs code only when the condition is true. age = 20 if age >= 18: print("You are eligible to vote") Explanation: Python checks the condition If it is True, the message is printed If it is False, nothing happens 🔹 The if-else Statement Used when there are two possible outcomes. age = 16 if age >= 18: print("You are eligible to vote") else: print("You are not eligible to vote") Explanation: One block will always execute If if is false, else runs 🔹 The elif Statement Used to check multiple conditions. marks = 75 if marks >= 80: print("Grade A") elif marks >= 60: print("Grade B") elif marks >= 40: print("Grade C") else: print("Fail") Explanation: Python checks conditions from top to bottom First true condition is executed 🔹 Important Rule (Indentation) Python uses indentation (spaces) to define blocks. Wrong indentation = error. ✔ Correct: if True: print("Hello") ❌ Wrong: if True: print("Hello") 🔹 If-Else with User Input age = int(input("Enter your age: ")) if age >= 18: print("Adult") else: print("Minor") 🔹 Day 5 Practice Task ✅ Take marks from user ✅ Print grade using if-elif-else ✅ Take age and check adult or minor marks = int(input("Enter your marks: ")) if marks >= 50: print("Pass") else: print("Fail") 🚀 60 Days of Python – Day 5 Completed 🐍 Today I learned decision making in Python using if, else, and elif. What I practiced today: ✔ Writing conditions ✔ Making decisions based on user input ✔ Understanding indentation in Python age = int(input("Enter age: ")) if age >= 18: print("Adult") else: print("Minor") Learning how programs think step by step 💡 Consistency beats talent. #Python #Programming #LearningJourney #Day5
To view or add a comment, sign in
-
Day 180/200 Regular Expressions in Python. A regular expression (regex) is a sequence of characters that form a pattern. In Python, regular expressions are used to efficiently search for complex patterns like IP addresses, emails, or device IDs within strings. To access regular expressions and related functions in Python, you need to import the ‘re’ module first. The ‘re’ module is a built-in Python module that provides functions for working with regular expressions, including searching and matching patterns. I explored how regular expressions work through the re.findall() function. The re.findall() function returns a list of matches to a regular expression. It requires two parameters. The first is the string containing the regular expression pattern, and the second is the string you want to search through. An example of regular expression using the ‘re’ module and the ‘findall()’ function: import re re.findall("Jos”, "Joshua, Ruth, John, Joseph") “Jos” (the first parameter) is the regular expression in this code, and “Joshua, Ruth, John, Joseph” is the string of names to search through. Regular expressions are stored in Python as strings. Then, these strings are used in re module functions to search through other strings. The output of the code above will be a list of only two elements, the two matches to “Jos”: [‘Jos’, ‘Jos’], from Joshua and Joseph. Happy New Year!!! 🥂
To view or add a comment, sign in
-
Good Evening! Let’s talk about Object Serialization in Python — a concept that sounds technical but is incredibly useful. Ahmed: "Bro, I spent two hours training a model yesterday... and I just lost it. Again. My laptop crashed." Zayd: "You didn’t save the model object?" Ahmed: "I saved the results, not the model itself. Is there a way to save entire objects in Python?" Zayd: [smiling] "Welcome to Serialization." Ahmed: "Serialization?" Zayd: "Yeah. Think of it like freezing your object in time — and unfreezing it whenever you want. Python’s `pickle` module lets you do that." Ahmed: "So I can save a whole model... and load it later like nothing happened?" Zayd: "Exactly. One line to dump, one to load." ```python import pickle Save it with open('model.pkl', 'wb') as f: pickle.dump(my_model, f) Load it with open('model.pkl', 'rb') as f: my_model = pickle.load(f) ``` Ahmed: "That’s a game-changer. What else can I serialize?" Zayd: "Almost anything — models, configs, custom objects. Just be careful: don’t unpickle files from untrusted sources." Ahmed: "Bro, you just saved me hours. Literally."
To view or add a comment, sign in
-
Python’s 🐍 standard library has a hidden gem: difflib With it, you can catch near-duplicate user input like: • Almost identical form submissions • Repeated comments with tiny typos • Duplicate product listings • "Did You Mean…?" Suggestions ✅ No ML, no extra libraries; just clean, fast, production-safe Python. 💡 Save yourself from messy string comparisons and spammy inputs. I wrote a short, practical post with real API examples. 👉 https://lnkd.in/ge9-k3Z5 #Python #Backend #APIs #Django #CleanCode
To view or add a comment, sign in
-
Day 186/200 Methods used to work with files in Python. I learnt about two important methods when reading from and writing to files in Python. .read() method and .write() method. The .read() method converts files into strings. It is used to display the contents of files. Once a file has been read using .read() method, a string of the file content is generated and you can perform the same operations on it that you might perform with any other string. The .write() method writes string data to a specified file. It can be represented with two letters; “w” or “a”. “w” is used to replace the contents of an existing file, overwriting it. It can also be used to create a new file. “a” is used to append new information to the end of an existing file rather than overwriting it. When “a” is used, the existing information in the file will not be deleted. With both "w" and "a", you can use the .write() method. “w” stands for write. “a” stands for append. It's important for security professionals to be able to import files into Python and then read from or write to them.
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
Learning Python as a beginner doesn’t have to be confusing. I share simple, structured Python lessons and coding tips on my YouTube channel for people starting out in tech. 🎥 Subscribe here: https://youtube.com/@tonybenard7210?si=8R6opV3kZ_HDR242