Code Challenge Python Loops
All, as you learn Python or any programming language that is, its a good practice to try to research and figure out a solution to the problem.
If you understand what the problem is, you are halfway there to solving it. You just need to write down the logic on how you can go out figuring out the answer manually then proceed to implement this.
Problem 1:
The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. Fill in the blanks to complete the function to satisfy these conditions.
If i give you the following see if you can figure out what goes in the blank.
def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = ___
# What is the additional condition to exit out of the loop?
if ___ :
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
___ += 1multiplication_table(3)
# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15multiplication_table(5)
# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25multiplication_table(8)
# Should print: 8x1=8 8x2=16 8x3=24
solution:
def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = multiplier * number
# What is the additional condition to exit out of the loop?
if result > 25:
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1multiplication_table(3)
# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15multiplication_table(5)
# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25multiplication_table(8)
# Should print: 8x1=8 8x2=16 8x3=24
Question 4
Get Khemlall Mangal’s stories in your inbox
Join Medium for free to get updates from this writer.
Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.
Challenge:
def sum_divisors(n):sum = 0return sum
Expectations:
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
Solution:
def sum_divisors(n):
sum = 0
divisors = [1]for i in range(1, n):
if n ==0:
return 1[n]
if (n % i)==0:
#sum =+ i
sum = sum + i
my_list =+i
divisors.append(i)
res = divisors[1:]
return sum








