MIT 6.0001 Introduction to Comp Sci and Programming in Python 2
MIT 6.0001 Introduction to Comp Sci and Programming in Python 2
Keywords in Programming:
if, else, elif (else-if)
Computers don't make decisions. Programmers build decisions into programs.
If Statement:
Checks a condition. If true, executes a block of code.
Syntax:
python
Copy code
if condition:
# code block
If-Else Statement:
Checks a condition. If true, executes one block of code, otherwise executes another.
Syntax:
python
Copy code
if condition:
# code block 1
else:
# code block 2
If-Elif-Else Statement:
Multiple decision points.
Syntax:
python
Copy code
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
3. Loops
While Loop:
Repeats a block of code as long as a condition is true.
Syntax:
python
Copy code
while condition:
# code block
Can lead to infinite loops if not careful.
For Loop:
Iterates over a sequence (range, list, etc.).
Syntax:
python
Copy code
for variable in range(start, stop, step):
# code block
range() function: Generates a sequence of numbers.
range(stop): Generates numbers from 0 to stop-1.
range(start, stop): Generates numbers from start to stop-1.
range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.
Break Statement:
Exits the loop prematurely.
Syntax:
python
Copy code
if condition:
break
For Loops:
Used when the number of iterations is known.
Has an inherent counter.
While Loops:
Useful for unpredictable tasks, like user input.
Can use a counter, but must be initialized and incremented manually.
Can be rewritten as a for loop, but the reverse isn't always true.