Complete Python Language Series: Chapter 2

May 30, 2024

Complete Python Language Series: Chapter 2

Introduction

  • Lecture Focus: Python Strings and Conditional Statements
  • Resources: Notes available in the playlist for download in the description box

Python Strings

Data Type

  • Definition: Sequence of characters (single character, word, sentence, paragraph)
  • Creation: Strings can be created using:
    • Double quotes: "This is a string"
    • Single quotes: 'single word'
    • Triple quotes: '''This is a string'''

String Creation Examples

  • Example using VS Code lecture2.py file:
    string1 = "This is a string"
    string2 = 'single word'
    string3 = '''This is a string'''
    
  • Preferred Method: Double quotes
  • Reason for Different Quotes: To handle apostrophes conveniently:
    string = "This is Amit's book"
    
    Ensures no confusion by the interpreter.

Multi-line Strings

  • Escape Sequence Characters: For formatting (e.g., new lines \n, tabs \t)
  • Example:
    string = "This is a string\nWe are creating it in Python"
    print(string)
    
    Output:
    This is a string
    We are creating it in Python
    

String Operations

Concatenation

  • Definition: Joining two strings using + operator
  • Example:
    string1 = "Amit"
    string2 = "College"
    final_string = string1 + " " + string2
    print(final_string) # Output: "Amit College"
    

Length of String

  • Function: len() to find string length
  • Example:
    length = len(string1)
    print(length) # Output: 4
    

String Indexing & Slicing

Indexing

  • Zero-based Index: First character index is 0
  • Access Character: Using [index]
  • Example:
    string = "Python"
    print(string[0]) # Output: 'P'
    print(string[1]) # Output: 'y'
    
  • Negative Indexing: To access characters from the end, starting with -1
    print(string[-1]) # Output: 'n'
    print(string[-2]) # Output: 'o'
    

Slicing

  • Definition: Accessing parts of a string using [start:end]
    part = string[1:4] # Output: 'yth'
    
  • Note: start index included, end index excluded
  • Omitting Indices: Implies start from beginning/end
    part = string[:4] # Output: 'Pyth'
    part = string[3:] # Output: 'hon'
    

String Functions

  • Common Functions: Endswith, Capitalize, Replace, Find, and Count
  • Example Usage:
    • endswith: Checks if a string ends with certain characters
      string.endswith("ing") # Output: True
      
    • capitalize: Capitalizes the first character
      string.capitalize()
      
    • replace: Replaces old substring with new
      string.replace("Python", "Java")
      
    • find: Finds first occurrence of substring
      string.find("thon") # Output: 2
      
    • count: Counts occurrences of substring
      string.count("a")
      

Conditional Statements

Introduction

  • Purpose: Control the flow of code execution based on conditions
  • Keywords: if, elif, else
  • Syntax: Writing Rules
    • Example:
      if condition:
          # Execute this block
      elif other_condition:
          # Execute this block
      else:
          # Execute this block
      
    • Note: Indentation (4 spaces/tab) is crucial

Practical Examples

Example: Voter Eligibility

  • Code: Check if age allows voting
    age = 21
    if age >= 18:
        print("Can vote and apply for license")
    else:
        print("Cannot vote")
    

Example: Traffic Lights

  • Code: Actions based on traffic light color
    light = "green"
    if light == "red":
        print("Stop")
    elif light == "green":
        print("Go")
    else:
        print("Look")
    

Nested Conditional Statements

  • Definition: if statement inside another if
  • Usage: For complex conditions
  • **Example:
    age = 95
    if age >= 18:
        if age >= 80:
            print("Cannot drive")
        else:
            print("Can drive")
    else:
        print("Cannot drive")
    

Practice Problems

  1. Odd/Even Check
    number = int(input("Enter a number: "))
    if number % 2 == 0:
        print("Even")
    else:
        print("Odd")
    
  2. Greatest of Three Numbers
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))
    c = int(input("Enter third number: "))
    if a >= b and a >= c:
        print("First is largest")
    elif b >= a and b >= c:
        print("Second is largest")
    else:
        print("Third is largest")
    
  3. Multiple of Seven
    number = int(input("Enter a number: "))
    if number % 7 == 0:
        print("Multiple of 7")
    else:
        print("Not a multiple of 7")