Downloads are text notes. Choose Save as PDF in your browser’s print dialog for a PDF copy.
Understand the concept
A for loop visits each item in an iterable such as a list. Python uses indentation to group the loop body. range(3) yields 0, 1, and 2; the stop value is excluded. An if statement lets you choose which values to process.
A function groups work under a name. Parameters receive inputs; return sends a result back to the caller. print displays a value but does not replace return. A function without an explicit return returns None.
Keep functions focused. An accumulator starts with an initial value and updates during iteration. Return after the loop when you need the result from all items; returning inside it often ends the function too early. Think about empty inputs and boundary values.
Run the example
def total_positive(values):
total = 0
for value in values:
if value > 0:
total += value
return total
print(total_positive([4, -2, 6, 0]))
print(total_positive([]))
Output / what to expect
10
0
Try it yourself
Write count_even(values) that returns how many integers are even. Check [2, 3, 4, 0] and an empty list.
View a suggested solution
def count_even(values):
count = 0
for value in values:
if value % 2 == 0:
count += 1
return count
print(count_even([2, 3, 4, 0])) # 3
print(count_even([])) # 0
for loop list jaise iterable ka har item ek-ek karke leta hai. Indentation batata hai kaunsa code loop ke andar hai. range(3) se 0, 1, 2 milte hain; stop value include nahi hoti. if condition se decide karo kaunsi values process karni hain.
Function repeated kaam ko ek naam deta hai. Parameters inputs lete hain; return result caller ko wapas deta hai. print sirf screen par dikhata hai, return ka replacement nahi hai. Explicit return nahi ho toh function None return karta hai.
Function ko ek clear task do. Accumulator initial value se shuru hota hai aur loop mein update hota hai. Sab items ka result chahiye toh return loop ke baad rakho. Loop ke andar return karne se function jaldi khatam ho sakta hai. Empty list aur boundary values bhi socho.
Code chalao
def total_positive(values):
total = 0
for value in values:
if value > 0:
total += value
return total
print(total_positive([4, -2, 6, 0]))
print(total_positive([]))
Output / kya expect karein
10
0
Ab khud try karo
count_even(values) banao jo even integers ki ginti return kare. [2, 3, 4, 0] aur empty list dono check karo.
Solution dekho
def count_even(values):
count = 0
for value in values:
if value % 2 == 0:
count += 1
return count
print(count_even([2, 3, 4, 0])) # 3
print(count_even([])) # 0
Run the example and attempt the exercise before marking this lesson complete.
pass the idea on
What did this make you think?
You review and publish the post yourself. Instagram uses your device’s share menu when available; otherwise copy the text and link. Facebook opens the link composer, where you add your thoughts.