Neural Sync Active
Week 2: Control Flow - Conditionals and While Loops
Registry Synced
Week 2: Control Flow - Conditionals and While Loops
458 words
2 min read
Course: Jan 2026 - Python Difficulty: Intermediate Focus: Logic branching, relational operators, and indefinite loops.
1. Relational and Logical Operators
To make decisions in code, we need to compare values. These operations always result in a Boolean (
True or False).1.1 Relational Operators
==(Equal to)!=(Not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
1.2 Logical Operators
Used to combine multiple conditions:
and: True only if both operands are True.or: True if at least one operand is True.not: Reverses the Boolean value.
2. Conditional Statements (if, elif, else)
Conditional statements allow your program to execute different blocks of code based on conditions. Python uses indentation (usually 4 spaces) to define blocks.
2.1 Syntax
pythonscore = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") else: print("Grade: F")
2.2 Nested Conditionals
You can place
if statements inside other if statements.pythonnum = 10 if num > 0: if num % 2 == 0: print("Positive Even") else: print("Positive Odd")
3. String Basics
Strings are ordered sequences of characters.
3.1 Indexing
Characters can be accessed using their position (index), starting from 0. Negative indexing starts from the end (-1 is the last character).
pythonword = "Python" print(word[0]) # Output: 'P' print(word[-1]) # Output: 'n'
3.2 Basic String Operations
- Concatenation (
+):"Hello" + "World"results in"HelloWorld" - Repetition (
*):"A" * 3results in"AAA" - Length:
len("Python")returns6
4. The while Loop
A
while loop repeatedly executes a block of code as long as a specified condition evaluates to True.4.1 Structure
pythoncount = 0 while count < 3: print("Count is:", count) count = count + 1 # Crucial to avoid an infinite loop!
Output:
Count is: 0 Count is: 1 Count is: 2
4.2 Common Use Case: Input Validation
while loops are excellent when you don't know beforehand how many times the loop will run.pythonpassword = "" while password != "secret123": password = input("Enter password: ") print("Access Granted!")
Caution
Infinite Loops: If the condition in a
while loop never becomes False (e.g., you forget to increment a counter), the loop will run forever, crashing your program.🧭 Navigation
- 📘 Textbook Notes: Week 2 Notes
- 📝 Assignment: Week 2 Assignment
- ⬅️ Previous Week: Week 1 Notes
- ➡️ Next Week: Week 3 Notes