Python Basics: Conditional Statements and Loops

Sep 5, 2024

Data Analysis with Python Zero to Pandas

Introduction

  • Free certification course at zerotopandas.com
  • Instructor: Aakash
  • Focus: Basics of Python

Lesson 2: Conditional Statements and Loops

Conditional Statements

  • Branching: Decision making in code execution based on conditions.
  • If Statement:
    • Syntax: if condition: followed by indented block.
    • Example: Check if a number is even using modulus operator.
  • Else Statement:
    • Execute alternate block when condition is false.
    • Example: Print whether number is odd or even.
  • Elif Statement:
    • Check multiple conditions in sequence.
    • Example: Print messages based on the day of the week.
  • Truth Values:
    • Non-boolean values can be conditions; empty values = false, others = true.
  • Nesting:
    • If statements can be nested but avoid deep nesting for clarity.

Loops

  • While Loop:

    • Executes block repeatedly while condition is true.
    • Example: Calculate factorial of a number using a loop.
    • Infinite Loops: Occurs if condition never becomes false. Use Kernel Interrupt or stop button.
    • Break Statement: Exit loop before condition is false.
    • Continue Statement: Skip rest of loop block, continue with next iteration.
  • For Loop:

    • Iterate over a sequence (list, string, dictionary).
    • Syntax: for value in sequence:
    • Range Function: Define a sequence of numbers for iteration.
    • Example: Loop through days of the week or iterate over dictionary items.
    • Break and Continue: Similar usage as in while loop.

Functions and Scope

  • Defining Functions:

    • Use def keyword, can take inputs (arguments), return outputs.
    • Example Function: say_hello prints a message.
  • Arguments and Parameters:

    • Functions can accept multiple arguments, making them flexible.
    • Example: filter_even filters even numbers from a list.
  • Scope:

    • Variables inside functions are local (not accessible outside).
  • Advanced Function Features:

    • Return Values: Use return to provide output from function.
    • Default Arguments: Specify a default value for function parameters.
    • Named Arguments: Specify parameter names during function call for clarity.
  • Modules: Import external Python files, use functions without polluting namespace.

    • Example: import math to use math.ceil

Error Handling

  • Try-Except Block:
    • Catch and handle exceptions, such as divide by zero errors.
    • Example: Handle zero division error in EMI calculation.

Documentation

  • Docstrings: Document functions with descriptions.
    • Use help function to view docstring.

Exercises and Further Practice

  • Practice exercises provided to reinforce learning.
  • Encourage participation in forums for questions and discussion.