for i in range(3,33,3):
for j in range(1,11,1):
print("3 *", j, '=', i)
if j == 10:
break
This is the output that I am getting:
3 * 1 = 3
3 * 2 = 3
3 * 3 = 3
3 * 4 = 3
3 * 5 = 3
3 * 6 = 3
3 * 7 = 3
3 * 8 = 3
3 * 9 = 3
3 * 10 = 3
Could anyone please point out the error for me?
Change the i
to i * j
:
for i in range(3,33,3):
for j in range(1,11,1):
print("3 *", j, '=', i * j)
if j == 10:
break
Here is a simplified version:
for i in range(1, 11):
print(f"3 * {i} = {3 * i}")
Output:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
If you just want to print multiples of 3
, you don't need two loops. Just one loop from 1 to 10, and then multiply that by 3.
for i in range(1, 11):
j = i * 3
print('3 *', i, '=', j)
I believe you want the product as well as the multiplier, you can use enumerate for this. The code will look something like this:
for i,j in enumerate(range(3,33,3)):
print("3 *", i, '=', j)
You're doing nested loops*, but you meant to loop in parallel. You can do that with zip()
:
for i, j in zip(range(3, 33, 3), range(1, 11)):
print("3 *", j, '=', i)
Output:
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
Canonical question: How to iterate through two lists in parallel?
* This creates a Cartesian product , but it's cut short by the break
.
However, in this case it's simpler to just do the math, like in Barmar's answer .
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.