Python – Strings & Conditional Statements (Chapter 2)

Strings – Core Concepts

  • A string is a sequence of characters.
    • May contain 0, 1 or many characters; can store a word, a sentence, even a paragraph.
    • Belongs to Python’s sequence data-types (already encountered in Chapter 1).

Creating strings (3 syntaxes)
  • Double quotes – most common and preferred:

  s1 = "This is a string"
  • Single quotes – equally valid:

  s2 = 'hello'
  • Triple quotes – for multi-line text or docstrings:

  s3 = '''This is
a multi-line
string.'''
Why 3 quoting styles?
  • To embed one type of quote inside another without escaping.
    • Want an apostrophe? Use double quotes: "This is Shraddha's notebook".
    • Want embedded double quotes? Wrap the whole text in single quotes or triple quotes.

Escape-sequence characters (formatting helpers)

Code

Meaning

\n

line break (newline)

\t

horizontal tab

\\

literal back-slash

\'

literal single quote inside single-quoted string

\"

literal double quote inside double-quoted string

Example – insert a newline and a tab:

s = "This is a string\n\twritten on next line with a tab"
print(s)

Fundamental Operations on Strings

1. Concatenation
  • Combine two strings via +.

  first = "अपना"
  second = "college"
  final = first + " " + second    # space deliberately added
  print(final)          # अपना college
  • Operation is called concatenation. Works only between strings.

2. Length
  • Built-in function len()\text{len}(\cdot) gives total number of characters including spaces & special symbols.

  n = len(final)        # 12, because space counts as 1 char
3. Indexing (random access)
  • Characters auto-labelled with indices starting at 00 from the left.
    final[0] → first char,
    final[4] → the space in “अपना college”.

  • Attempting to assign: final[4] = '-' ⇒ error “str object does not support item assignment” (immutability!).

4. Negative Indexing
  • Python also allows counting from right: last char = 1-1, second-last = 2-2

  word = "apple"
  word[-3]    # 'p'
5. Slicing

Extract a sub-string via [start:end][\text{start} : \text{end}]
start index inclusive, end exclusive.
• Either bound may be omitted (defaults to 0 or len).

  text = "अपना college"
  text[1:4]   # 'pna'
  text[:4]    # 'अपना'
  text[5:]    # 'college'
  text[-3:-1] # 'le'

Essential String Methods (all return new strings, originals unchanged unless re-assigned)

  1. str.endswith(substr)
    • Returns True/False whether str finishes with given substring.

   sentence.endswith("ege")   # True
  1. str.capitalize()
    • Makes first character upper-case; rest lower.

   s = "hello world"
   s_cap = s.capitalize()      # 'Hello world'
   s = s.capitalize()          # overwrite if you need permanent change
  1. str.replace(old, new)
    • Replaces all occurrences of old with new.

   "room 101".replace("o", "0")   # 'r00m 101'
  1. str.find(substr)
    • Returns first starting index of substr; 1-1 if not found.

  2. str.count(substr)
    • Returns number of (possibly overlapping) occurrences.

Practical tip

You will not memorise every method; in real projects engineers quickly search or take help from editor suggestions – understanding logic matters more than rote learning.


Conditional Statements

Syntax skeleton
if CONDITION1:
    stmt_block_1
elif CONDITION2:
    stmt_block_2
elif CONDITION3:
    ...
else:
    default_block

Rules

  • if block executes when its condition is True\text{True}.

  • As soon as one block runs, interpreter skips all remaining elif/else siblings.

  • else (optional) must be last; contains no condition – executes when none of the earlier tests passed.

  • Indentation (4 spaces or a tab) defines code blocks; Python does not use {}.

Example 1 – Age & licence
age = 21
if age >= 18:
    print("Can vote and apply for licence")
else:
    print("Cannot vote")
Example 2 – Traffic light
light = "green"
if light == "red":
    print("STOP")
elif light == "green":
    print("GO")
elif light == "yellow":
    print("LOOK / WAIT")
else:
    print("Light is broken!")
Logical operators inside conditions
  • and, or, not – build compound expressions.

  if marks >= 80 and marks < 90:
      grade = 'B'
Nesting
  • One if (or loop) inside another. Completely legal:

  if age >= 18:
      if age >= 80:
          print("Cannot drive (too old)")
      else:
          print("Can drive")
  else:
      print("Too young to drive")

End-to-End Program – Grading System

marks = int(input("Enter marks: "))
if marks >= 90:
    grade = 'A'
elif marks >= 80 and marks < 90:
    grade = 'B'
elif marks >= 70 and marks < 80:
    grade = 'C'
else:
    grade = 'D'
print("Grade:", grade)

Flow

  1. Input → integer marks.

  2. Cascade through ranges using if/elif.

  3. Output corresponding letter grade.


Practice Problems & Approaches

1. Odd or Even

Logic: a number is even if remainder after division by 2 is 0.
Formula: num%2==0\text{num} \% 2 == 0
Code (minimal):

n = int(input())
print("Even" if n % 2 == 0 else "Odd")
2. Largest of Three Numbers

Steps

  1. Read a,b,ca,b,c.

  2. Compare hierarchically using if-elif-else or nested if.

   if a >= b and a >= c:
       largest = a
   elif b >= c:
       largest = b
   else:
       largest = c

Extension homework → generalise to n numbers (hint: loop or use max() built-in).

3. Multiple of 7 Checker

Criterion: num%7==0\text{num} \% 7 == 0.

x = int(input())
if x % 7 == 0:
    print("Multiple of 7")
else:
    print("Not a multiple of 7")

Programming Tips Mentioned

  • Immutability of strings ⇒ you must build new strings for modifications.

  • Google / docs during development is normal; focus on logical understanding, not brute memorisation.

  • Indentation is syntactically mandatory in Python; always maintain consistent four-space blocks.


Real-World & Future Relevance

  • String slicing & indexing are critical for data-cleaning in Machine Learning / Data Science.

  • Conditional statements form the decision-making backbone in every non-trivial program – from simple CLI apps to production servers.


(End of Chapter 2 study notes)