26,939 views
11 votes
11 votes
The function below takes one parameter: an integer (begin). Complete the function so that it prints every other number starting at begin down to and including 0, each on a separate line. There are two recommended approaches for this: (1) use a for loop over a range statement with a negative step value, or (2) use a while loop, printing and decrementing the value each time.

1 - def countdown_trigger (begin):
2 i = begin
3 while i < 0:
4 print(i)
5 i -= 1 Restore original file

User Avatar
by
2.4k points

2 Answers

15 votes
15 votes

Final answer:

To complete the function, we either use a corrected while loop that decrements by 2 or a for loop that iterates over a range with a step value of -2, to print every other number from the starting integer down to 0.

Step-by-step explanation:

The student's question wants to modify a given function to print every other number starting at a given integer begin down to and including 0. We can approach this using a while loop or a for loop.

While Loop Approach:

We correct the while loop condition to check that i is greater than or equal to 0 (since we're counting down), and modify the decrement step to decrease by 2:

def countdown_trigger(begin):
i = begin
while i >= 0:
print(i)
i -= 2

For Loop Approach:

Alternatively, we can use a for loop with a range that includes a negative step:

def countdown_trigger(begin):
for i in range(begin, -1, -2):
print(i)

Either of these solutions will successfully print every other number from the begin parameter down to 0 as specified by the student's question.

User DespeiL
by
3.2k points
7 votes
7 votes

Answer:

Follows are code to the given question:

def countdown_trigger(begin):#defining a method countdown_trigger that accepts a parameter

i = begin#defining variable that holds parameter value

while i >= 0:#defining while loop that check i value greater than equal to0

print(i)#print i value

i -= 2 # decreasing i value by 2

print(countdown_trigger(2))#calling method

Output:

2

0

None

Explanation:

In this code, a method "countdown_trigger" is declared, that accepts "begin" variable value in its parameters, and inside the method "i" declared, that holds parameters values.

By using a while loop, that checks "i" value which is greater than equal to 0, and prints "value" by decreasing a value by 2.

User Utoah
by
3.1k points