# Python
x = 5
if x > 0:
print("Positive")
print("Finished checking") # outside the blockPositive
Finished checking
(CSE331) Python for Data Science
Control flow determines which statements run and how often they run. We begin with decisions, then use loops to process collections.
:) starts a block after statements such as if, for, while, and def.Unlike R, Python does not use braces to delimit these blocks.
# R
x <- 5
if (x > 0) {
print("Positive")
}# Python
x = 5
if x > 0:
print("Positive")
print("Finished checking") # outside the blockPositive
Finished checking
An if block runs when its condition is true. An optional else block handles the other case.
score = 42
if score >= 40:
print("You passed the exam.")
else:
print("You failed the exam.")You passed the exam.
Use == for an equality comparison. = is assignment.
Python checks conditions from top to bottom and runs the first matching branch.
score = 75
if score < 0 or score > 100:
print("Invalid score")
elif score >= 80:
print("Excellent")
elif score >= 60:
print("Good")
elif score >= 40:
print("Pass")
else:
print("Fail")Good
These labels are illustrative performance categories, not the University’s letter-grade scale. Put higher cutoffs first when testing score >= cutoff.
and stops as soon as an operand is false; or stops as soon as an operand is true. This can avoid an invalid operation.
score = None
if score is not None and score >= 40:
print("Pass")
else:
print("Missing score or below the pass mark")Missing score or below the pass mark
The comparison score >= 40 is not evaluated when score is None.
Do not use if score: to identify a recorded score: a legitimate score of 0 is also false.
Use a conditional expression to select a value in a short, simple decision:
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)Adult
Syntax: value_if_true if condition else value_if_false. For several branches, an ordinary if/elif/else block is usually clearer.
A for loop takes each item from an iterable. Lists, tuples, strings, ranges, dictionaries, and sets are iterable.
names = ["Ayesha", "Imran", "Nadia"]
for name in names:
print(f"Hello, {name}!")Hello, Ayesha!
Hello, Imran!
Hello, Nadia!
The loop variable holds the current item. It need not be a numerical counter.
range(start, stop, step) excludes stop.
for i in range(1, 6):
print(i, i**2)1 1
2 4
3 9
4 16
5 25
Initialize the total before the loop.
# Sum of squares of the first 100 positive integers
total = 0
for i in range(1, 101):
total += i**2
print(total)338350
Use a built-in function when it already expresses the calculation:
values = [4, 7, 2]
print(sum(values))13
values = [5, -2, 0, 8, -1]
positive_values = []
for value in values:
if value > 0:
positive_values.append(value)
print(positive_values)[5, 8]
Create a new collection when filtering. Removing items from the list you are currently iterating over can skip items unexpectedly.
Looping directly over a dictionary gives its keys. Use .items() to obtain keys and values together.
scores = {"Ayesha": 72, "Imran": 64, "Nadia": 81}
for name, score in scores.items():
print(name, score)Ayesha 72
Imran 64
Nadia 81
Here each key-value pair is unpacked into two variables.
A while loop repeats as long as its condition remains true.
n = 1
while n <= 5:
print(n**2)
n += 11
4
9
16
25
Use for when processing an iterable; use while when repetition is controlled by a condition. A for loop does not require knowing the number of items in advance.
# How many doublings are needed to reach at least 100?
value = 3
doublings = 0
while value < 100:
value *= 2
doublings += 1
print(value, doublings)192 6
Ensure the condition can eventually become false, or provide a reachable break. Interrupt the kernel if a loop runs indefinitely.
values = [5, 12, 7, 0, 13, 9]
for value in values:
if value == 0:
break
print(value)5
12
7
break exits the innermost enclosing loop, not the entire program.
for n in range(1, 7):
if n == 3:
continue
print(n)1
2
4
5
6
In a while loop, take care not to skip the update that allows the loop to finish:
n = 0
while n < 6:
n += 1
if n == 3:
continue
print(n)1
2
4
5
6
Both examples print 1, 2, 4, 5, and 6.
The inner loop runs for each item in the outer loop.
for row in range(1, 4):
for column in range(1, 4):
print(row, column, row * column)1 1 1
1 2 2
1 3 3
2 1 2
2 2 4
2 3 6
3 1 3
3 2 6
3 3 9
To process a list of lists:
rows = [[4, 7], [2, 9], [5, 6]]
total = 0
for row in rows:
for value in row:
total += value
print(total)33
We will use None for a missing score. A score of zero must remain in the calculation.
students = [
{"name": "Ayesha", "score": 72},
{"name": "Imran", "score": None},
{"name": "Nadia", "score": 0},
{"name": "Rafi", "score": 84},
]
total = 0
count = 0
for student in students:
score = student["score"]
if score is None:
continue
total += score
count += 1
if count > 0:
print(f"Mean of {count} recorded scores: {total / count:.2f}")
else:
print("No recorded scores")Mean of 3 recorded scores: 52.00
Expected mean: 52.00, using three recorded scores.
Use loops and conditions; user-defined functions are introduced next.
Pass if it is at least 40 and Fail otherwise."Even" or "Odd" to parity for an integer n.7 × 1 to 7 × 10.text = "Applied Statistics", ignoring case.nums = [3, 10, -4, 7, 0, 9], build a new list containing only positive values.d = {"x": 4, "y": 9, "z": 16}, print each key and the square root of its value.[4, 7, 2, -1, 9] until the first negative value appears. Exclude that negative value and all later values.continue.[[3, 5], [2, 8], [4, 6]] using nested loops.for processes an iterable; while repeats according to a condition..items() to loop over dictionary keys and values together.