🔄 Loops & Conditions
Complete solutions with detailed explanations
📋 Questions & Solutions
# Create list 1 to 10
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Sum all except 5 and 7
total = 0
for num in numbers:
if num not in [5, 7]:
total += num
print("Sum (excluding 5 and 7):", total)
# Verify: 1+2+3+4+6+8+9+10 = 43
# Full sum would be 55, minus 5 and 7 = 55-12 = 43Sum (excluding 5 and 7): 43
🎓 Explanation
if num not in [5, 7] skips 5 and 7. Alternative: if num != 5 and num != 7. The continue keyword could also be used.
# Create list skipping multiples of 3
result = []
num = 1
while num <= 100:
if num % 3 != 0: # Not divisible by 3
result.append(num)
num += 1
print("Numbers (excluding divisible by 3):")
print(result)
print(f"\nTotal count: {len(result)}")Numbers (excluding divisible by 3): [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98, 100] Total count: 67
🎓 Explanation
% is modulo (remainder). num % 3 != 0 means "not divisible by 3". Out of 100 numbers, 33 are divisible by 3, leaving 67.
# Method 1: for loop with range
for i in range(1, 11):
print(i, end=" ")
print() # New line
# Method 2: while loop
num = 1
while num <= 10:
print(num, end=" ")
num += 11 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
🎓 Explanation
range(1, 11) generates 1 to 10 (end is exclusive). end=" " prints on same line with space separator.
# Method 1: Built-in sum with range
total = sum(range(1, 101))
print("Sum (1 to 100):", total)
# Method 2: Loop
total_loop = 0
for i in range(1, 101):
total_loop += i
print("Sum (loop):", total_loop)
# Method 3: Formula n(n+1)/2
n = 100
formula_result = n * (n + 1) // 2
print("Sum (formula):", formula_result)Sum (1 to 100): 5050 Sum (loop): 5050 Sum (formula): 5050
🎓 Explanation
The formula n(n+1)/2 is Gauss's trick! For 1 to 100: 100×101/2 = 5050. Much faster than looping for large numbers.
list1 = [11,2,190,43,23,65,19]
list2 = [12,11,121,190,43,23,76,190]
list1 = [11, 2, 190, 43, 23, 65, 19]
list2 = [12, 11, 121, 190, 43, 23, 76, 190]
# Method 1: Set intersection
common = list(set(list1) & set(list2))
print("Common elements:", common)
# Method 2: List comprehension
common2 = [x for x in list1 if x in list2]
print("Common (comprehension):", common2)
# Method 3: set.intersection()
common3 = set(list1).intersection(set(list2))
print("Common (method):", common3)Common elements: [11, 43, 190, 23]
Common (comprehension): [11, 190, 43, 23]
Common (method): {11, 43, 190, 23}🎓 Explanation
Set intersection (&) is most efficient O(n). Common elements are: 11, 190, 43, 23. Note: sets don't preserve order.
numbers = [21, 44, 22, 878, 55, 90, 17, 68, 69, 91]
# Method 1: Loop
even = []
odd = []
for num in numbers:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
print("Even numbers:", even)
print("Odd numbers:", odd)
# Method 2: List comprehension
even2 = [n for n in numbers if n % 2 == 0]
odd2 = [n for n in numbers if n % 2 != 0]
print("\nEven (comprehension):", even2)
print("Odd (comprehension):", odd2)Even numbers: [44, 22, 878, 90, 68] Odd numbers: [21, 55, 17, 69, 91] Even (comprehension): [44, 22, 878, 90, 68] Odd (comprehension): [21, 55, 17, 69, 91]
🎓 Explanation
num % 2 == 0 checks if even (remainder 0 when divided by 2). List comprehension is more Pythonic and concise.
numbers = [21, 44, 767, 98, 37]
# Using loop
total = 0
for num in numbers:
total += num
print("Sum:", total)
# Verify with built-in
print("Sum (built-in):", sum(numbers))Sum: 967 Sum (built-in): 967
🎓 Explanation
total += num is shorthand for total = total + num. Initialize accumulator to 0 before loop. 21+44+767+98+37 = 967.
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
# Test with different numbers
test_numbers = [10, -5, 0, 3.14, -0.5]
for n in test_numbers:
print(f"{n} is {check_number(n)}")10 is Positive -5 is Negative 0 is Zero 3.14 is Positive -0.5 is Negative
🎓 Explanation
Use if/elif/else chain. Order matters: check positive first, then negative, else must be zero. Works for floats too!
text = "Data Science and Machine Learning"
# Split into words
words = text.split()
# Method 1: Loop
max_length = 0
longest_word = ""
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print(f"Longest word: '{longest_word}'")
print(f"Length: {max_length}")
# Method 2: Using max with key
longest = max(words, key=len)
print(f"\nUsing max(): '{longest}' ({len(longest)} chars)")Longest word: 'Learning'
Length: 8
Using max(): 'Learning' ({len(longest)} chars)🎓 Explanation
split() breaks string into words by whitespace. max(words, key=len) finds the word with maximum length. "Learning" and "Science" both have 8 chars, but "Science" comes first.
# Sum of squares: 1² + 2² + 3² + ... + 10²
i = 1
sum_of_squares = 0
while i <= 10:
sum_of_squares += i ** 2
i += 1
print("Sum of squares (1 to 10):", sum_of_squares)
# Verify with formula: n(n+1)(2n+1)/6
n = 10
formula = n * (n + 1) * (2 * n + 1) // 6
print("Using formula:", formula)
# Show breakdown
print("\nBreakdown: 1+4+9+16+25+36+49+64+81+100 =",
1+4+9+16+25+36+49+64+81+100)Sum of squares (1 to 10): 385 Using formula: 385 Breakdown: 1+4+9+16+25+36+49+64+81+100 = 385
🎓 Explanation
i ** 2 squares the number. The formula for sum of squares is n(n+1)(2n+1)/6. For n=10: 10×11×21/6 = 385.