Is there a better way in Python?

Question:

is there any better + faster to write this code:

number = 7

print("1:", number * 1)
print("2:", number * 2)
print("3:", number * 3)
print("4:", number * 4)
print("5:", number * 5)
print("6:", number * 6)
print("7:", number * 7)
print("8:", number * 8)
print("9:", number * 9)
print("10:", number * 10)

I hope an experienced python user can help me answer it! Thanks again, guys!

Asked By: Robotic Programmer

||

Answers:

You need to use for loops. This is how your code should look

number = 7
for i in range(1,11):
  print(str(i) + ': ' + str(number*i))
Answered By: Marko Borković

The use of loops and f-strings (assuming you have Python 3.6 or better) make this easy:

number = 7
for i in range(1, 11):
    print(f"{i}: {number * i}")

It generates, as desired:

1: 7
2: 14
3: 21
4: 28
5: 35
6: 42
7: 49
8: 56
9: 63
10: 70

Or, if you want to be "clever":

number = 7
print("n".join([f"{i}: {number * i}" for i in range(1, 11)]))

No, just joking, it will work but it’s not a good idea if you value readability 🙂

Answered By: paxdiablo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.