简体   繁体   中英

For-Loop printing entire range

I'm new to Python and learning about For Loops and wrote this code:

cars = [1, 2, 3, 4]
trucks = ['red', 'blue', 'green', 'white']

for numbers in cars:
    print (f"I can count: {numbers}")

for colors in trucks:
    print(f"I can list colors: {colors}")

new_list = []

for numbers in range(0, 4):
    new_list.append(numbers)

for numbers in new_list:
    print(f"I can count more: {new_list}!")

and I'm getting this result:

I can count: 1
I can count: 2
I can count: 3
I can count: 4
I can list colors: red
I can list colors: blue
I can list colors: green
I can list colors: white
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!
I can count more: [0, 1, 2, 3]!

For the "I can count more" part, how do I get it to list the range in numeric order:

I can count more: 1! 
I can count more: 2!, etc.

instead of printing the entire range in the line?

print(f"I can count more: {new_list}!")

should be

print(f"I can count more: {numbers}!")

since new_list is the entire list and numbers is your for variable defined in for numbers in new_list

Use "numbers" instead of "new_list". And do not iterate again and again over the same list as new_list contains the same items you are showing in the last loop. So,your code should be like this,

for numbers in range(0, 4):
    print(f"I can count more: {numbers}!")

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