Lists, conditional statements, loops
This module includes:
1. Start with strings
We learned that string is a sequence of characters. You can treat it like a list of single-character elements.
▷ Indexing
Use square brackets []
to retrieve a single character. Indices start at 0
; negative indices count from the end.
sample = "sample"
print(sample[0]) # → 's' (first character)
print(sample[1]) # → 'a' (second character)
print(sample[-1]) # → 'e' (last character)
▷ Slicing
Retrieve a substring by specifying a start and end index: [start:end]
grabs characters at positions start
up to (but not including) end
.
s = "sample"
print(s[0:1]) # → 's'
print(s[0:2]) # → 'sa'
print(s[1:-1]) # → 'ampl'
print(s[1:]) # → 'ample'
print(s[:2]) # → 'sa'
▷ Concatenation
Join strings with the +
operator:
a = "super"
b = "awesome"
print(a + b) # → 'superawesome'
print(a + " " + b) # → 'super awesome'
▷ Membership test
Use the in
operator to check if a substring exists:
word = "awesome"
if "a" in word:
print("Contains 'a'!") # → Contains 'a'!
else:
print("No 'a' found.")
2. Lists
A list is an ordered, mutable collection of any Python objects. Lists use square brackets and commas.
platforms = ["Windows", "Mac", "Linux"]
▷ Indexing and slicing
Just like we used indexing and slicing for strings, lists also support the same rules:
print(platforms[1]) # → 'Mac'
print(platforms[1:]) # → ['Mac', 'Linux']
▷ Concatenation
Combine lists with +
:
numbers = [1, 2, 3]
combined = platforms + numbers
print(combined)
# → ['Windows', 'Mac', 'Linux', 1, 2, 3]
▷ Mutability
.append(x)
adds an element to the end.lst[i] = x
replaces the element at indexi
.
platforms.append("Android")
print(platforms)
# → ['Windows', 'Mac', 'Linux', 'Android']
platforms[0] = "FreeBSD"
print(platforms)
# → ['FreeBSD', 'Mac', 'Linux', 'Android']
3. Conditional Statements
Branch your code using if
, elif
, and else
. Conditions use comparison or membership operators.
x = 2
if x < 2:
print("x is less than 2")
elif x == 2:
print("x is exactly 2") # → x is exactly 2
else:
print("x is greater than 2")
- Examples with strings and lists:
# String comparison
s = "python"
if s == "python":
print("Match!") # → Match!
# Membership test in list
langs = ["Python", "Java", "C++"]
if "Python" in langs:
print("Found Python!") # → Found Python!
4. Loops
Loops repeat a block of code for each item in an iterable.
▷ for
loops
for
loops are used when you know how many times you want to repeat something. It iterates over a sequence (like a list, string, or range).
words = ["read", "code", "repeat"]
for w in words:
print(w)
# → read
# → code
# → repeat
You can nest conditionals inside loops:
for w in words:
if "e" in w:
print(w)
# → read
# → repeat
▷ while
loops
while
loops are used when you want to keep repeating until a condition is no longer true. The number of repetitions is not fixed in advance.
count = 0
while count < 3:
print(count)
count += 1
# → 0
# → 1
# → 2
# you might want to test the different between for vs. while loops by running the following code!
words = ["read", "code", "repeat"]
while w in words:
print(w)
5. Exercises
-
String indexing and slicing
- Assign
"programming"
tos
. - Print the first character, last character, and substring
"gram"
.
- Assign
-
List operations
- Create
fruits = ["apple", "banana", "cherry"]
. - Append
"date"
, replace"banana"
with"blueberry"
, and printfruits[1:]
.
- Create
-
Conditional logic
- Given
n = 7
, write anif
block that prints whethern
is even or odd.
- Given
-
Loop practice
- Write a
for
loop over the list[2, 4, 6, 8, 10]
that prints each number divided by 2.
- Write a
-
Combined task
- Write a function
filter_long_words(words, min_length)
that returns a list of words whose length ≥min_length
. - Test it on
["data", "analysis", "python", "AI"]
withmin_length=5
.
- Write a function