Python Forum
Is it not possible to begin a for loop by 1 instead of 0
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it not possible to begin a for loop by 1 instead of 0
#1
Hi all ! With C++ no problem, I can begin a for loop by 1. I should like to delete all multipilcations by 0, as we find multiplication tables in a school.

print("MULTIPLICATION TABLE")

M=[[0,1,2,3,4,5,6,7,8,9],
   [1,1,1,1,1,1,1,1,1,1],
   [2,2,2,2,2,2,2,2,2,2],
   [3,3,3,3,3,3,3,3,3,3],
   [4,4,4,4,4,4,4,4,4,4],
   [5,5,5,5,5,5,5,5,5,5],
   [6,6,6,6,6,6,6,6,6,6],
   [7,7,7,7,7,7,7,7,7,7],
   [8,8,8,8,8,8,8,8,8,8],
   [9,9,9,9,9,9,9,9,9,9]]


for i in range (len(M)):
   for j in range (len(M)):
      M[i][j] =i*j


for x in range (len(M)):
   print(M[x])
Reply
#2
range accepts additional argument for starting value of sequence; you can use
for i in range(1, 4):
   print(i)
to get
Output:
1 2 3
Reply
#3
Thanks . With "for x in range (1,10)" in the print statement, I only suppressed the fist line. How to soppress leading zeros of all following lines ?
Here is my output:
/usr/bin/python3.5 /home/sylvain/PycharmProjects/Py4/lambda.py
MULTIPLICATION TABLE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54]
[0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
[0, 8, 16, 24, 32, 40, 48, 56, 64, 72]
[0, 9, 18, 27, 36, 45, 54, 63, 72, 81]
Reply
#4
print M[x][1:] instead of M[x]. Actually you dont need to use range to remove first elements, you can use
for row in M[1:]:
   print(row[1:])
Reply
#5
Thanks again. Now I have a good multiplication table. Last question: is it possible to avoid the matrix I have on the top of the file ?
Reply
#6
Of course, you can use list comprehension

multiplication_table = [[x*y for y in range(1,10)] for x in range(1,10)]
print(multiplication_table)
in any case, no need to create the table in advance and then change each element

multiplication_table = []
for x in range(1,10):
    new_row = []
    for y in range(1,10):
        new_row.append(x*y)
    multiplication_table.append(new_row)
print(multiplication_table)
Reply
#7
Thanks to Buran. Indeed python language is very strong, and therefor hard to leatn.
Reply
#8
These are the range arguments: range(start, stop, step).

In [1]: for num in range(2, 21, 2):
   ...:     print(num, end=" ")
   ...:     
2 4 6 8 10 12 14 16 18 20 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020