Understand Python: LESSON 9 LOOPS IN PYTHON Imagine you want to print "Hello" 5x Without loops, we would do: print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") This is repetitive and inefficient. A loop enables Python to execute instructions repeatedly. ■ What Is a Loop? A loop is a programming structure that repeats a block of code until a condition is met. ■ Types of Loops in Python Python has two main loops: 1. for loop → used when the number of repetitions is known 2. while loop → used when the number of repetitions is unknown ■ The for Loop What Is a for Loop? A for loop is used to iterate over a sequence, such as: • List • String • Range of numbers Basic Syntax: for variable in sequence: # code to repeat Example 1: for i in range(5): print("Hello") Output: Hello Hello Hello Hello Hello 🔹 range(5) means numbers from 0 to 4 Example 2: for i in range(1, 6): print(i) Output: 1 2 3 4 5 ■ The while Loop What Is a while Loop? A while loop repeats as long as a condition is True. Basic Syntax: while condition: # code to repeat Example 1: count = 1 while count <= 5: print(count) count += 1 The count += 1 updates/increases the count value after each loop till it gets to 5 (while count <= 5) Output would be: 1, 2, 3, 4, 5 ⚠️ Always update the condition to avoid infinite loops. Example 2: password = "" while password != "1234": password = input("Enter password: ") print("Access granted") ■ Infinite Loops while True: print("This will run forever") Use this only when necessary, and always include a way to stop it. ■ Common Mistakes Beginners Make ❌ Forgetting to update the while condition ❌ Using wrong indentation ❌ Confusing for and while ❌ Creating infinite loops ■ When to Use Which Loop? • Known number of repetitions, use for loop • Unknown repetitions, use while loop • Looping through list/string, use for loop • Condition-based repetition, Use while loop #Python
Python Loops: For and While Explained
More Relevant Posts
-
Understand Python: LESSON 11 NESTED LOOPS IN PYTHON ■ What Is a Nested Loop? A nested loop is a loop inside another loop. • The outer loop runs first • For each run of the outer loop, the inner loop runs completely ■ Basic Syntax of Nested Loops 1. Nested for Loop > for outer in sequence1: for inner in sequence2: # code runs for each inner loop 2. Nested while Loop > while condition1: while condition2: # code runs for each inner loop ■ How Nested Loops Work (Very Important) Let’s visualize this: examples Example 1: Nested for Loop for i in range(3): for j in range(2): print(i, j) This can be a bit confusing, but here is a Step-by-step breakdown: • i = 0 → j runs 0, 1 • i = 1 → j runs 0, 1 • i = 2 → j runs 0, 1 Output becomes: 0 0 0 1 1 0 1 1 2 0 2 1 ➡️ Inner loop runs fully for each outer loop cycle. Example 2: Nested while Loop i = 1 while i <= 3: j = 1 while j <= 2: print(i, j) j += 1 i += 1 (What would be our output for this 👆. Drop your answer in the comment.) ⚠️ Always update both loop variables to avoid infinite loops. ■ When Should You Use Nested Loops? Use nested loops when: • Working with tables or grids • Handling 2D lists (matrices) • Generating patterns • Comparing each item in one list with another ■ When to Avoid Nested Loops Avoid nested loops when: • A simpler solution exists • Performance matters (large data) • Logical operators or built-in functions can solve. 📌 Drop your questions and contributions 👇. Let's grow together. #Python
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
Understand Python: LESSON 10 LOOP CONTROL STATEMENTS IN PYTHON Normally, loops run from start to finish. But sometimes, we want to: • Stop a loop early • Skip a particular step • Leave a placeholder for future code Python provides loop control statements for this purpose. ■ What Are Loop Control Statements? Loop control statements change the normal flow of a loop. Python has two main loop control statements: 1. break 2. continue ■ The break Statement break is used to immediately stop a loop, even if the loop condition is still true. Example 1: for i in range(10): if i == 5: break print(i) Our Output would be: 0 1 2 3 4 ➡️ Once i becomes 5, the loop stops completely. ■ The continue Statement continue is used to skip the current iteration and move to the next one. Example 1: for i in range(5): if i == 2: continue print(i) Our Output: 0 1 3 4 ➡️ When i is 2, Python skips printing and continues. ■ When to Use Each: 1. Use break when a goal is reached 2. Use continue to ignore unwanted cases Let's look at a few more examples. ▪︎ Example 1: numbers = [2, 4, 6, 8, 9, 10] for num in numbers: if num % 2 != 0: print("First odd number found:", num) break (Drop the answer to this 👆 in the comment) ▪︎ Example 2: for i in range(1, 11): if i % 2 != 0: continue print(i) ➡️ Prints only even numbers. #python
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 5 of Python Programming: Working with Text (Strings) in Python 🐍📝 (Text is everywhere in programming) 1/ So far, we’ve printed text and done math. Today, we learn how Python handles text properly. In Python, text is called a string. 2/ A string is anything inside quotes: code Python name = "Kehinde" country = "Nigeria" If it’s inside " " or ' ', Python treats it as text. 3/ You can combine strings together. This is called concatenation. Example: code Python first_name = "Kehinde" last_name = "Fasola" print(first_name + " " + last_name) That space " " is important 👀 4/ Let’s fix a common beginner problem. This will cause an error ❌ code Python age = 25 print("I am " + age) Why? Because Python can’t mix text and numbers directly. 5/ Correct way #1: Separate with commas ✅ code Python age = 25 print("I am", age, "years old") Python handles the conversion for you. 6/ Correct way #2 (BEST way): f-strings 🔥 code Python name = "Kehinde" age = 25 print(f"My name is {name} and I am {age} years old") This is clean, modern, and powerful. 7/ Strings can also be: • Uppercase • Lowercase • Counted Examples: code Python text = "Python" print(text.upper()) print(text.lower()) print(len(text)) Python gives you tools for free. 8/ Today’s challenge Create variables for: ✔ Your name ✔ Your age ✔ Your country Print ONE sentence using an f-string like: code: My name is ___, I am ___ years old and I live in ___ Reply DONE if it worked 9/ Tomorrow (Day 6): • Getting input from users • Making programs interactive • Your code will start asking questions 😎 Follow & turn on notifications 🐍💻 You’re leveling up fast.
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
-
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
-
DAY 6 of Python Programming: Getting User Input in Python 🐍⌨️ (Now your programs can ask questions) 🧵👇 1/ So far, our programs talk. Today, they start listening. We’ll learn how to get input from the user. This is a big step. 2/ Python uses the input() function to collect user input. Example: code name = input("What is your name? ") print(name) Run it. Type your name. Press Enter. Your program just interacted with you. 3/ What’s happening? • input() pauses the program • The user types something • Python stores it as text (string) Important: 👉 input() ALWAYS returns a string. 4/ Let’s combine input with what we already know. code name = input("Enter your name: ") country = input("Enter your country: ") print(f"My name is {name} and I live in {country}") Your program now feels alive. 5/ Common beginner mistake 🚫 This will NOT work: code age = input("Enter your age: ") print(age + 5) Why? Because age is a string. 6/ To fix it, we convert input to a number. code age = int(input("Enter your age: ")) print(age + 5) Now Python understands math again. 7/ Mini project 🧠👇 Build this program: • Ask for user’s name • Ask for user’s age • Calculate age in 5 years • Print a full sentence Example output: Hello Kehinde, in 5 years you’ll be 30 years old. 8/ Today’s challenge 👇 ✔ Use input() at least twice ✔ Use an f-string ✔ Perform one calculation Reply DONE if it worked 💪 9/ Tomorrow (Day 7): • Mini project • Combine everything learned so far • You’ll feel like a real programmer 😎 Follow & turn on notifications 🐍💻 This is where confidence builds.
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 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
-
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
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