Sharing notes from my ongoing learning journey — what I build, break and understand along the way.
Learning Python – Post 7: If-Else, For Loops, and Putting It All Together
Learning Python – Post 7: If-Else, For Loops, and Putting It All Together
Tonight was about bringing things together. I started exploring conditions (if
, else
, elif
) and moved into loops — especially the for
loop combined with range()
.
These two tools are powerful when you want to make decisions or repeat tasks. Here’s a breakdown of what I learned and some example code I worked through.
if
, elif
, else
– Making Decisions
I started with the basics. Here’s how you can check if a number is positive or negative:
number = -4
if number > 0:
print("The number is positive")
elif number < 0:
print("The number is negative")
else:
print("The number is zero")
Pretty straightforward, but one thing I had to get used to: indentation matters a lot in Python. If the print()
lines aren’t indented correctly, the code won’t run or will give weird results. That’s something I caught myself doing wrong a couple times.
for
Loops – Repeating Things
Next up: loops. I practiced going through lists and ranges using for
.
Here’s a very basic loop:
nums = [2, 4, 6, 8]
for num in nums:
print(num * num)
That prints the square of each number in the list.
Then I tried it with range()
instead:
for i in range(1, 6):
print(i * i)
Which prints:
1
4
9
16
25
You can also step through numbers with custom intervals:
for i in range(1, 21, 2):
print(i * i * i) # cubes of odd numbers from 1 to 20
Example: Analyzing Numbers from 1 to 20
Finally, I put everything together into one combined piece. It loops through numbers from 1 to 20, and for each number, it:
- Prints the number
- Says whether it’s even or odd
- Says whether it’s positive or negative (kind of obvious here, but still)
- Prints its square
Here’s the full example:
numbers = list(range(1, 21))
for number in numbers:
print("Number:", number)
if number % 2 == 0:
print("- Even")
else:
print("- Odd")
if number > 0:
print("- Positive")
elif number < 0:
print("- Negative")
else:
print("- Zero")
print("- Square:", number * number)
print("-------------------")
Notes to Self:
- Again: indentation is everything in Python. One extra space can cause a logic error.
range()
doesn’t include the last number (e.g.,range(1, 21)
goes up to 20).- Always double-check logic blocks — like when to use
elif
instead of just anotherif
.