简体   繁体   中英

Python 3.X: Call Outside Variable In Nested For Loop

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?

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")

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

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM