3.0 University logo
  • Home
  • About us
  • All Courses
    • Cybersecurity Programs
      • Certified Ethical Hacker (CEH v13)
      • Certified SOC Analyst
      • Certified Penitration Testing Professional
      • Computer Hacking Forensic Investigator
      • Certified Cybersecurity Technician (CCT)
      • Certified AI Program Manager
      • Certified Offensive AI Security Professional
      • Certified Responsible AI Governance & Ethics Professional
      • Artificial Intelligence Essentials
    • Crypto Market Programs
    • Blockchain & Web3 Programs
      • Digital Assets Trading & Analysis Program
      • Certified Web3 Strategy & Growth Specialist
      • Certified Web3 Governance & Compliance Expert
      • Full Stack Blockchain Developer Program
      • Private Blockchain Developer Program
      • Public Blockchain Developer Program
    • IGM x IIG Programs
      • Jewellery Design Executive Program
      • Gems & Diamond Specialist Program
      • Jewellery Business Specialist Program
  • Schools
    • School of Decentralized Economics
    • School of Cyber Resilience
    • School of Intelligent Systems
    • School of Design Thinking
  • Partners
    • Certification & Knowledge Partner
    • Academic Partner
    • Hiring Partner
    • Delivery Partner
    • Affiliate Partner
    • Hybrid Center Partner
  • Blog
  • Home
  • About us
  • All Courses
    • Cybersecurity Programs
      • Certified Ethical Hacker (CEH v13)
      • Certified SOC Analyst
      • Certified Penitration Testing Professional
      • Computer Hacking Forensic Investigator
      • Certified Cybersecurity Technician (CCT)
      • Certified AI Program Manager
      • Certified Offensive AI Security Professional
      • Certified Responsible AI Governance & Ethics Professional
      • Artificial Intelligence Essentials
    • Crypto Market Programs
    • Blockchain & Web3 Programs
      • Digital Assets Trading & Analysis Program
      • Certified Web3 Strategy & Growth Specialist
      • Certified Web3 Governance & Compliance Expert
      • Full Stack Blockchain Developer Program
      • Private Blockchain Developer Program
      • Public Blockchain Developer Program
    • IGM x IIG Programs
      • Jewellery Design Executive Program
      • Gems & Diamond Specialist Program
      • Jewellery Business Specialist Program
  • Schools
    • School of Decentralized Economics
    • School of Cyber Resilience
    • School of Intelligent Systems
    • School of Design Thinking
  • Partners
    • Certification & Knowledge Partner
    • Academic Partner
    • Hiring Partner
    • Delivery Partner
    • Affiliate Partner
    • Hybrid Center Partner
  • Blog
    Login
    ₹0.00 0 Cart

    Learn Articles

    • Home
    • Learn Articles

    Python Loops and Conditional Statements Explained With Examples

    • Posted by 3.0 University
    • Date August 24, 2026
    • Comments 0 comment

    A for loop in Python repeats a block of code for every item in a sequence, such as a list, string or range of numbers. You write it as for item in sequence: followed by an indented block. Python has two loop types: for and while. Both are controlled with break, continue and pass.

    • Python has exactly two loop types: for and while. There is no built-in do-while loop.
    • Conditions use if, elif and else in that order. You can chain as many elif blocks as you need.
    • Indentation is mandatory. Four spaces per level is the PEP 8 standard. Mixing tabs and spaces crashes your program.
    • range() is exclusive at the top end. range(1, 6) gives you 1 through 5, not 6.
    • pass is a legal no-op. It holds an empty block open without a syntax error while you build out the logic.

    According to the Stack Overflow Developer Survey 2024, Python is the most popular programming language for the third consecutive year, used by 51% of professional developers surveyed globally. That makes understanding what is for loop in Python one of the most practically valuable things a beginner can learn right now.

    Writing Conditions with if, elif and else in Python

    Conditional statements let your program make decisions. In Python the syntax is cleaner than most languages: no parentheses around the condition, no curly braces around the body. The colon and indentation do all the work.

    Here is a grading example used throughout this article. A student scores 72 out of 100 and you want to print their grade letter:

    marks = 72
    
    if marks >= 90:
        grade = "A"
    elif marks >= 75:
        grade = "B"
    elif marks >= 60:
        grade = "C"
    elif marks >= 40:
        grade = "D"
    else:
        grade = "F"
    
    print("Grade:", grade)

    Run that and you get Grade: C. Python checks each condition from top to bottom and stops the moment one is true. The else block catches everything that does not match any earlier condition. This student-marks scenario is deliberately familiar: Python is now a core subject in IIT, NIT and many state engineering curricula across India, so the grading script maps directly to real lab exercises.

    How to Use if-else in Python Without Making a Mess

    The single most common beginner mistake is forgetting the colon. if marks >= 90 without the colon gives you a SyntaxError before the program even runs. The second mistake is inconsistent indentation. Python’s official style guide, PEP 8, recommends four spaces per indentation level. Most editors like VS Code and PyCharm enforce this automatically. If you are studying at a coaching institute or following a GATE or UPSC tech curriculum, your lab computers may default to tabs. Pick one and never mix them in the same file.

    Nested Conditions and Indentation Errors

    You can nest an if inside another if. Say you want to flag students who scored above 90 but also submitted late:

    marks = 93
    submitted_late = True
    
    if marks >= 90:
        if submitted_late:
            grade = "A (late penalty applies)"
        else:
            grade = "A"
    else:
        grade = "Below A"

    Each nested level adds four more spaces. If you see IndentationError: unexpected indent, one line has more spaces than Python expected. If you see IndentationError: unindent does not match any outer indentation level, you have mixed tabs and spaces. The fix: select all, convert to spaces, re-run.

    For Loops and While Loops in Python: Core Differences

    What is for loop in Python versus a while loop? A for loop iterates over a known sequence. A while loop runs until a condition fails. Use a for loop when you know the collection size upfront; use a while loop when you do not.

    Feature for loop while loop Typical use case
    Iteration basis Sequence / iterable Boolean condition for: lists, strings, range(); while: user input, polling
    Iteration count known upfront? Yes No for: fixed datasets; while: unknown repetitions
    Risk of infinite loop Low High if condition never becomes false Always include a break or condition update in while
    do-while equivalent No while True + break Guarantee body runs at least once
    Python popularity (SO Survey 2024) 51% of professional developers use Python; loops are its most-taught construct

    How to Use a for Loop in Python with range()

    The python for loop with range() is the most common pattern for numeric iteration. Here is the class grading scenario with a list of marks:

    class_marks = [85, 42, 91, 67, 55, 38, 76]
    
    for marks in class_marks:
        if marks >= 90:
            grade = "A"
        elif marks >= 75:
            grade = "B"
        elif marks >= 60:
            grade = "C"
        elif marks >= 40:
            grade = "D"
        else:
            grade = "F"
        print(f"Marks: {marks} | Grade: {grade}")

    The loop runs seven times, once per item. range(1, 8) produces integers 1 through 7. The stop value is always excluded. A lot of beginners write range(1, 7) expecting seven iterations and get six. Check your stop value every time.

    The NASSCOM Future Skills Report 2023 found that Python proficiency ranks among the top three skills Indian employers look for in entry-level tech roles, with demand concentrated in Bengaluru, Hyderabad and Pune. Knowing what is for loop in Python and how to apply it to real datasets is the baseline those employers test in screening rounds.

    Using enumerate() to Get Index and Value Together

    When you need the position of each item alongside its value, use python enumerate. It is cleaner than maintaining a counter variable manually:

    for index, marks in enumerate(class_marks, start=1):
        print(f"Student {index}: {marks} marks")

    This prints Student 1: 85 marks, Student 2: 42 marks and so on. The start=1 argument tells enumerate() to begin counting at 1 instead of 0, which makes output readable for non-technical stakeholders.

    How to Use a while Loop in Python

    A python while loop keeps running as long as a condition stays true. Use it when you do not know in advance how many iterations you need:

    marks = -1
    
    while marks < 0 or marks > 100:
        marks = int(input("Enter marks (0-100): "))
    
    print("Valid marks entered:", marks)

    The loop will not exit until the input falls between 0 and 100. That is the core difference from a for loop: a for loop iterates over a known sequence; a while loop runs until a condition fails.

    Is There a do-while Loop in Python?

    No. Python does not have a do-while loop. The standard replacement is a while True loop with a break at the end:

    while True:
        marks = int(input("Enter marks (0-100): "))
        if 0 <= marks <= 100:
            break
    
    print("Accepted:", marks)

    This runs the body at least once, then breaks out when the condition is met. It is the accepted Python idiom and you will see it in production codebases regularly.

    Nested Loops: Printing a Marks Grid

    A nested loop places one loop inside another. Each time the outer loop runs once, the inner loop completes all its iterations:

    students = ["Riya", "Arjun", "Sneha"]
    subjects = ["Maths", "Science", "English"]
    
    for student in students:
        for subject in subjects:
            print(f"{student} - {subject}")

    That produces nine lines: every combination of student and subject. Nested loops are common in data processing and matrix operations. If you are curious how Python feeds into large-scale analytics work, check out the Big Data Analytics notes on this platform.

    break, continue and pass: Python Loop Control Statements

    These three keywords give you fine-grained control over what happens inside a loop. Beginners often confuse them, so here is a precise breakdown.

    break: Exit the Loop Early

    break stops the entire loop immediately and moves execution to the first line after the loop block. Use it when you have found what you were looking for:

    for marks in class_marks:
        if marks < 40:
            print(f"First failing mark found: {marks}")
            break

    The loop stops the moment it finds the first mark below 40. That saves processing time on large datasets, which matters when Python scripts run against Naukri.com-scale candidate databases or government exam result files.

    continue: Skip One Iteration

    continue skips the rest of the current iteration and jumps straight to the next one. The loop itself keeps going:

    for marks in class_marks:
        if marks < 40:
            continue
        print(f"Processing marks: {marks}")

    Marks below 40 are silently skipped. Every other mark gets processed. This is useful for filtering out invalid or irrelevant data without breaking the whole loop.

    What Does the pass Statement Do in Python?

    pass is a placeholder. It does nothing at runtime but satisfies Python's requirement that an indented block cannot be empty:

    for marks in class_marks:
        if marks >= 90:
            pass  # TODO: send distinction email
        else:
            print(f"Standard result: {marks}")

    Without pass, an empty if block throws a SyntaxError. With it, the program runs fine. It is a legitimate tool, not a shortcut to avoid writing real logic.

    Loop Control Keywords at a Glance

    Keyword What it does Loop continues? Common use case
    break Exits the loop entirely No Stop when a match is found
    continue Skips current iteration Yes Filter out unwanted values
    pass Does nothing, holds the block Yes Placeholder during development
    else on loop Runs if loop completes without break N/A Confirm no early exit occurred

    Python also supports an else clause on loops, which most beginners do not know about. It runs only if the loop finished normally without hitting a break. It is genuinely useful for search patterns where you want to confirm nothing was found.

    The GitHub Octoverse 2023 report confirmed Python as the most-used language on the platform, overtaking JavaScript for the first time. Learning what is for loop in Python and how loop control statements work is not optional groundwork; it is the core of everything Python does in data science, automation and AI tooling.

    If you are serious about building these skills with structured mentorship and real projects, explore the bootcamp training programs at 3.0 University, designed for students and working professionals who want to go from beginner to job-ready fast. You can also browse the online certification courses when you are ready to go deeper into cybersecurity, AI or data science.

    Connect with peers who are learning the same material in the REACH learner community, where students share code, debug together and keep each other accountable.

    Python control flow is the foundation you will need when you start working with real-world data pipelines and automation scripts. If you are thinking longer term about where programming skills take your career, read this piece on how to future-proof your career in the age of AI.

    The practical next steps this week: write the grading script by hand, not by copying it. Change the marks list, add a subject loop, and deliberately break the indentation to read the error message. Understanding what a broken program looks like is half of learning to fix one. Then browse the 3.0 University blog for more beginner-friendly Python content.

    Frequently Asked Questions

    What is a for loop in Python?

    A for loop in Python iterates over every item in a sequence, such as a list, string or range() object, and runs the indented code block once per item. It is the most common loop type for working with collections of fixed size. Python's for loop behaves like a for-each loop rather than the index-based for loops in C or Java.

    How do you write an if-else statement in Python?

    Write if condition: followed by an indented block, then else: followed by its own indented block. For multiple conditions, insert one or more elif condition: blocks between them. The colon at the end of each clause is mandatory. Python checks conditions from top to bottom and runs only the first matching block.

    Is there a do-while loop in Python?

    No. Python does not include a do-while loop. The standard replacement is while True: with a break statement inside the loop body, placed after the condition check. This guarantees the body runs at least once, which is the defining behaviour of a do-while. It is the accepted Python idiom and widely used in production code.

    What does the pass statement do in Python?

    The pass statement is a no-operation placeholder. It satisfies Python's rule that an indented block cannot be empty, without actually doing anything at runtime. Developers use it to stub out functions, classes or conditional branches they have not written yet. Removing it and leaving the block empty will cause a SyntaxError.

    How many types of loops are there in Python?

    Python has exactly two loop types: for and while. A for loop iterates over a sequence of known length. A while loop runs as long as a condition remains true and is better suited for situations where the number of iterations is not known upfront. Both support break, continue, pass and an optional else clause.

    How is a for loop used in Python for data processing in India?

    Python for loops are widely used in Indian tech roles for processing structured data: iterating over student result files, parsing government open datasets from data.gov.in, or looping through financial transaction records in fintech companies like Razorpay or Zerodha. The NASSCOM Future Skills Report 2023 confirms Python is a top-three skill for entry-level tech hiring across Indian cities.

    Last updated: June 2025. Reviewed by the 3University editorial team.

    • Share:
    3.0 University

    Previous post

    Python Operators Explained: Types, Examples and Precedence
    August 24, 2026

    Next post

    Python Functions Explained: Lambda, Recursion, Generators and Decorators
    August 24, 2026

    You may also like

    Free AI Certificate Course by Government of India
    FREE AI Course with Certificate Launched by Govt of India
    June 19, 2026
    Highest Paid Professions in India
    Highest Paid Profession in India
    June 12, 2026
    Cyber Security Course Eligibility
    Cyber Security Course Eligibility
    June 11, 2026

    Leave A Reply Cancel reply

    You must be logged in to post a comment.

    3.0 University is a pioneering academic initiative for creating a comprehensive knowledge ecosystem for emerging technologies. We have developed an in-house suite of course offerings for retail, institutional market participants and industry-at-large. 

    Facebook X-twitter Instagram Linkedin
    Quick Links
    • About us
    • Courses
    • Become a Partner
    • Contact Us
    • Blog
    • Learn
    Trending Courses
    • Certified SOC Analyst
    • Certified Ethical Hacker v13 Program
    • Certified Penitration Testing Professional
    • Full Stack Blockchain Developer
    • Certified AI Program Manager
    Policies
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer
    • Refund Policy
    Contact Us
    FT Tower, CTS No. 256 & 257, Suren Road, Chakala, Andheri (E), Mumbai-400093 India.

    +91 8657961141

    support@3university.io

    Login with your site account

    Lost your password?

    Not a member yet? Register now

    Register a new account

    Are you a member? Login now

    Login with your site account

    Lost your password?

    Not a member yet? Register now

    Register a new account

    Are you a member? Login now

    Sign In

    Welcome back! Or create an account

    OR
    Forgot password?

    Need a new verification email?

    Don't have an account? Register

    Create Account

    Already have an account? Sign in

    OR

    Already have an account? Log in

    Reset Password

    Enter your email and we'll send you a reset link.

    ← Back to login

    Check Your Email

    Almost there!
    We have sent a verification link to your email address. Please check your inbox (and spam folder) and click the link to activate your account.

    Didn't receive the email? Enter your address to resend:

    Already verified? Sign in