How do you use a for loop in python for multiplication?

If n = 6, then range[-1 * n] will be 0, 1, 2, 3, 4, 5. Those aren't the numbers you want, you want -6, -5, -4, -3, -2, -1. To get that sequence, you should use range[n, 0].

And you're supposed to multiply, not add. That also means you need to initialize the result with 1, not 0, because multiplying by 0 is always 0.

n = int[input['Enter a negative number: ']]
result = 1
for i in range[n, 0]:
    result *= i
print[result]

In the previous exercise, Solved tasks for Python lesson 4-5, we've practiced our knowledge from previous lessons.

In the previous tutorial, Solved tasks for Python lesson 4-5, we learned about conditions in Python. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have covered almost all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to be repeated. If we wanted a program to do something 100 times, we certainly wouldn't write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The while loop

The while loop is the simplest loop in Python. It simply repeats the commands in the block while the condition is True. It can contain an optional else: branch which will be executed when the condition is no longer True. The syntax of the loop is the following:

while [condition]:
    
else:
    

Let's create a simple example. Most of us know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:

{PYTHON}
print["Knock"]
print["Knock"]
print["Knock"]
print["Penny!"]

However, using loops, we no longer have to copy the same code over and over:

{PYTHON}
i = 0
while [i < 3]:
    print["Knock"]
    i += 1
print["Penny!"]
Console application
Knock
Knock
Knock
Penny!

We've introduced an auxiliary variable named i. The loop will run through 3 times. At the very beginning, i is set to zero, the loop then prints "Knock" and increases i by one. It continues in the same way with values one and two. Once i hits three, the condition i < 3 is no longer True and the loop terminates. Loops have the same indentation rules as conditions. Now, we can simply change value 3 to 10 in the loop declaration. The command will execute 10x without adding anything else to it. Surely, you now see that loops are a very powerful tool.

Now, let's put the variable incrementation to use. We'll print the numbers from one to ten. We want our output to be separated by spaces rather than lines. Therefore, we'll specify the end parameter for the print[] function and set the space character to it.

{PYTHON}
i = 1
while [i 

Chủ Đề