2

I've nested one for loop inside of another. The first loop simply iterates over the second loop five times; the second loop iterates over the same simple block of code five times.

In total, these loops should perform the same job twenty-five times.

x = 0

for y in range(0, 5,):
    for z in range(0, 5,):
        print(str(int(x + 1)) + ". Hello")

I expected the output to be:

1. Hello.
2. Hello.
3. Hello.
4. Hello.
5. Hello.

Twenty-five times, with each proceeding line increasing the number's value by one.

Instead, the output was:

1. Hello

This output repeated itself twenty-five times. How do I fix this problem and receive the output I want?

2
  • 1
    The number never changes because you never increment x Commented Jan 31, 2019 at 0:51
  • 1
    To be clear, you do add 1 to x in int(x + 1) but you don't store the result in x. Like some of the answers are suggesting, by separating the computation and storage x = x + 1 or x += 1 from printing the result print(str(x) + ". Hello"), you solve the problem. Some languages would allow you to do the whole thing in one go, but using the assignment in Python looks just like assigning a value to a named parameter, so print(x = x + 1) confuses Python and isn't very clear to begin with. Commented Jan 31, 2019 at 0:54

3 Answers 3

1

You aren't updating the value for x as you loop through.

Try this:

x = 0

for y in range(0, 5,):
    for z in range(0, 5,):
        x+=1
        print(str(x) + ". Hello")
Sign up to request clarification or add additional context in comments.

Comments

0

You are almost there. Just add one extra line

x = 0

for y in range(0, 5,):
    for z in range(0, 5,):
        print(str(int(x + 1)) + ". Hello")
        x += 1

1 Comment

Oh, thank you, I didn't realize I had to separately modify the variable's value when using it in a loop.
0

you can also use this :

   i = 0
for y in range(0, 5):
    for z in range(0, 5):
        i = i+1
        print(str(i) + "." " Hello.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.